test.cc 720 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580
  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. detail::UrlComponents uc;
  13014. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  13015. EXPECT_TRUE(uc.scheme.empty());
  13016. EXPECT_EQ("example.com", uc.host);
  13017. EXPECT_EQ("/path", uc.path);
  13018. EXPECT_EQ("?q=1", uc.query);
  13019. }
  13020. {
  13021. detail::UrlComponents uc;
  13022. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  13023. EXPECT_TRUE(uc.host.empty());
  13024. EXPECT_EQ("/path", uc.path);
  13025. EXPECT_EQ("?q=1", uc.query);
  13026. }
  13027. {
  13028. detail::UrlComponents uc;
  13029. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  13030. EXPECT_EQ("example.com", uc.host);
  13031. EXPECT_EQ("8080", uc.port);
  13032. }
  13033. {
  13034. // Unix socket path — must not be parsed as host
  13035. detail::UrlComponents uc;
  13036. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  13037. EXPECT_TRUE(uc.host.empty());
  13038. }
  13039. {
  13040. detail::UrlComponents uc;
  13041. ASSERT_TRUE(detail::parse_url("", uc));
  13042. EXPECT_TRUE(uc.host.empty());
  13043. EXPECT_TRUE(uc.path.empty());
  13044. }
  13045. {
  13046. detail::UrlComponents uc;
  13047. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  13048. }
  13049. {
  13050. detail::UrlComponents uc;
  13051. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  13052. }
  13053. {
  13054. // Accepted by parse_url; callers restrict to http/https
  13055. detail::UrlComponents uc;
  13056. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  13057. EXPECT_EQ("ftp", uc.scheme);
  13058. }
  13059. {
  13060. detail::UrlComponents uc;
  13061. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  13062. }
  13063. {
  13064. detail::UrlComponents uc;
  13065. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  13066. }
  13067. }
  13068. TEST(ParseUrlTest, FragmentHandling) {
  13069. {
  13070. detail::UrlComponents uc;
  13071. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  13072. EXPECT_EQ("/path", uc.path);
  13073. EXPECT_TRUE(uc.query.empty());
  13074. }
  13075. {
  13076. detail::UrlComponents uc;
  13077. ASSERT_TRUE(detail::parse_url("#frag", uc));
  13078. EXPECT_TRUE(uc.path.empty());
  13079. EXPECT_TRUE(uc.query.empty());
  13080. }
  13081. }
  13082. TEST(ParseUrlTest, UserinfoHandling) {
  13083. // Userinfo with @ but no colon — host includes @
  13084. detail::UrlComponents uc;
  13085. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  13086. EXPECT_EQ("user@host.com", uc.host);
  13087. EXPECT_EQ("/path", uc.path);
  13088. }
  13089. TEST(ParseUrlTest, IPv6EdgeCases) {
  13090. {
  13091. detail::UrlComponents uc;
  13092. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  13093. EXPECT_TRUE(uc.scheme.empty());
  13094. EXPECT_EQ("::1", uc.host);
  13095. EXPECT_EQ("8080", uc.port);
  13096. }
  13097. {
  13098. // Zone ID '%25' is not in [a-fA-F0-9:]
  13099. detail::UrlComponents uc;
  13100. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  13101. }
  13102. }
  13103. TEST(ParseUrlTest, SchemeEdgeCases) {
  13104. {
  13105. detail::UrlComponents uc;
  13106. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  13107. }
  13108. {
  13109. detail::UrlComponents uc;
  13110. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  13111. }
  13112. {
  13113. detail::UrlComponents uc;
  13114. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  13115. }
  13116. }
  13117. TEST(ParseUrlTest, PortEdgeCases) {
  13118. {
  13119. detail::UrlComponents uc;
  13120. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  13121. EXPECT_TRUE(uc.port.empty());
  13122. EXPECT_EQ("/path", uc.path);
  13123. }
  13124. {
  13125. // parse_url accepts any port string; validation is done by parse_port
  13126. detail::UrlComponents uc;
  13127. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  13128. EXPECT_EQ("abc", uc.port);
  13129. }
  13130. }
  13131. TEST(ParseUrlTest, WebSocketPatterns) {
  13132. {
  13133. detail::UrlComponents uc;
  13134. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  13135. EXPECT_EQ("ws", uc.scheme);
  13136. EXPECT_EQ("echo.example.com", uc.host);
  13137. EXPECT_EQ("8080", uc.port);
  13138. EXPECT_EQ("/ws", uc.path);
  13139. }
  13140. {
  13141. detail::UrlComponents uc;
  13142. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  13143. EXPECT_EQ("wss", uc.scheme);
  13144. EXPECT_EQ("echo.example.com", uc.host);
  13145. EXPECT_TRUE(uc.port.empty());
  13146. EXPECT_EQ("/ws", uc.path);
  13147. }
  13148. }
  13149. TEST(ParseUrlTest, QueryOnly) {
  13150. detail::UrlComponents uc;
  13151. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  13152. EXPECT_TRUE(uc.host.empty());
  13153. EXPECT_TRUE(uc.path.empty());
  13154. EXPECT_EQ("?q=1&r=2", uc.query);
  13155. }
  13156. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  13157. detail::UrlComponents uc;
  13158. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  13159. EXPECT_TRUE(uc.scheme.empty());
  13160. EXPECT_EQ("example.com", uc.host);
  13161. EXPECT_EQ("443", uc.port);
  13162. EXPECT_EQ("/path", uc.path);
  13163. }
  13164. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  13165. // If ipv6 regex working, regex match codepath is taken.
  13166. // else port will default to 80 in Client impl
  13167. int clientImplMagicPort = 80;
  13168. int port = 4321;
  13169. // above ports must be different to avoid false negative
  13170. EXPECT_NE(clientImplMagicPort, port);
  13171. std::string ipV6TestURL = "http://[ff06::c3]";
  13172. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  13173. CLIENT_PRIVATE_KEY_FILE);
  13174. EXPECT_EQ(cli.port(), port);
  13175. }
  13176. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  13177. auto file_path = "./www/dir/index.html";
  13178. auto dir_path = "./www/dir";
  13179. detail::FileStat stat_file(file_path);
  13180. EXPECT_TRUE(stat_file.is_file());
  13181. EXPECT_FALSE(stat_file.is_dir());
  13182. detail::FileStat stat_dir(dir_path);
  13183. EXPECT_FALSE(stat_dir.is_file());
  13184. EXPECT_TRUE(stat_dir.is_dir());
  13185. }
  13186. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  13187. // IPv4 with default HTTP port (80)
  13188. EXPECT_EQ("example.com",
  13189. detail::make_host_and_port_string("example.com", 80, false));
  13190. // IPv4 with default HTTPS port (443)
  13191. EXPECT_EQ("example.com",
  13192. detail::make_host_and_port_string("example.com", 443, true));
  13193. // IPv4 with non-default HTTP port
  13194. EXPECT_EQ("example.com:8080",
  13195. detail::make_host_and_port_string("example.com", 8080, false));
  13196. // IPv4 with non-default HTTPS port
  13197. EXPECT_EQ("example.com:8443",
  13198. detail::make_host_and_port_string("example.com", 8443, true));
  13199. // IPv6 with default HTTP port (80)
  13200. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  13201. // IPv6 with default HTTPS port (443)
  13202. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  13203. // IPv6 with non-default HTTP port
  13204. EXPECT_EQ("[::1]:8080",
  13205. detail::make_host_and_port_string("::1", 8080, false));
  13206. // IPv6 with non-default HTTPS port
  13207. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  13208. // IPv6 full address with default port
  13209. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  13210. detail::make_host_and_port_string(
  13211. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  13212. // IPv6 full address with non-default port
  13213. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  13214. detail::make_host_and_port_string(
  13215. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  13216. // IPv6 localhost with non-default port
  13217. EXPECT_EQ("[::1]:3000",
  13218. detail::make_host_and_port_string("::1", 3000, false));
  13219. // IPv6 with zone ID (link-local address) with default port
  13220. EXPECT_EQ("[fe80::1%eth0]",
  13221. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  13222. // IPv6 with zone ID (link-local address) with non-default port
  13223. EXPECT_EQ("[fe80::1%eth0]:8080",
  13224. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  13225. // Edge case: Port 443 with is_ssl=false (should add port)
  13226. EXPECT_EQ("example.com:443",
  13227. detail::make_host_and_port_string("example.com", 443, false));
  13228. // Edge case: Port 80 with is_ssl=true (should add port)
  13229. EXPECT_EQ("example.com:80",
  13230. detail::make_host_and_port_string("example.com", 80, true));
  13231. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  13232. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  13233. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  13234. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  13235. // Security fix: Already bracketed IPv6 should not get double brackets
  13236. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  13237. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  13238. EXPECT_EQ("[::1]:8080",
  13239. detail::make_host_and_port_string("[::1]", 8080, false));
  13240. EXPECT_EQ("[2001:db8::1]:8080",
  13241. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  13242. EXPECT_EQ("[fe80::1%eth0]",
  13243. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  13244. EXPECT_EQ("[fe80::1%eth0]:8080",
  13245. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  13246. // Edge case: Empty host (should return as-is)
  13247. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  13248. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  13249. // This is a known limitation but shouldn't crash
  13250. EXPECT_EQ("[host:name]",
  13251. detail::make_host_and_port_string("host:name", 80, false));
  13252. // Port number edge cases (no validation, but should not crash)
  13253. EXPECT_EQ("example.com:0",
  13254. detail::make_host_and_port_string("example.com", 0, false));
  13255. EXPECT_EQ("example.com:-1",
  13256. detail::make_host_and_port_string("example.com", -1, false));
  13257. EXPECT_EQ("example.com:65535",
  13258. detail::make_host_and_port_string("example.com", 65535, false));
  13259. EXPECT_EQ("example.com:65536",
  13260. detail::make_host_and_port_string("example.com", 65536, false));
  13261. }
  13262. #ifdef CPPHTTPLIB_SSL_ENABLED
  13263. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  13264. httplib::SSLClient cli("roblox.com", 443);
  13265. cli.set_follow_location(true);
  13266. auto res = cli.Get("/");
  13267. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13268. EXPECT_EQ(StatusCode::OK_200, res->status);
  13269. }
  13270. #endif
  13271. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  13272. Server svr;
  13273. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  13274. EXPECT_EQ(res.status, 400);
  13275. });
  13276. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13277. auto se = detail::scope_exit([&] {
  13278. svr.stop();
  13279. thread.join();
  13280. ASSERT_FALSE(svr.is_running());
  13281. });
  13282. svr.wait_until_ready();
  13283. Client cli(HOST, PORT);
  13284. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  13285. }
  13286. TEST(InvalidHeaderCharsTest, is_field_name) {
  13287. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  13288. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  13289. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  13290. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  13291. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  13292. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  13293. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  13294. EXPECT_FALSE(detail::fields::is_field_name(""));
  13295. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  13296. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  13297. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  13298. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  13299. }
  13300. TEST(InvalidHeaderCharsTest, is_field_value) {
  13301. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  13302. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  13303. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  13304. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  13305. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  13306. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  13307. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  13308. EXPECT_TRUE(detail::fields::is_field_value(""));
  13309. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  13310. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  13311. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  13312. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  13313. EXPECT_TRUE(detail::fields::is_field_value("0"));
  13314. }
  13315. TEST(InvalidHeaderCharsTest, OnServer) {
  13316. Server svr;
  13317. svr.Get("/test_name", [&](const Request &req, Response &res) {
  13318. std::string header = "Not Set";
  13319. if (req.has_param("header")) { header = req.get_param_value("header"); }
  13320. res.set_header(header, "value");
  13321. res.set_content("Page Content Page Content", "text/plain");
  13322. });
  13323. svr.Get("/test_value", [&](const Request &req, Response &res) {
  13324. std::string header = "Not Set";
  13325. if (req.has_param("header")) { header = req.get_param_value("header"); }
  13326. res.set_header("X-Test", header);
  13327. res.set_content("Page Content Page Content", "text/plain");
  13328. });
  13329. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13330. auto se = detail::scope_exit([&] {
  13331. svr.stop();
  13332. thread.join();
  13333. ASSERT_FALSE(svr.is_running());
  13334. });
  13335. svr.wait_until_ready();
  13336. Client cli(HOST, PORT);
  13337. {
  13338. auto res = cli.Get(
  13339. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  13340. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13341. EXPECT_EQ("Page Content Page Content", res->body);
  13342. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  13343. }
  13344. {
  13345. auto res = cli.Get(
  13346. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  13347. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13348. EXPECT_EQ("Page Content Page Content", res->body);
  13349. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  13350. }
  13351. }
  13352. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  13353. auto handled = false;
  13354. Server svr;
  13355. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  13356. thread t = thread([&] { svr.listen(HOST, PORT); });
  13357. auto se = detail::scope_exit([&] {
  13358. svr.stop();
  13359. t.join();
  13360. ASSERT_FALSE(svr.is_running());
  13361. ASSERT_FALSE(handled);
  13362. });
  13363. svr.wait_until_ready();
  13364. auto req = "POST /test HTTP/1.1\r\n"
  13365. "Content-Length: x\r\n"
  13366. "\r\n";
  13367. std::string response;
  13368. ASSERT_TRUE(send_request(1, req, &response));
  13369. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  13370. response.substr(0, response.find("\r\n")));
  13371. }
  13372. #ifndef _WIN32
  13373. TEST(Expect100ContinueTest, ServerClosesConnection) {
  13374. static constexpr char reject[] = "Unauthorized";
  13375. static constexpr char accept[] = "Upload accepted";
  13376. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  13377. Server svr;
  13378. svr.set_expect_100_continue_handler(
  13379. [](const Request & /*req*/, Response &res) {
  13380. res.status = StatusCode::Unauthorized_401;
  13381. res.set_content(reject, "text/plain");
  13382. return res.status;
  13383. });
  13384. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  13385. res.set_content(accept, "text/plain");
  13386. });
  13387. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13388. auto se = detail::scope_exit([&] {
  13389. svr.stop();
  13390. thread.join();
  13391. ASSERT_FALSE(svr.is_running());
  13392. });
  13393. svr.wait_until_ready();
  13394. {
  13395. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  13396. curl_easy_init(), &curl_easy_cleanup};
  13397. ASSERT_NE(curl, nullptr);
  13398. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  13399. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  13400. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  13401. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  13402. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  13403. &curl_slist_free_all};
  13404. ASSERT_NE(list, nullptr);
  13405. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  13406. struct read_data {
  13407. size_t read_size;
  13408. size_t total_size;
  13409. } data = {0, total_size};
  13410. using read_callback_t =
  13411. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  13412. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  13413. void *userdata) -> size_t {
  13414. read_data *d = (read_data *)userdata;
  13415. if (!userdata || d->read_size >= d->total_size) { return 0; }
  13416. std::fill_n(ptr, size * nmemb, 'A');
  13417. d->read_size += size * nmemb;
  13418. return size * nmemb;
  13419. };
  13420. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  13421. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  13422. std::vector<char> buffer;
  13423. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  13424. using write_callback_t =
  13425. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  13426. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  13427. void *userdata) -> size_t {
  13428. std::vector<char> *buf = (std::vector<char> *)userdata;
  13429. buf->reserve(buf->size() + size * nmemb + 1);
  13430. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  13431. return size * nmemb;
  13432. };
  13433. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  13434. {
  13435. const auto res = curl_easy_perform(curl.get());
  13436. ASSERT_EQ(res, CURLE_OK);
  13437. }
  13438. {
  13439. auto response_code = long{};
  13440. const auto res =
  13441. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  13442. ASSERT_EQ(res, CURLE_OK);
  13443. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  13444. }
  13445. {
  13446. auto dl = curl_off_t{};
  13447. const auto res =
  13448. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  13449. ASSERT_EQ(res, CURLE_OK);
  13450. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  13451. }
  13452. {
  13453. buffer.push_back('\0');
  13454. ASSERT_STRCASEEQ(buffer.data(), reject);
  13455. }
  13456. }
  13457. }
  13458. #endif
  13459. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  13460. // Regression test for #2458.
  13461. //
  13462. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  13463. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  13464. // ticket can make the client socket spuriously readable during the
  13465. // 100-continue wait. If the readiness is mistaken for an incoming response,
  13466. // the client withholds the body and then blocks reading a response that never
  13467. // comes, failing with `Failed to read connection`.
  13468. //
  13469. // A correct client (like curl) sends the body once no `100 Continue` arrives
  13470. // within the timeout. This raw OpenSSL server deliberately never sends
  13471. // `100 Continue`; the client must still deliver the body and receive 200.
  13472. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  13473. signal(SIGPIPE, SIG_IGN);
  13474. const auto port = PORT + 4;
  13475. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13476. ASSERT_NE(srv, INVALID_SOCKET);
  13477. int opt = 1;
  13478. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  13479. sockaddr_in addr{};
  13480. addr.sin_family = AF_INET;
  13481. addr.sin_port = htons(static_cast<uint16_t>(port));
  13482. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13483. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  13484. ASSERT_EQ(0, ::listen(srv, 1));
  13485. std::atomic<size_t> server_body_bytes{0};
  13486. auto server_thread = std::thread([&] {
  13487. sockaddr_in cli_addr{};
  13488. socklen_t cli_len = sizeof(cli_addr);
  13489. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13490. if (cli == INVALID_SOCKET) { return; }
  13491. // Bound the lifetime of the server side so a buggy client (which never
  13492. // sends the body) cannot make this thread block forever on join.
  13493. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  13494. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  13495. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  13496. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  13497. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  13498. SSL *ssl = SSL_new(ctx);
  13499. SSL_set_fd(ssl, static_cast<int>(cli));
  13500. if (SSL_accept(ssl) > 0) {
  13501. // Read the request headers. Reading here also flushes the TLS 1.3
  13502. // session tickets to the client. Deliberately do NOT send
  13503. // `100 Continue`.
  13504. std::string buf;
  13505. char tmp[1024];
  13506. while (buf.find("\r\n\r\n") == std::string::npos) {
  13507. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  13508. if (n <= 0) { break; }
  13509. buf.append(tmp, static_cast<size_t>(n));
  13510. }
  13511. // A correct client sends the body now; count what arrives.
  13512. auto pos = buf.find("\r\n\r\n");
  13513. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  13514. while (body < 4096) {
  13515. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  13516. if (n <= 0) { break; }
  13517. body += static_cast<size_t>(n);
  13518. }
  13519. server_body_bytes = body;
  13520. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  13521. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  13522. SSL_shutdown(ssl);
  13523. }
  13524. SSL_free(ssl);
  13525. detail::close_socket(cli);
  13526. SSL_CTX_free(ctx);
  13527. });
  13528. auto se = detail::scope_exit([&] {
  13529. server_thread.join();
  13530. detail::close_socket(srv);
  13531. });
  13532. SSLClient cli("127.0.0.1", port);
  13533. cli.enable_server_certificate_verification(false);
  13534. cli.set_connection_timeout(5, 0);
  13535. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  13536. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  13537. std::string body(4096, 'A');
  13538. auto res = cli.Put("/api/test", body, "application/json");
  13539. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  13540. EXPECT_EQ(StatusCode::OK_200, res->status);
  13541. EXPECT_EQ(body.size(), server_body_bytes.load());
  13542. }
  13543. #endif
  13544. template <typename S, typename C>
  13545. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  13546. svr.Get("/stream", [&](const Request &, Response &res) {
  13547. auto data = new std::string("01234567890123456789");
  13548. res.set_content_provider(
  13549. data->size(), "text/plain",
  13550. [&, data](size_t offset, size_t length, DataSink &sink) {
  13551. const size_t DATA_CHUNK_SIZE = 4;
  13552. const auto &d = *data;
  13553. std::this_thread::sleep_for(std::chrono::seconds(1));
  13554. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  13555. return true;
  13556. },
  13557. [data](bool success) {
  13558. EXPECT_FALSE(success);
  13559. delete data;
  13560. });
  13561. });
  13562. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  13563. auto i = new size_t(0);
  13564. res.set_content_provider(
  13565. "text/plain",
  13566. [i](size_t, DataSink &sink) {
  13567. if (*i < 5) {
  13568. std::this_thread::sleep_for(std::chrono::seconds(1));
  13569. sink.write("abcd", 4);
  13570. (*i)++;
  13571. } else {
  13572. sink.done();
  13573. }
  13574. return true;
  13575. },
  13576. [i](bool success) {
  13577. EXPECT_FALSE(success);
  13578. delete i;
  13579. });
  13580. });
  13581. svr.Get("/chunked", [&](const Request &, Response &res) {
  13582. auto i = new size_t(0);
  13583. res.set_chunked_content_provider(
  13584. "text/plain",
  13585. [i](size_t, DataSink &sink) {
  13586. if (*i < 5) {
  13587. std::this_thread::sleep_for(std::chrono::seconds(1));
  13588. sink.os << "abcd";
  13589. (*i)++;
  13590. } else {
  13591. sink.done();
  13592. }
  13593. return true;
  13594. },
  13595. [i](bool success) {
  13596. EXPECT_FALSE(success);
  13597. delete i;
  13598. });
  13599. });
  13600. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  13601. auto se = detail::scope_exit([&] {
  13602. svr.stop();
  13603. listen_thread.join();
  13604. ASSERT_FALSE(svr.is_running());
  13605. });
  13606. svr.wait_until_ready();
  13607. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  13608. {
  13609. auto start = std::chrono::steady_clock::now();
  13610. auto res = cli.Get("/stream");
  13611. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  13612. std::chrono::steady_clock::now() - start)
  13613. .count();
  13614. ASSERT_FALSE(res);
  13615. EXPECT_EQ(Error::Read, res.error());
  13616. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  13617. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  13618. }
  13619. {
  13620. auto start = std::chrono::steady_clock::now();
  13621. auto res = cli.Get("/stream_without_length");
  13622. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  13623. std::chrono::steady_clock::now() - start)
  13624. .count();
  13625. ASSERT_FALSE(res);
  13626. EXPECT_EQ(Error::Read, res.error());
  13627. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  13628. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  13629. }
  13630. {
  13631. auto start = std::chrono::steady_clock::now();
  13632. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  13633. EXPECT_EQ("abcd", string(data, data_length));
  13634. return true;
  13635. });
  13636. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  13637. std::chrono::steady_clock::now() - start)
  13638. .count();
  13639. ASSERT_FALSE(res);
  13640. EXPECT_EQ(Error::Read, res.error());
  13641. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  13642. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  13643. }
  13644. }
  13645. TEST(MaxTimeoutTest, ContentStream) {
  13646. time_t timeout = 2000;
  13647. time_t threshold = 200;
  13648. Server svr;
  13649. Client cli("localhost", PORT);
  13650. max_timeout_test(svr, cli, timeout, threshold);
  13651. }
  13652. #ifdef CPPHTTPLIB_SSL_ENABLED
  13653. TEST(MaxTimeoutTest, ContentStreamSSL) {
  13654. time_t timeout = 2000;
  13655. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  13656. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13657. SSLClient cli("localhost", PORT);
  13658. cli.enable_server_certificate_verification(false);
  13659. max_timeout_test(svr, cli, timeout, threshold);
  13660. }
  13661. #endif
  13662. class EventDispatcher {
  13663. public:
  13664. EventDispatcher() {}
  13665. bool wait_event(DataSink *sink) {
  13666. unique_lock<mutex> lk(m_);
  13667. int id = id_;
  13668. // Wait with timeout to prevent hanging if client disconnects
  13669. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  13670. [&] { return cid_ == id; })) {
  13671. return false; // Timeout occurred
  13672. }
  13673. sink->write(message_.data(), message_.size());
  13674. return true;
  13675. }
  13676. void send_event(const string &message) {
  13677. lock_guard<mutex> lk(m_);
  13678. cid_ = id_++;
  13679. message_ = message;
  13680. cv_.notify_all();
  13681. }
  13682. private:
  13683. mutex m_;
  13684. condition_variable cv_;
  13685. atomic_int id_{0};
  13686. atomic_int cid_{-1};
  13687. string message_;
  13688. };
  13689. TEST(ClientInThreadTest, Issue2068) {
  13690. EventDispatcher ed;
  13691. Server svr;
  13692. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  13693. res.set_chunked_content_provider("text/event-stream",
  13694. [&](size_t /*offset*/, DataSink &sink) {
  13695. return ed.wait_event(&sink);
  13696. });
  13697. });
  13698. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  13699. svr.wait_until_ready();
  13700. thread event_thread([&] {
  13701. int id = 0;
  13702. while (svr.is_running()) {
  13703. this_thread::sleep_for(chrono::milliseconds(500));
  13704. std::stringstream ss;
  13705. ss << "data: " << id << "\n\n";
  13706. ed.send_event(ss.str());
  13707. id++;
  13708. }
  13709. });
  13710. auto se = detail::scope_exit([&] {
  13711. svr.stop();
  13712. listen_thread.join();
  13713. event_thread.join();
  13714. ASSERT_FALSE(svr.is_running());
  13715. });
  13716. {
  13717. auto client = detail::make_unique<Client>(HOST, PORT);
  13718. client->set_read_timeout(std::chrono::minutes(10));
  13719. std::atomic<bool> stop{false};
  13720. std::thread t([&] {
  13721. client->Get("/event1",
  13722. [&](const char *, size_t) -> bool { return !stop; });
  13723. });
  13724. std::this_thread::sleep_for(std::chrono::seconds(2));
  13725. stop = true;
  13726. client->stop();
  13727. t.join();
  13728. // Reset client after thread has finished
  13729. client.reset();
  13730. }
  13731. }
  13732. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  13733. auto handled = false;
  13734. Server svr;
  13735. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  13736. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13737. auto se = detail::scope_exit([&] {
  13738. svr.stop();
  13739. t.join();
  13740. ASSERT_FALSE(svr.is_running());
  13741. ASSERT_FALSE(handled);
  13742. });
  13743. svr.wait_until_ready();
  13744. // Two Content-Length headers with different values — must be rejected
  13745. auto req = "POST /test HTTP/1.1\r\n"
  13746. "Content-Length: 5\r\n"
  13747. "Content-Length: 10\r\n"
  13748. "\r\n"
  13749. "hello";
  13750. std::string response;
  13751. ASSERT_TRUE(send_request(1, req, &response));
  13752. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  13753. response.substr(0, response.find("\r\n")));
  13754. }
  13755. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  13756. auto handled = false;
  13757. Server svr;
  13758. svr.Post("/test", [&](const Request &, Response &res) {
  13759. handled = true;
  13760. res.set_content("ok", "text/plain");
  13761. });
  13762. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13763. auto se = detail::scope_exit([&] {
  13764. svr.stop();
  13765. t.join();
  13766. ASSERT_FALSE(svr.is_running());
  13767. ASSERT_TRUE(handled);
  13768. });
  13769. svr.wait_until_ready();
  13770. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  13771. auto req = "POST /test HTTP/1.1\r\n"
  13772. "Content-Length: 5\r\n"
  13773. "Content-Length: 5\r\n"
  13774. "\r\n"
  13775. "hello";
  13776. std::string response;
  13777. ASSERT_TRUE(send_request(1, req, &response));
  13778. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  13779. }
  13780. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  13781. Server svr;
  13782. svr.Get("/", [](const Request &req, Response &res) {
  13783. EXPECT_EQ(2U, req.trailers.size());
  13784. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  13785. // Denied
  13786. EXPECT_FALSE(req.has_trailer("Content-Length"));
  13787. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  13788. // Accepted
  13789. EXPECT_TRUE(req.has_trailer("X-Hello"));
  13790. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  13791. EXPECT_TRUE(req.has_trailer("X-World"));
  13792. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  13793. res.set_content("ok", "text/plain");
  13794. });
  13795. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13796. auto se = detail::scope_exit([&] {
  13797. svr.stop();
  13798. t.join();
  13799. ASSERT_FALSE(svr.is_running());
  13800. });
  13801. svr.wait_until_ready();
  13802. const std::string req = "GET / HTTP/1.1\r\n"
  13803. "Transfer-Encoding: chunked\r\n"
  13804. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  13805. "\r\n"
  13806. "0\r\n"
  13807. "Content-Length: 10\r\n"
  13808. "Host: internal.local\r\n"
  13809. "Content-Type: malicious/content\r\n"
  13810. "Cookie: any\r\n"
  13811. "Set-Cookie: any\r\n"
  13812. "X-Forwarded-For: attacker.com\r\n"
  13813. "X-Real-Ip: 1.1.1.1\r\n"
  13814. "X-Hello: hello\r\n"
  13815. "X-World: world\r\n"
  13816. "\r\n";
  13817. std::string res;
  13818. ASSERT_TRUE(send_request(1, req, &res));
  13819. }
  13820. // A direct client that is not listed in trusted_proxies must not be able to
  13821. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  13822. // the peer address on the actual TCP connection determines whether the
  13823. // header is honored.
  13824. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  13825. Server svr;
  13826. // Deliberately does NOT include the loopback address the test client
  13827. // actually connects from, so the direct connection is not a trusted proxy.
  13828. svr.set_trusted_proxies({"203.0.113.66"});
  13829. std::string observed_remote_addr;
  13830. svr.Get("/ip", [&](const Request &req, Response &res) {
  13831. observed_remote_addr = req.remote_addr;
  13832. res.set_content("ok", "text/plain");
  13833. });
  13834. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13835. auto se = detail::scope_exit([&] {
  13836. svr.stop();
  13837. t.join();
  13838. ASSERT_FALSE(svr.is_running());
  13839. });
  13840. svr.wait_until_ready();
  13841. Client cli(HOST, PORT);
  13842. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  13843. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13844. EXPECT_EQ(StatusCode::OK_200, res->status);
  13845. // The connecting peer is not a trusted proxy, so the spoofed header must be
  13846. // ignored entirely and the real connection-level address retained.
  13847. EXPECT_TRUE(observed_remote_addr == "::1" ||
  13848. observed_remote_addr == "127.0.0.1");
  13849. }
  13850. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  13851. Server svr;
  13852. std::string observed_remote_addr;
  13853. std::string observed_xff;
  13854. svr.Get("/ip", [&](const Request &req, Response &res) {
  13855. observed_remote_addr = req.remote_addr;
  13856. observed_xff = req.get_header_value("X-Forwarded-For");
  13857. res.set_content("ok", "text/plain");
  13858. });
  13859. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13860. auto se = detail::scope_exit([&] {
  13861. svr.stop();
  13862. t.join();
  13863. ASSERT_FALSE(svr.is_running());
  13864. });
  13865. svr.wait_until_ready();
  13866. Client cli(HOST, PORT);
  13867. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  13868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13869. EXPECT_EQ(StatusCode::OK_200, res->status);
  13870. EXPECT_EQ(observed_xff, "203.0.113.66");
  13871. EXPECT_TRUE(observed_remote_addr == "::1" ||
  13872. observed_remote_addr == "127.0.0.1");
  13873. }
  13874. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  13875. Server svr;
  13876. svr.set_trusted_proxies({"203.0.113.66"});
  13877. std::string observed_remote_addr;
  13878. std::string observed_xff;
  13879. svr.Get("/ip", [&](const Request &req, Response &res) {
  13880. observed_remote_addr = req.remote_addr;
  13881. observed_xff = req.get_header_value("X-Forwarded-For");
  13882. res.set_content("ok", "text/plain");
  13883. });
  13884. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13885. auto se = detail::scope_exit([&] {
  13886. svr.stop();
  13887. t.join();
  13888. ASSERT_FALSE(svr.is_running());
  13889. });
  13890. svr.wait_until_ready();
  13891. Client cli(HOST, PORT);
  13892. auto res = cli.Get("/ip");
  13893. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13894. EXPECT_EQ(StatusCode::OK_200, res->status);
  13895. EXPECT_EQ(observed_xff, "");
  13896. EXPECT_TRUE(observed_remote_addr == "::1" ||
  13897. observed_remote_addr == "127.0.0.1");
  13898. }
  13899. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  13900. Server svr;
  13901. // Include the loopback address the test client actually connects from, so
  13902. // the direct connection itself is recognized as the trusted proxy hop.
  13903. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  13904. std::string observed_remote_addr;
  13905. std::string observed_xff;
  13906. svr.Get("/ip", [&](const Request &req, Response &res) {
  13907. observed_remote_addr = req.remote_addr;
  13908. observed_xff = req.get_header_value("X-Forwarded-For");
  13909. res.set_content("ok", "text/plain");
  13910. });
  13911. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13912. auto se = detail::scope_exit([&] {
  13913. svr.stop();
  13914. t.join();
  13915. ASSERT_FALSE(svr.is_running());
  13916. });
  13917. svr.wait_until_ready();
  13918. Client cli(HOST, PORT);
  13919. auto res = cli.Get(
  13920. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  13921. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13922. EXPECT_EQ(StatusCode::OK_200, res->status);
  13923. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  13924. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  13925. }
  13926. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  13927. Server svr;
  13928. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  13929. std::string observed_remote_addr;
  13930. std::string observed_xff;
  13931. svr.Get("/ip", [&](const Request &req, Response &res) {
  13932. observed_remote_addr = req.remote_addr;
  13933. observed_xff = req.get_header_value("X-Forwarded-For");
  13934. res.set_content("ok", "text/plain");
  13935. });
  13936. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13937. auto se = detail::scope_exit([&] {
  13938. svr.stop();
  13939. t.join();
  13940. ASSERT_FALSE(svr.is_running());
  13941. });
  13942. svr.wait_until_ready();
  13943. Client cli(HOST, PORT);
  13944. auto res = cli.Get(
  13945. "/ip",
  13946. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  13947. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13948. EXPECT_EQ(StatusCode::OK_200, res->status);
  13949. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  13950. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  13951. }
  13952. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  13953. Server svr;
  13954. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  13955. std::string observed_remote_addr;
  13956. std::string observed_xff;
  13957. svr.Get("/ip", [&](const Request &req, Response &res) {
  13958. observed_remote_addr = req.remote_addr;
  13959. observed_xff = req.get_header_value("X-Forwarded-For");
  13960. res.set_content("ok", "text/plain");
  13961. });
  13962. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13963. auto se = detail::scope_exit([&] {
  13964. svr.stop();
  13965. t.join();
  13966. ASSERT_FALSE(svr.is_running());
  13967. });
  13968. svr.wait_until_ready();
  13969. Client cli(HOST, PORT);
  13970. auto res = cli.Get(
  13971. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  13972. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13973. EXPECT_EQ(StatusCode::OK_200, res->status);
  13974. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  13975. // by the closest hop) is used. The leftmost entry is fully client-controlled
  13976. // and must not be selected.
  13977. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  13978. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  13979. }
  13980. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  13981. Server svr;
  13982. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  13983. std::string observed_remote_addr;
  13984. svr.Get("/ip", [&](const Request &req, Response &res) {
  13985. observed_remote_addr = req.remote_addr;
  13986. res.set_content("ok", "text/plain");
  13987. });
  13988. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13989. auto se = detail::scope_exit([&] {
  13990. svr.stop();
  13991. t.join();
  13992. ASSERT_FALSE(svr.is_running());
  13993. });
  13994. svr.wait_until_ready();
  13995. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  13996. // a forged address and the trusted proxy's own address; the forged value must
  13997. // not win over the address the trusted proxy actually recorded.
  13998. Client cli(HOST, PORT);
  13999. auto res = cli.Get(
  14000. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  14001. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14002. EXPECT_EQ(StatusCode::OK_200, res->status);
  14003. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  14004. }
  14005. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  14006. Server svr;
  14007. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  14008. std::string observed_remote_addr;
  14009. std::string observed_xff;
  14010. svr.Get("/ip", [&](const Request &req, Response &res) {
  14011. observed_remote_addr = req.remote_addr;
  14012. observed_xff = req.get_header_value("X-Forwarded-For");
  14013. res.set_content("ok", "text/plain");
  14014. });
  14015. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14016. auto se = detail::scope_exit([&] {
  14017. svr.stop();
  14018. t.join();
  14019. ASSERT_FALSE(svr.is_running());
  14020. });
  14021. svr.wait_until_ready();
  14022. Client cli(HOST, PORT);
  14023. auto res = cli.Get(
  14024. "/ip",
  14025. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  14026. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14027. EXPECT_EQ(StatusCode::OK_200, res->status);
  14028. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  14029. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  14030. }
  14031. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  14032. Server svr;
  14033. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  14034. std::string observed_remote_addr;
  14035. std::string observed_xff;
  14036. svr.Get("/ip", [&](const Request &req, Response &res) {
  14037. observed_remote_addr = req.remote_addr;
  14038. observed_xff = req.get_header_value("X-Forwarded-For");
  14039. res.set_content("ok", "text/plain");
  14040. });
  14041. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14042. auto se = detail::scope_exit([&] {
  14043. svr.stop();
  14044. t.join();
  14045. ASSERT_FALSE(svr.is_running());
  14046. });
  14047. svr.wait_until_ready();
  14048. std::string raw_req =
  14049. "GET /ip HTTP/1.1\r\n"
  14050. "Host: localhost\r\n"
  14051. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  14052. "Connection: close\r\n"
  14053. "\r\n";
  14054. std::string out;
  14055. ASSERT_TRUE(send_request(5, raw_req, &out));
  14056. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  14057. // Header parser trims surrounding whitespace of the header value
  14058. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  14059. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  14060. }
  14061. // An X-Forwarded-For header whose value parses to zero IP segments must not
  14062. // crash the server (it used to call front() on an empty vector inside
  14063. // get_client_ip). The connection-level remote address must be retained instead.
  14064. static void run_malformed_xff_test(const std::string &xff_value) {
  14065. Server svr;
  14066. svr.set_trusted_proxies({"192.0.2.45"});
  14067. std::string observed_remote_addr;
  14068. svr.Get("/ip", [&](const Request &req, Response &res) {
  14069. observed_remote_addr = req.remote_addr;
  14070. res.set_content("ok", "text/plain");
  14071. });
  14072. int port = 0;
  14073. thread t = thread([&]() {
  14074. port = svr.bind_to_any_port(HOST);
  14075. svr.listen_after_bind();
  14076. });
  14077. auto se = detail::scope_exit([&] {
  14078. svr.stop();
  14079. t.join();
  14080. ASSERT_FALSE(svr.is_running());
  14081. });
  14082. svr.wait_until_ready();
  14083. Client cli(HOST, port);
  14084. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  14085. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14086. EXPECT_EQ(StatusCode::OK_200, res->status);
  14087. EXPECT_TRUE(observed_remote_addr == "::1" ||
  14088. observed_remote_addr == "127.0.0.1");
  14089. }
  14090. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  14091. run_malformed_xff_test("");
  14092. }
  14093. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  14094. run_malformed_xff_test(",");
  14095. }
  14096. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  14097. run_malformed_xff_test(", , ,");
  14098. }
  14099. #ifndef _WIN32
  14100. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  14101. Server svr;
  14102. svr.Post("/post", [&](const Request &req, Response &res) {
  14103. res.set_content(req.body, "text/plain");
  14104. });
  14105. svr.Put("/put", [&](const Request &req, Response &res) {
  14106. res.set_content(req.body, "text/plain");
  14107. });
  14108. svr.Patch("/patch", [&](const Request &req, Response &res) {
  14109. res.set_content(req.body, "text/plain");
  14110. });
  14111. svr.Delete("/delete", [&](const Request &req, Response &res) {
  14112. res.set_content(req.body, "text/plain");
  14113. });
  14114. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14115. auto se = detail::scope_exit([&] {
  14116. svr.stop();
  14117. t.join();
  14118. ASSERT_FALSE(svr.is_running());
  14119. });
  14120. svr.wait_until_ready();
  14121. std::string resp;
  14122. // POST without Content-Length
  14123. ASSERT_TRUE(send_request(5,
  14124. "POST /post HTTP/1.1\r\n"
  14125. "Host: localhost\r\n"
  14126. "Connection: close\r\n"
  14127. "\r\n",
  14128. &resp));
  14129. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  14130. // PUT without Content-Length
  14131. resp.clear();
  14132. ASSERT_TRUE(send_request(5,
  14133. "PUT /put HTTP/1.1\r\n"
  14134. "Host: localhost\r\n"
  14135. "Connection: close\r\n"
  14136. "\r\n",
  14137. &resp));
  14138. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  14139. // PATCH without Content-Length
  14140. resp.clear();
  14141. ASSERT_TRUE(send_request(5,
  14142. "PATCH /patch HTTP/1.1\r\n"
  14143. "Host: localhost\r\n"
  14144. "Connection: close\r\n"
  14145. "\r\n",
  14146. &resp));
  14147. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  14148. // DELETE without Content-Length
  14149. resp.clear();
  14150. ASSERT_TRUE(send_request(5,
  14151. "DELETE /delete HTTP/1.1\r\n"
  14152. "Host: localhost\r\n"
  14153. "Connection: close\r\n"
  14154. "\r\n",
  14155. &resp));
  14156. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  14157. }
  14158. #endif
  14159. //==============================================================================
  14160. // open_stream() Tests
  14161. //==============================================================================
  14162. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  14163. std::string result;
  14164. char buf[8192];
  14165. ssize_t n;
  14166. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  14167. result.append(buf, static_cast<size_t>(n));
  14168. }
  14169. return result;
  14170. }
  14171. // Mock stream for unit tests
  14172. class MockStream : public Stream {
  14173. public:
  14174. std::string data;
  14175. size_t pos = 0;
  14176. ssize_t error_after = -1; // -1 = no error
  14177. explicit MockStream(const std::string &d, ssize_t err = -1)
  14178. : data(d), error_after(err) {}
  14179. bool is_readable() const override { return true; }
  14180. bool wait_readable() const override { return true; }
  14181. bool wait_writable() const override { return true; }
  14182. ssize_t read(char *ptr, size_t size) override {
  14183. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  14184. if (pos >= data.size()) return 0;
  14185. size_t limit =
  14186. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  14187. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  14188. std::memcpy(ptr, data.data() + pos, to_read);
  14189. pos += to_read;
  14190. return static_cast<ssize_t>(to_read);
  14191. }
  14192. ssize_t write(const char *, size_t) override { return -1; }
  14193. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  14194. ip = "127.0.0.1";
  14195. port = 0;
  14196. }
  14197. void get_local_ip_and_port(std::string &ip, int &port) const override {
  14198. ip = "127.0.0.1";
  14199. port = 0;
  14200. }
  14201. socket_t socket() const override { return INVALID_SOCKET; }
  14202. time_t duration() const override { return 0; }
  14203. };
  14204. TEST(StreamHandleTest, Basic) {
  14205. ClientImpl::StreamHandle handle;
  14206. EXPECT_FALSE(handle.is_valid());
  14207. handle.response = detail::make_unique<Response>();
  14208. handle.error = Error::Connection;
  14209. EXPECT_FALSE(handle.is_valid());
  14210. handle.error = Error::Success;
  14211. EXPECT_TRUE(handle.is_valid());
  14212. }
  14213. TEST(BodyReaderTest, Basic) {
  14214. MockStream stream("Hello, World!");
  14215. detail::BodyReader reader;
  14216. reader.stream = &stream;
  14217. reader.content_length = 13;
  14218. char buf[32];
  14219. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  14220. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  14221. EXPECT_TRUE(reader.eof);
  14222. }
  14223. TEST(BodyReaderTest, NoStream) {
  14224. detail::BodyReader reader;
  14225. char buf[32];
  14226. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  14227. EXPECT_EQ(Error::Connection, reader.last_error);
  14228. }
  14229. TEST(BodyReaderTest, Error) {
  14230. MockStream stream("Hello, World!", 5);
  14231. detail::BodyReader reader;
  14232. reader.stream = &stream;
  14233. reader.content_length = 13;
  14234. char buf[32];
  14235. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  14236. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  14237. EXPECT_EQ(Error::Read, reader.last_error);
  14238. }
  14239. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  14240. // Mock-based StreamHandle tests relying on private internals are removed.
  14241. class OpenStreamTest : public ::testing::Test {
  14242. protected:
  14243. void SetUp() override {
  14244. svr_.Get("/hello", [](const Request &, Response &res) {
  14245. res.set_content("Hello World!", "text/plain");
  14246. });
  14247. svr_.Get("/large", [](const Request &, Response &res) {
  14248. res.set_content(std::string(10000, 'X'), "text/plain");
  14249. });
  14250. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  14251. res.set_content("Hello World!", "image/jpeg");
  14252. res.set_header("Content-Encoding", "UTF-8");
  14253. });
  14254. svr_.Get("/chunked", [](const Request &, Response &res) {
  14255. res.set_chunked_content_provider("text/plain",
  14256. [](size_t offset, DataSink &sink) {
  14257. if (offset < 15) {
  14258. sink.write("chunk", 5);
  14259. return true;
  14260. }
  14261. sink.done();
  14262. return true;
  14263. });
  14264. });
  14265. svr_.Get("/compressible", [](const Request &, Response &res) {
  14266. res.set_chunked_content_provider("text/plain", [](size_t offset,
  14267. DataSink &sink) {
  14268. if (offset < 100 * 1024) {
  14269. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  14270. sink.write(chunk.data(), chunk.size());
  14271. return true;
  14272. }
  14273. sink.done();
  14274. return true;
  14275. });
  14276. });
  14277. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  14278. [](const Request & /*req*/, Response &res) {
  14279. auto i = new int(0);
  14280. res.set_header("Trailer", "Content-Length, X-Allowed");
  14281. res.set_chunked_content_provider(
  14282. "text/plain",
  14283. [i](size_t /*offset*/, DataSink &sink) {
  14284. switch (*i) {
  14285. case 0: sink.os << "123"; break;
  14286. case 1: sink.os << "456"; break;
  14287. case 2: sink.os << "789"; break;
  14288. case 3: {
  14289. sink.done_with_trailer(
  14290. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  14291. } break;
  14292. }
  14293. (*i)++;
  14294. return true;
  14295. },
  14296. [i](bool success) {
  14297. EXPECT_TRUE(success);
  14298. delete i;
  14299. });
  14300. });
  14301. // Echo headers endpoint for header-related tests
  14302. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  14303. std::string body;
  14304. for (const auto &h : req.headers) {
  14305. body.append(h.first);
  14306. body.push_back(':');
  14307. body.append(h.second);
  14308. body.push_back('\n');
  14309. }
  14310. res.set_content(body, "text/plain");
  14311. });
  14312. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  14313. std::string body;
  14314. for (const auto &h : req.headers) {
  14315. body.append(h.first);
  14316. body.push_back(':');
  14317. body.append(h.second);
  14318. body.push_back('\n');
  14319. }
  14320. res.set_content(body, "text/plain");
  14321. });
  14322. port_ = svr_.bind_to_any_port("127.0.0.1");
  14323. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  14324. svr_.wait_until_ready();
  14325. }
  14326. void TearDown() override {
  14327. svr_.stop();
  14328. if (thread_.joinable()) thread_.join();
  14329. }
  14330. Server svr_;
  14331. std::thread thread_;
  14332. int port_ = 0;
  14333. };
  14334. TEST_F(OpenStreamTest, Basic) {
  14335. Client cli("127.0.0.1", port_);
  14336. auto handle = cli.open_stream("GET", "/hello");
  14337. EXPECT_TRUE(handle.is_valid());
  14338. EXPECT_EQ("Hello World!", read_all(handle));
  14339. }
  14340. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  14341. Client cli("127.0.0.1", port_);
  14342. auto handle = cli.open_stream("GET", "/unknown-encoding");
  14343. ASSERT_TRUE(handle.is_valid());
  14344. EXPECT_EQ("Hello World!", read_all(handle));
  14345. }
  14346. TEST_F(OpenStreamTest, SmallBuffer) {
  14347. Client cli("127.0.0.1", port_);
  14348. auto handle = cli.open_stream("GET", "/hello");
  14349. std::string result;
  14350. char buf[4];
  14351. ssize_t n;
  14352. while ((n = handle.read(buf, sizeof(buf))) > 0)
  14353. result.append(buf, static_cast<size_t>(n));
  14354. EXPECT_EQ("Hello World!", result);
  14355. }
  14356. TEST_F(OpenStreamTest, DefaultHeaders) {
  14357. Client cli("127.0.0.1", port_);
  14358. // open_stream GET should include Host, User-Agent and Accept-Encoding
  14359. {
  14360. auto handle = cli.open_stream("GET", "/echo-headers");
  14361. ASSERT_TRUE(handle.is_valid());
  14362. auto body = read_all(handle);
  14363. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  14364. std::string::npos);
  14365. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  14366. std::string::npos);
  14367. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  14368. }
  14369. // open_stream POST with body and no explicit content_type should NOT add
  14370. // text/plain Content-Type (behavior differs from non-streaming path), but
  14371. // should include Content-Length
  14372. {
  14373. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  14374. ASSERT_TRUE(handle.is_valid());
  14375. auto body = read_all(handle);
  14376. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  14377. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  14378. }
  14379. // open_stream POST with explicit Content-Type should preserve it
  14380. {
  14381. auto handle = cli.open_stream("POST", "/echo-headers", {},
  14382. {{"Content-Type", "application/custom"}},
  14383. "{}", "application/custom");
  14384. ASSERT_TRUE(handle.is_valid());
  14385. auto body = read_all(handle);
  14386. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  14387. }
  14388. // User-specified User-Agent must not be overwritten for stream API
  14389. {
  14390. auto handle = cli.open_stream("GET", "/echo-headers", {},
  14391. {{"User-Agent", "MyAgent/1.2"}});
  14392. ASSERT_TRUE(handle.is_valid());
  14393. auto body = read_all(handle);
  14394. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  14395. }
  14396. }
  14397. TEST_F(OpenStreamTest, Large) {
  14398. Client cli("127.0.0.1", port_);
  14399. auto handle = cli.open_stream("GET", "/large");
  14400. EXPECT_EQ(10000u, read_all(handle).size());
  14401. }
  14402. TEST_F(OpenStreamTest, ConnectionError) {
  14403. Client cli("127.0.0.1", 9999);
  14404. auto handle = cli.open_stream("GET", "/hello");
  14405. EXPECT_FALSE(handle.is_valid());
  14406. }
  14407. TEST_F(OpenStreamTest, Chunked) {
  14408. Client cli("127.0.0.1", port_);
  14409. auto handle = cli.open_stream("GET", "/chunked");
  14410. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  14411. "Transfer-Encoding") == "chunked");
  14412. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  14413. }
  14414. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  14415. Client cli("127.0.0.1", port_);
  14416. auto handle =
  14417. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  14418. ASSERT_TRUE(handle.is_valid());
  14419. // Consume body to allow trailers to be received/parsed
  14420. auto body = read_all(handle);
  14421. // Explicitly parse trailers (ensure trailers are available for assertion)
  14422. handle.parse_trailers_if_needed();
  14423. EXPECT_EQ(std::string("123456789"), body);
  14424. // The response should include a Trailer header declaring both names
  14425. ASSERT_TRUE(handle.response);
  14426. EXPECT_TRUE(handle.response->has_header("Trailer"));
  14427. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  14428. handle.response->get_header_value("Trailer"));
  14429. // Prohibited trailer must not be present
  14430. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  14431. // Allowed trailer should be present
  14432. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  14433. EXPECT_EQ(std::string("yes"),
  14434. handle.response->get_trailer_value("X-Allowed"));
  14435. // Verify trailers are NOT present as regular headers
  14436. EXPECT_EQ(std::string(""),
  14437. handle.response->get_header_value("Content-Length"));
  14438. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  14439. }
  14440. static std::thread serve_single_response(std::promise<int> &port_promise,
  14441. const std::string &response) {
  14442. return std::thread([&port_promise, response] {
  14443. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  14444. default_socket_options(srv);
  14445. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  14446. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  14447. sockaddr_in addr{};
  14448. addr.sin_family = AF_INET;
  14449. addr.sin_port = htons(0); // Let OS assign a free port
  14450. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  14451. int opt = 1;
  14452. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  14453. #ifdef _WIN32
  14454. reinterpret_cast<const char *>(&opt),
  14455. #else
  14456. &opt,
  14457. #endif
  14458. sizeof(opt));
  14459. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  14460. ::listen(srv, 1) != 0) {
  14461. port_promise.set_value(-1);
  14462. detail::close_socket(srv);
  14463. return;
  14464. }
  14465. socklen_t addr_len = sizeof(addr);
  14466. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  14467. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  14468. sockaddr_in cli_addr{};
  14469. socklen_t cli_len = sizeof(cli_addr);
  14470. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  14471. if (cli != INVALID_SOCKET) {
  14472. // Read the complete HTTP request (until the blank line that terminates
  14473. // headers) before sending the response. If the server closes the socket
  14474. // while the client's request data is still unread in the kernel receive
  14475. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  14476. // connection on both sides: it discards the client's receive buffer
  14477. // (which already holds our response) and causes any in-progress write on
  14478. // the client to fail with ECONNRESET. Reading all request data first
  14479. // ensures close() emits a graceful FIN.
  14480. {
  14481. char rbuf[256];
  14482. std::string req;
  14483. while (req.find("\r\n\r\n") == std::string::npos) {
  14484. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  14485. if (n <= 0) { break; }
  14486. req.append(rbuf, static_cast<size_t>(n));
  14487. }
  14488. }
  14489. ::send(cli,
  14490. #ifdef _WIN32
  14491. static_cast<const char *>(response.c_str()),
  14492. static_cast<int>(response.size()),
  14493. #else
  14494. response.c_str(), response.size(),
  14495. #endif
  14496. 0);
  14497. detail::close_socket(cli);
  14498. }
  14499. detail::close_socket(srv);
  14500. });
  14501. }
  14502. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  14503. #ifndef _WIN32
  14504. signal(SIGPIPE, SIG_IGN);
  14505. #endif
  14506. std::promise<int> port_promise;
  14507. auto port_future = port_promise.get_future();
  14508. auto server_thread =
  14509. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  14510. "Content-Type: text/plain\r\n"
  14511. "Content-Length: not-a-number\r\n"
  14512. "Connection: close\r\n"
  14513. "\r\n"
  14514. "hello");
  14515. auto port = port_future.get();
  14516. ASSERT_GT(port, 0);
  14517. Client cli("127.0.0.1", port);
  14518. auto handle = cli.open_stream("GET", "/");
  14519. EXPECT_FALSE(handle.is_valid());
  14520. server_thread.join();
  14521. }
  14522. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  14523. #ifndef _WIN32
  14524. signal(SIGPIPE, SIG_IGN);
  14525. #endif
  14526. std::promise<int> port_promise;
  14527. auto port_future = port_promise.get_future();
  14528. auto server_thread = serve_single_response(
  14529. port_promise, "HTTP/1.1 200 OK\r\n"
  14530. "Content-Type: text/plain\r\n"
  14531. "Content-Length: 99999999999999999999999999\r\n"
  14532. "Connection: close\r\n"
  14533. "\r\n"
  14534. "hello");
  14535. auto port = port_future.get();
  14536. ASSERT_GT(port, 0);
  14537. // Historically std::stoull would throw std::out_of_range here and crash
  14538. // the process, then parsing silently clamped to a bogus framing length and
  14539. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  14540. // so the stream fails to open, matching the not-a-number case above. The
  14541. // process still must NOT terminate.
  14542. Client cli("127.0.0.1", port);
  14543. auto handle = cli.open_stream("GET", "/");
  14544. EXPECT_FALSE(handle.is_valid());
  14545. server_thread.join();
  14546. }
  14547. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  14548. TEST_F(OpenStreamTest, Gzip) {
  14549. Client cli("127.0.0.1", port_);
  14550. auto handle = cli.open_stream("GET", "/compressible", {},
  14551. {{"Accept-Encoding", "gzip"}});
  14552. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  14553. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  14554. }
  14555. #endif
  14556. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  14557. TEST_F(OpenStreamTest, Brotli) {
  14558. Client cli("127.0.0.1", port_);
  14559. auto handle =
  14560. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  14561. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  14562. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  14563. }
  14564. #endif
  14565. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  14566. TEST_F(OpenStreamTest, Zstd) {
  14567. Client cli("127.0.0.1", port_);
  14568. auto handle = cli.open_stream("GET", "/compressible", {},
  14569. {{"Accept-Encoding", "zstd"}});
  14570. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  14571. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  14572. }
  14573. #endif
  14574. #ifdef CPPHTTPLIB_SSL_ENABLED
  14575. class SSLOpenStreamTest : public ::testing::Test {
  14576. protected:
  14577. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  14578. void SetUp() override {
  14579. svr_.Get("/hello", [](const Request &, Response &res) {
  14580. res.set_content("Hello SSL World!", "text/plain");
  14581. });
  14582. svr_.Get("/chunked", [](const Request &, Response &res) {
  14583. res.set_chunked_content_provider("text/plain",
  14584. [](size_t offset, DataSink &sink) {
  14585. if (offset < 15) {
  14586. sink.write("chunk", 5);
  14587. return true;
  14588. }
  14589. sink.done();
  14590. return true;
  14591. });
  14592. });
  14593. svr_.Post("/echo", [](const Request &req, Response &res) {
  14594. res.set_content(req.body, req.get_header_value("Content-Type"));
  14595. });
  14596. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  14597. std::string body = req.body;
  14598. res.set_chunked_content_provider(
  14599. "text/plain", [body](size_t offset, DataSink &sink) {
  14600. if (offset < body.size()) {
  14601. sink.write(body.data() + offset, body.size() - offset);
  14602. }
  14603. sink.done();
  14604. return true;
  14605. });
  14606. });
  14607. port_ = svr_.bind_to_any_port("127.0.0.1");
  14608. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  14609. svr_.wait_until_ready();
  14610. }
  14611. void TearDown() override {
  14612. svr_.stop();
  14613. if (thread_.joinable()) thread_.join();
  14614. }
  14615. SSLServer svr_;
  14616. std::thread thread_;
  14617. int port_ = 0;
  14618. };
  14619. TEST_F(SSLOpenStreamTest, Basic) {
  14620. SSLClient cli("127.0.0.1", port_);
  14621. cli.enable_server_certificate_verification(false);
  14622. auto handle = cli.open_stream("GET", "/hello");
  14623. ASSERT_TRUE(handle.is_valid());
  14624. EXPECT_EQ("Hello SSL World!", read_all(handle));
  14625. }
  14626. TEST_F(SSLOpenStreamTest, Chunked) {
  14627. SSLClient cli("127.0.0.1", port_);
  14628. cli.enable_server_certificate_verification(false);
  14629. auto handle = cli.open_stream("GET", "/chunked");
  14630. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  14631. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  14632. "Transfer-Encoding") == "chunked");
  14633. auto body = read_all(handle);
  14634. EXPECT_EQ("chunkchunkchunk", body);
  14635. }
  14636. TEST_F(SSLOpenStreamTest, Post) {
  14637. SSLClient cli("127.0.0.1", port_);
  14638. cli.enable_server_certificate_verification(false);
  14639. auto handle =
  14640. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  14641. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  14642. EXPECT_EQ(200, handle.response->status);
  14643. auto body = read_all(handle);
  14644. EXPECT_EQ("Hello SSL POST", body);
  14645. }
  14646. TEST_F(SSLOpenStreamTest, PostChunked) {
  14647. SSLClient cli("127.0.0.1", port_);
  14648. cli.enable_server_certificate_verification(false);
  14649. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  14650. "Chunked SSL Data", "text/plain");
  14651. ASSERT_TRUE(handle.is_valid());
  14652. EXPECT_EQ(200, handle.response->status);
  14653. auto body = read_all(handle);
  14654. EXPECT_EQ("Chunked SSL Data", body);
  14655. }
  14656. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  14657. // Content-Length is terminated by the server closing the connection. When the
  14658. // SSL peer sends a close_notify after the body, the client must treat it as a
  14659. // clean EOF and return a successful response rather than an error.
  14660. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  14661. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14662. ASSERT_TRUE(svr.is_valid());
  14663. svr.set_keep_alive_max_count(1);
  14664. const std::string expected_body = "Hello from connection-close response!";
  14665. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  14666. res.set_content_provider("text/plain",
  14667. [&](size_t offset, DataSink &sink) -> bool {
  14668. if (offset < expected_body.size()) {
  14669. sink.write(expected_body.data() + offset,
  14670. expected_body.size() - offset);
  14671. }
  14672. sink.done();
  14673. return true;
  14674. });
  14675. });
  14676. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  14677. auto se = detail::scope_exit([&] {
  14678. svr.stop();
  14679. listen_thread.join();
  14680. ASSERT_FALSE(svr.is_running());
  14681. });
  14682. svr.wait_until_ready();
  14683. SSLClient cli(HOST, PORT);
  14684. cli.enable_server_certificate_verification(false);
  14685. auto res = cli.Get("/no-content-length");
  14686. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  14687. EXPECT_EQ(StatusCode::OK_200, res->status);
  14688. EXPECT_EQ(expected_body, res->body);
  14689. }
  14690. #endif // CPPHTTPLIB_SSL_ENABLED
  14691. //==============================================================================
  14692. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  14693. // results for various scenarios.
  14694. //==============================================================================
  14695. TEST(ParityTest, GetVsOpenStream) {
  14696. Server svr;
  14697. const std::string path = "/parity";
  14698. const std::string content = "Parity test content: hello world";
  14699. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  14700. res.set_content(content, "text/plain");
  14701. });
  14702. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14703. auto se = detail::scope_exit([&] {
  14704. svr.stop();
  14705. t.join();
  14706. ASSERT_FALSE(svr.is_running());
  14707. });
  14708. svr.wait_until_ready();
  14709. Client cli(HOST, PORT);
  14710. // Non-stream path
  14711. auto r1 = cli.Get(path);
  14712. ASSERT_TRUE(r1);
  14713. EXPECT_EQ(StatusCode::OK_200, r1->status);
  14714. // Stream path
  14715. auto h = cli.open_stream("GET", path);
  14716. ASSERT_TRUE(h.is_valid());
  14717. EXPECT_EQ(r1->body, read_all(h));
  14718. }
  14719. // Helper to compress data with provided compressor type T
  14720. template <typename Compressor>
  14721. static std::string compress_payload_for_parity(const std::string &in) {
  14722. std::string out;
  14723. Compressor compressor;
  14724. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  14725. [&](const char *data, size_t n) {
  14726. out.append(data, n);
  14727. return true;
  14728. });
  14729. EXPECT_TRUE(ok);
  14730. return out;
  14731. }
  14732. // Helper function for compression parity tests
  14733. template <typename Compressor>
  14734. static void test_compression_parity(const std::string &original,
  14735. const std::string &path,
  14736. const std::string &encoding) {
  14737. const std::string compressed =
  14738. compress_payload_for_parity<Compressor>(original);
  14739. Server svr;
  14740. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  14741. res.set_content(compressed, "application/octet-stream");
  14742. res.set_header("Content-Encoding", encoding);
  14743. });
  14744. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  14745. auto se = detail::scope_exit([&] {
  14746. svr.stop();
  14747. t.join();
  14748. ASSERT_FALSE(svr.is_running());
  14749. });
  14750. svr.wait_until_ready();
  14751. Client cli(HOST, PORT);
  14752. // Non-streaming
  14753. {
  14754. auto res = cli.Get(path);
  14755. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14756. EXPECT_EQ(StatusCode::OK_200, res->status);
  14757. EXPECT_EQ(original, res->body);
  14758. }
  14759. // Streaming
  14760. {
  14761. auto h = cli.open_stream("GET", path);
  14762. ASSERT_TRUE(h.is_valid());
  14763. EXPECT_EQ(original, read_all(h));
  14764. }
  14765. }
  14766. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  14767. TEST(ParityTest, Gzip) {
  14768. test_compression_parity<detail::gzip_compressor>(
  14769. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  14770. }
  14771. #endif
  14772. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  14773. TEST(ParityTest, Brotli) {
  14774. test_compression_parity<detail::brotli_compressor>(
  14775. "Hello, brotli parity test payload", "/parity-br", "br");
  14776. }
  14777. #endif
  14778. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  14779. TEST(ParityTest, Zstd) {
  14780. test_compression_parity<detail::zstd_compressor>(
  14781. "Zstandard parity test payload", "/parity-zstd", "zstd");
  14782. }
  14783. #endif
  14784. //==============================================================================
  14785. // New Stream API Tests
  14786. //==============================================================================
  14787. inline std::string read_body(httplib::stream::Result &result) {
  14788. std::string body;
  14789. while (result.next()) {
  14790. body.append(result.data(), result.size());
  14791. }
  14792. return body;
  14793. }
  14794. TEST(ClientConnectionTest, Basic) {
  14795. httplib::ClientConnection conn;
  14796. EXPECT_FALSE(conn.is_open());
  14797. conn.sock = 1;
  14798. EXPECT_TRUE(conn.is_open());
  14799. httplib::ClientConnection conn2(std::move(conn));
  14800. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  14801. conn2.sock = INVALID_SOCKET;
  14802. }
  14803. // Unified test server for all stream::* tests
  14804. class StreamApiTest : public ::testing::Test {
  14805. protected:
  14806. void SetUp() override {
  14807. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  14808. res.set_content("Hello World!", "text/plain");
  14809. });
  14810. svr_.Get("/echo-params",
  14811. [](const httplib::Request &req, httplib::Response &res) {
  14812. std::string r;
  14813. for (const auto &p : req.params) {
  14814. if (!r.empty()) r += "&";
  14815. r += p.first + "=" + p.second;
  14816. }
  14817. res.set_content(r, "text/plain");
  14818. });
  14819. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  14820. res.set_content(req.body, req.get_header_value("Content-Type"));
  14821. });
  14822. svr_.Post("/echo-headers",
  14823. [](const httplib::Request &req, httplib::Response &res) {
  14824. std::string r;
  14825. for (const auto &h : req.headers)
  14826. r += h.first + ": " + h.second + "\n";
  14827. res.set_content(r, "text/plain");
  14828. });
  14829. svr_.Post("/echo-params",
  14830. [](const httplib::Request &req, httplib::Response &res) {
  14831. std::string r = "params:";
  14832. for (const auto &p : req.params)
  14833. r += p.first + "=" + p.second + ";";
  14834. res.set_content(r + " body:" + req.body, "text/plain");
  14835. });
  14836. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  14837. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  14838. });
  14839. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  14840. res.set_content("PUT:" + req.body, "text/plain");
  14841. });
  14842. svr_.Patch("/echo",
  14843. [](const httplib::Request &req, httplib::Response &res) {
  14844. res.set_content("PATCH:" + req.body, "text/plain");
  14845. });
  14846. svr_.Delete(
  14847. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  14848. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  14849. "text/plain");
  14850. });
  14851. svr_.Get("/head-test",
  14852. [](const httplib::Request &, httplib::Response &res) {
  14853. res.set_content("body for HEAD", "text/plain");
  14854. });
  14855. svr_.Options("/options",
  14856. [](const httplib::Request &, httplib::Response &res) {
  14857. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  14858. });
  14859. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  14860. svr_.wait_until_ready();
  14861. }
  14862. void TearDown() override {
  14863. svr_.stop();
  14864. if (thread_.joinable()) thread_.join();
  14865. }
  14866. httplib::Server svr_;
  14867. std::thread thread_;
  14868. };
  14869. // stream::Get tests
  14870. TEST_F(StreamApiTest, GetBasic) {
  14871. httplib::Client cli(HOST, PORT);
  14872. auto result = httplib::stream::Get(cli, "/hello");
  14873. ASSERT_TRUE(result.is_valid());
  14874. EXPECT_EQ(200, result.status());
  14875. EXPECT_EQ("Hello World!", read_body(result));
  14876. }
  14877. TEST_F(StreamApiTest, GetWithParams) {
  14878. httplib::Client cli(HOST, PORT);
  14879. httplib::Params params{{"foo", "bar"}};
  14880. auto result = httplib::stream::Get(cli, "/echo-params", params);
  14881. ASSERT_TRUE(result.is_valid());
  14882. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  14883. }
  14884. TEST_F(StreamApiTest, GetConnectionError) {
  14885. httplib::Client cli(HOST, 9999);
  14886. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  14887. }
  14888. TEST_F(StreamApiTest, Get404) {
  14889. httplib::Client cli(HOST, PORT);
  14890. auto result = httplib::stream::Get(cli, "/nonexistent");
  14891. EXPECT_TRUE(result.is_valid());
  14892. EXPECT_EQ(404, result.status());
  14893. }
  14894. // stream::Post tests
  14895. TEST_F(StreamApiTest, PostBasic) {
  14896. httplib::Client cli(HOST, PORT);
  14897. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  14898. "application/json");
  14899. ASSERT_TRUE(result.is_valid());
  14900. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  14901. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  14902. }
  14903. TEST_F(StreamApiTest, PostWithHeaders) {
  14904. httplib::Client cli(HOST, PORT);
  14905. httplib::Headers headers{{"X-Custom", "value"}};
  14906. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  14907. "text/plain");
  14908. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  14909. }
  14910. TEST_F(StreamApiTest, PostWithParams) {
  14911. httplib::Client cli(HOST, PORT);
  14912. httplib::Params params{{"k", "v"}};
  14913. auto result =
  14914. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  14915. auto body = read_body(result);
  14916. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  14917. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  14918. }
  14919. TEST_F(StreamApiTest, PostLarge) {
  14920. httplib::Client cli(HOST, PORT);
  14921. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  14922. size_t total = 0;
  14923. while (result.next()) {
  14924. total += result.size();
  14925. }
  14926. EXPECT_EQ(100u * 1024u, total);
  14927. }
  14928. // stream::Put/Patch tests
  14929. TEST_F(StreamApiTest, PutAndPatch) {
  14930. httplib::Client cli(HOST, PORT);
  14931. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  14932. EXPECT_EQ("PUT:test", read_body(put));
  14933. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  14934. EXPECT_EQ("PATCH:test", read_body(patch));
  14935. }
  14936. // stream::Delete tests
  14937. TEST_F(StreamApiTest, Delete) {
  14938. httplib::Client cli(HOST, PORT);
  14939. auto del1 = httplib::stream::Delete(cli, "/resource");
  14940. EXPECT_EQ("Deleted", read_body(del1));
  14941. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  14942. EXPECT_EQ("Deleted:data", read_body(del2));
  14943. }
  14944. // stream::Head/Options tests
  14945. TEST_F(StreamApiTest, HeadAndOptions) {
  14946. httplib::Client cli(HOST, PORT);
  14947. auto head = httplib::stream::Head(cli, "/head-test");
  14948. EXPECT_TRUE(head.is_valid());
  14949. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  14950. auto opts = httplib::stream::Options(cli, "/options");
  14951. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  14952. }
  14953. // SSL stream::* tests
  14954. #ifdef CPPHTTPLIB_SSL_ENABLED
  14955. class SSLStreamApiTest : public ::testing::Test {
  14956. protected:
  14957. void SetUp() override {
  14958. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  14959. res.set_content("Hello SSL!", "text/plain");
  14960. });
  14961. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  14962. res.set_content(req.body, "text/plain");
  14963. });
  14964. port_ = svr_.bind_to_any_port("127.0.0.1");
  14965. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  14966. svr_.wait_until_ready();
  14967. }
  14968. void TearDown() override {
  14969. svr_.stop();
  14970. if (thread_.joinable()) thread_.join();
  14971. }
  14972. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  14973. std::thread thread_;
  14974. int port_ = 0;
  14975. };
  14976. TEST_F(SSLStreamApiTest, GetAndPost) {
  14977. httplib::SSLClient cli("127.0.0.1", port_);
  14978. cli.enable_server_certificate_verification(false);
  14979. auto get = httplib::stream::Get(cli, "/hello");
  14980. EXPECT_EQ("Hello SSL!", read_body(get));
  14981. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  14982. EXPECT_EQ("test", read_body(post));
  14983. }
  14984. #endif
  14985. // Tests for Error::Timeout and Error::ConnectionClosed error types
  14986. // These errors are set in SocketStream/SSLSocketStream and propagated through
  14987. // BodyReader
  14988. TEST(ErrorHandlingTest, StreamReadTimeout) {
  14989. // Test that read timeout during streaming is detected
  14990. // Use a large content-length response where server delays mid-stream
  14991. Server svr;
  14992. svr.Get("/slow-stream", [](const Request &, Response &res) {
  14993. // Send a large response with delay in the middle
  14994. res.set_content_provider(
  14995. 1000, // content_length
  14996. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  14997. if (offset < 100) {
  14998. // Send first 100 bytes immediately
  14999. std::string data(100, 'A');
  15000. sink.write(data.c_str(), data.size());
  15001. return true;
  15002. }
  15003. // Then delay longer than client timeout
  15004. std::this_thread::sleep_for(std::chrono::seconds(3));
  15005. std::string data(900, 'B');
  15006. sink.write(data.c_str(), data.size());
  15007. return true;
  15008. });
  15009. });
  15010. auto port = 8091;
  15011. std::thread t([&]() { svr.listen("localhost", port); });
  15012. svr.wait_until_ready();
  15013. Client cli("localhost", port);
  15014. cli.set_read_timeout(1, 0); // 1 second timeout
  15015. auto handle = cli.open_stream("GET", "/slow-stream");
  15016. ASSERT_TRUE(handle.is_valid());
  15017. char buf[256];
  15018. ssize_t total = 0;
  15019. ssize_t n;
  15020. bool got_error = false;
  15021. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  15022. total += n;
  15023. }
  15024. if (n < 0) {
  15025. got_error = true;
  15026. // Should be timeout or read error
  15027. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  15028. handle.get_read_error() == Error::Read)
  15029. << "Actual error: " << to_string(handle.get_read_error());
  15030. }
  15031. // Either we got an error, or we got less data than expected
  15032. EXPECT_TRUE(got_error || total < 1000)
  15033. << "Expected timeout but got all " << total << " bytes";
  15034. svr.stop();
  15035. t.join();
  15036. }
  15037. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  15038. // Test connection closed detection via BodyReader
  15039. Server svr;
  15040. std::atomic<bool> close_now{false};
  15041. svr.Get("/will-close", [&](const Request &, Response &res) {
  15042. res.set_content_provider(
  15043. 10000, // Large content_length that we won't fully send
  15044. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  15045. if (offset < 100) {
  15046. std::string data(100, 'X');
  15047. sink.write(data.c_str(), data.size());
  15048. return true;
  15049. }
  15050. // Wait for signal then abort
  15051. while (!close_now) {
  15052. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  15053. }
  15054. return false; // Abort - server will close connection
  15055. });
  15056. });
  15057. auto port = 8092;
  15058. std::thread t([&]() { svr.listen("localhost", port); });
  15059. svr.wait_until_ready();
  15060. Client cli("localhost", port);
  15061. auto handle = cli.open_stream("GET", "/will-close");
  15062. ASSERT_TRUE(handle.is_valid());
  15063. char buf[256];
  15064. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  15065. EXPECT_GT(n, 0) << "First read should succeed";
  15066. // Signal server to close
  15067. close_now = true;
  15068. // Keep reading until error or EOF
  15069. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  15070. // Keep reading
  15071. }
  15072. // Should get an error since content_length wasn't satisfied
  15073. if (n < 0) {
  15074. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  15075. handle.get_read_error() == Error::Read)
  15076. << "Actual error: " << to_string(handle.get_read_error());
  15077. }
  15078. svr.stop();
  15079. t.join();
  15080. }
  15081. #ifdef CPPHTTPLIB_SSL_ENABLED
  15082. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  15083. // Test that read timeout during SSL streaming is detected
  15084. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15085. svr.Get("/slow-stream", [](const Request &, Response &res) {
  15086. res.set_content_provider(
  15087. 1000, "text/plain",
  15088. [](size_t offset, size_t /*length*/, DataSink &sink) {
  15089. if (offset < 100) {
  15090. std::string data(100, 'A');
  15091. sink.write(data.c_str(), data.size());
  15092. return true;
  15093. }
  15094. std::this_thread::sleep_for(std::chrono::seconds(3));
  15095. std::string data(900, 'B');
  15096. sink.write(data.c_str(), data.size());
  15097. return true;
  15098. });
  15099. });
  15100. auto port = 8093;
  15101. std::thread t([&]() { svr.listen("localhost", port); });
  15102. svr.wait_until_ready();
  15103. SSLClient cli("localhost", port);
  15104. cli.enable_server_certificate_verification(false);
  15105. cli.set_read_timeout(1, 0); // 1 second timeout
  15106. auto handle = cli.open_stream("GET", "/slow-stream");
  15107. ASSERT_TRUE(handle.is_valid());
  15108. char buf[256];
  15109. ssize_t total = 0;
  15110. ssize_t n;
  15111. bool got_error = false;
  15112. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  15113. total += n;
  15114. }
  15115. if (n < 0) {
  15116. got_error = true;
  15117. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  15118. handle.get_read_error() == Error::Read)
  15119. << "Actual error: " << to_string(handle.get_read_error());
  15120. }
  15121. EXPECT_TRUE(got_error || total < 1000)
  15122. << "Expected timeout but got all " << total << " bytes";
  15123. svr.stop();
  15124. t.join();
  15125. }
  15126. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  15127. // Test SSL connection closed detection
  15128. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15129. std::atomic<bool> close_now{false};
  15130. svr.Get("/will-close", [&](const Request &, Response &res) {
  15131. res.set_content_provider(
  15132. 10000, "text/plain",
  15133. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  15134. if (offset < 100) {
  15135. std::string data(100, 'X');
  15136. sink.write(data.c_str(), data.size());
  15137. return true;
  15138. }
  15139. while (!close_now) {
  15140. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  15141. }
  15142. return false;
  15143. });
  15144. });
  15145. auto port = 8094;
  15146. std::thread t([&]() { svr.listen("localhost", port); });
  15147. svr.wait_until_ready();
  15148. SSLClient cli("localhost", port);
  15149. cli.enable_server_certificate_verification(false);
  15150. auto handle = cli.open_stream("GET", "/will-close");
  15151. ASSERT_TRUE(handle.is_valid());
  15152. char buf[256];
  15153. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  15154. EXPECT_GT(n, 0);
  15155. // Signal server to close
  15156. close_now = true;
  15157. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  15158. // Keep reading
  15159. }
  15160. if (n < 0) {
  15161. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  15162. handle.get_read_error() == Error::Read)
  15163. << "Actual error: " << to_string(handle.get_read_error());
  15164. }
  15165. svr.stop();
  15166. t.join();
  15167. }
  15168. #endif
  15169. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  15170. using namespace httplib;
  15171. // Create a test file
  15172. const char *fname = "etag_testfile.txt";
  15173. const char *content = "etag-content";
  15174. {
  15175. std::ofstream ofs(fname);
  15176. ofs << content;
  15177. ASSERT_TRUE(ofs.good());
  15178. }
  15179. Server svr;
  15180. svr.set_mount_point("/static", ".");
  15181. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  15182. svr.wait_until_ready();
  15183. Client cli(HOST, PORT);
  15184. // First request: should get 200 with ETag header
  15185. auto res1 = cli.Get("/static/etag_testfile.txt");
  15186. ASSERT_TRUE(res1);
  15187. ASSERT_EQ(200, res1->status);
  15188. ASSERT_TRUE(res1->has_header("ETag"));
  15189. std::string etag = res1->get_header_value("ETag");
  15190. EXPECT_FALSE(etag.empty());
  15191. // Verify ETag format: W/"hex-hex"
  15192. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  15193. EXPECT_EQ('W', etag[0]);
  15194. EXPECT_EQ('/', etag[1]);
  15195. EXPECT_EQ('"', etag[2]);
  15196. EXPECT_EQ('"', etag.back());
  15197. // Exact match: expect 304 Not Modified
  15198. Headers h2 = {{"If-None-Match", etag}};
  15199. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  15200. ASSERT_TRUE(res2);
  15201. EXPECT_EQ(304, res2->status);
  15202. // Wildcard match: expect 304 Not Modified
  15203. Headers h3 = {{"If-None-Match", "*"}};
  15204. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  15205. ASSERT_TRUE(res3);
  15206. EXPECT_EQ(304, res3->status);
  15207. // Non-matching ETag: expect 200
  15208. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  15209. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  15210. ASSERT_TRUE(res4);
  15211. EXPECT_EQ(200, res4->status);
  15212. // Multiple ETags with one matching: expect 304
  15213. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  15214. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  15215. ASSERT_TRUE(res5);
  15216. EXPECT_EQ(304, res5->status);
  15217. svr.stop();
  15218. t.join();
  15219. std::remove(fname);
  15220. }
  15221. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  15222. using namespace httplib;
  15223. Server svr;
  15224. svr.set_mount_point("/static", ".");
  15225. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15226. svr.wait_until_ready();
  15227. Client cli(HOST, PORT);
  15228. // Send If-None-Match: * to a non-existent file
  15229. Headers h = {{"If-None-Match", "*"}};
  15230. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  15231. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15232. EXPECT_EQ(404, res->status);
  15233. svr.stop();
  15234. t.join();
  15235. }
  15236. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  15237. using namespace httplib;
  15238. // Create a test file
  15239. const char *fname = "etag_boundary_testfile.txt";
  15240. const char *content = "boundary-test";
  15241. {
  15242. std::ofstream ofs(fname);
  15243. ofs << content;
  15244. ASSERT_TRUE(ofs.good());
  15245. }
  15246. Server svr;
  15247. svr.set_mount_point("/static", ".");
  15248. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  15249. svr.wait_until_ready();
  15250. Client cli(HOST, PORT);
  15251. // Get the actual ETag
  15252. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  15253. ASSERT_TRUE(res1);
  15254. ASSERT_EQ(200, res1->status);
  15255. ASSERT_TRUE(res1->has_header("ETag"));
  15256. std::string etag = res1->get_header_value("ETag");
  15257. // Test 1: Very long ETag value (longer than actual ETag)
  15258. // Should NOT match and return 200 (not trigger out-of-bounds read)
  15259. Headers h1 = {{"If-None-Match", "W/"
  15260. "\"very-long-etag-value-that-is-much-longer-"
  15261. "than-the-actual-etag-value\""}};
  15262. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  15263. ASSERT_TRUE(res2);
  15264. EXPECT_EQ(200, res2->status); // Should not match
  15265. // Test 2: Long string followed by wildcard
  15266. // Should match on "*" and return 304 (without out-of-bounds read on the long
  15267. // string)
  15268. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  15269. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  15270. ASSERT_TRUE(res3);
  15271. EXPECT_EQ(304, res3->status); // Should match on "*"
  15272. // Test 3: Wildcard followed by long string
  15273. // Should match on "*" immediately and return 304
  15274. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  15275. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  15276. ASSERT_TRUE(res4);
  15277. EXPECT_EQ(304, res4->status); // Should match on "*"
  15278. // Test 4: Multiple long non-matching values
  15279. // Should NOT match and return 200 (test that all comparisons are safe)
  15280. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  15281. "W/\"second-long-non-matching-value\", "
  15282. "W/\"third-long-non-matching-value\""}};
  15283. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  15284. ASSERT_TRUE(res5);
  15285. EXPECT_EQ(200, res5->status); // Should not match
  15286. // Test 5: Single character that is not "*" (edge case)
  15287. Headers h5 = {{"If-None-Match", "X"}};
  15288. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  15289. ASSERT_TRUE(res6);
  15290. EXPECT_EQ(200, res6->status); // Should not match
  15291. svr.stop();
  15292. t.join();
  15293. std::remove(fname);
  15294. }
  15295. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  15296. using namespace httplib;
  15297. // Create a test file
  15298. const char *fname = "ims_testfile.txt";
  15299. const char *content = "if-modified-since-test";
  15300. {
  15301. std::ofstream ofs(fname);
  15302. ofs << content;
  15303. ASSERT_TRUE(ofs.good());
  15304. }
  15305. Server svr;
  15306. svr.set_mount_point("/static", ".");
  15307. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15308. svr.wait_until_ready();
  15309. Client cli(HOST, PORT);
  15310. // First request: should get 200 with Last-Modified header
  15311. auto res1 = cli.Get("/static/ims_testfile.txt");
  15312. ASSERT_TRUE(res1);
  15313. ASSERT_EQ(200, res1->status);
  15314. ASSERT_TRUE(res1->has_header("Last-Modified"));
  15315. std::string last_modified = res1->get_header_value("Last-Modified");
  15316. EXPECT_FALSE(last_modified.empty());
  15317. // If-Modified-Since with same time: expect 304
  15318. Headers h2 = {{"If-Modified-Since", last_modified}};
  15319. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  15320. ASSERT_TRUE(res2);
  15321. EXPECT_EQ(304, res2->status);
  15322. // If-Modified-Since with future time: expect 304
  15323. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  15324. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  15325. ASSERT_TRUE(res3);
  15326. EXPECT_EQ(304, res3->status);
  15327. // If-Modified-Since with past time: expect 200
  15328. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  15329. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  15330. ASSERT_TRUE(res4);
  15331. EXPECT_EQ(200, res4->status);
  15332. // If-None-Match takes precedence over If-Modified-Since
  15333. // (send matching ETag with old If-Modified-Since -> should still be 304)
  15334. ASSERT_TRUE(res1->has_header("ETag"));
  15335. std::string etag = res1->get_header_value("ETag");
  15336. Headers h5 = {{"If-None-Match", etag},
  15337. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  15338. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  15339. ASSERT_TRUE(res5);
  15340. EXPECT_EQ(304, res5->status);
  15341. svr.stop();
  15342. t.join();
  15343. std::remove(fname);
  15344. }
  15345. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  15346. using namespace httplib;
  15347. Server svr;
  15348. // Endpoint that returns compressible content
  15349. svr.Get("/compressible", [](const Request &, Response &res) {
  15350. // Return a large enough body to trigger compression
  15351. std::string body(1000, 'a');
  15352. res.set_content(body, "text/plain");
  15353. });
  15354. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15355. svr.wait_until_ready();
  15356. Client cli(HOST, PORT);
  15357. // Request with gzip support: should get Vary header when compressed
  15358. cli.set_compress(true);
  15359. auto res1 = cli.Get("/compressible");
  15360. ASSERT_TRUE(res1);
  15361. EXPECT_EQ(200, res1->status);
  15362. // If Content-Encoding is set, Vary should also be set
  15363. if (res1->has_header("Content-Encoding")) {
  15364. EXPECT_TRUE(res1->has_header("Vary"));
  15365. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  15366. }
  15367. // Request without Accept-Encoding header: should not have compression
  15368. Headers h_no_compress;
  15369. auto res2 = cli.Get("/compressible", h_no_compress);
  15370. ASSERT_TRUE(res2);
  15371. EXPECT_EQ(200, res2->status);
  15372. // Verify Vary header is present when compression is applied
  15373. // (the exact behavior depends on server configuration)
  15374. svr.stop();
  15375. t.join();
  15376. }
  15377. TEST(ETagTest, IfRangeWithETag) {
  15378. using namespace httplib;
  15379. // Create a test file with known content
  15380. const char *fname = "if_range_testfile.txt";
  15381. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  15382. {
  15383. std::ofstream ofs(fname);
  15384. ofs << content;
  15385. ASSERT_TRUE(ofs.good());
  15386. }
  15387. Server svr;
  15388. svr.set_mount_point("/static", ".");
  15389. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15390. svr.wait_until_ready();
  15391. Client cli(HOST, PORT);
  15392. // First request: get ETag
  15393. auto res1 = cli.Get("/static/if_range_testfile.txt");
  15394. ASSERT_TRUE(res1);
  15395. ASSERT_EQ(200, res1->status);
  15396. ASSERT_TRUE(res1->has_header("ETag"));
  15397. std::string etag = res1->get_header_value("ETag");
  15398. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  15399. // Since our server generates weak ETags (W/"..."), If-Range with our
  15400. // ETag should NOT result in partial content - it should return full content.
  15401. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  15402. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  15403. ASSERT_TRUE(res2);
  15404. // Weak ETag in If-Range -> full content (200), not partial (206)
  15405. EXPECT_EQ(200, res2->status);
  15406. EXPECT_EQ(content, res2->body);
  15407. EXPECT_FALSE(res2->has_header("Content-Range"));
  15408. // Range request with non-matching If-Range (ETag): should get 200 (full
  15409. // content)
  15410. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  15411. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  15412. ASSERT_TRUE(res3);
  15413. EXPECT_EQ(200, res3->status);
  15414. EXPECT_EQ(content, res3->body);
  15415. EXPECT_FALSE(res3->has_header("Content-Range"));
  15416. // Range request with strong ETag (hypothetical - our server doesn't generate
  15417. // strong ETags, but if client sends a strong ETag that doesn't match, it
  15418. // should return full content)
  15419. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  15420. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  15421. ASSERT_TRUE(res4);
  15422. EXPECT_EQ(200, res4->status);
  15423. EXPECT_EQ(content, res4->body);
  15424. EXPECT_FALSE(res4->has_header("Content-Range"));
  15425. svr.stop();
  15426. t.join();
  15427. std::remove(fname);
  15428. }
  15429. TEST(ETagTest, IfRangeWithDate) {
  15430. using namespace httplib;
  15431. // Create a test file
  15432. const char *fname = "if_range_date_testfile.txt";
  15433. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  15434. {
  15435. std::ofstream ofs(fname);
  15436. ofs << content;
  15437. ASSERT_TRUE(ofs.good());
  15438. }
  15439. Server svr;
  15440. svr.set_mount_point("/static", ".");
  15441. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15442. svr.wait_until_ready();
  15443. Client cli(HOST, PORT);
  15444. // First request: get Last-Modified
  15445. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  15446. ASSERT_TRUE(res1);
  15447. ASSERT_EQ(200, res1->status);
  15448. ASSERT_TRUE(res1->has_header("Last-Modified"));
  15449. std::string last_modified = res1->get_header_value("Last-Modified");
  15450. // Range request with matching If-Range (date): should get 206
  15451. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  15452. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  15453. ASSERT_TRUE(res2);
  15454. EXPECT_EQ(206, res2->status);
  15455. EXPECT_EQ("FGHIJ", res2->body);
  15456. // Range request with old If-Range date: should get 200 (full content)
  15457. Headers h3 = {{"Range", "bytes=5-9"},
  15458. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  15459. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  15460. ASSERT_TRUE(res3);
  15461. EXPECT_EQ(200, res3->status);
  15462. EXPECT_EQ(content, res3->body);
  15463. // Range request with future If-Range date: should get 206
  15464. Headers h4 = {{"Range", "bytes=0-4"},
  15465. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  15466. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  15467. ASSERT_TRUE(res4);
  15468. EXPECT_EQ(206, res4->status);
  15469. EXPECT_EQ("ABCDE", res4->body);
  15470. svr.stop();
  15471. t.join();
  15472. std::remove(fname);
  15473. }
  15474. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  15475. using namespace httplib;
  15476. const char *fname = "etag_malformed.txt";
  15477. const char *content = "malformed-etag";
  15478. {
  15479. std::ofstream ofs(fname);
  15480. ofs << content;
  15481. ASSERT_TRUE(ofs.good());
  15482. }
  15483. Server svr;
  15484. svr.set_mount_point("/static", ".");
  15485. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15486. svr.wait_until_ready();
  15487. Client cli(HOST, PORT);
  15488. // baseline: should get 200 and an ETag
  15489. auto res1 = cli.Get("/static/etag_malformed.txt");
  15490. ASSERT_TRUE(res1);
  15491. ASSERT_EQ(200, res1->status);
  15492. ASSERT_TRUE(res1->has_header("ETag"));
  15493. // Malformed ETag value (missing quotes) should be treated as non-matching
  15494. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  15495. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  15496. ASSERT_TRUE(res_bad);
  15497. EXPECT_EQ(200, res_bad->status);
  15498. // Whitespace-only header value should be considered invalid / non-matching
  15499. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  15500. "Host: localhost\r\n"
  15501. "If-None-Match: \r\n"
  15502. "Connection: close\r\n"
  15503. "\r\n";
  15504. std::string out;
  15505. ASSERT_TRUE(send_request(5, raw_req, &out));
  15506. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  15507. svr.stop();
  15508. t.join();
  15509. std::remove(fname);
  15510. }
  15511. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  15512. using namespace httplib;
  15513. const char *fname = "ims_invalid_format.txt";
  15514. const char *content = "ims-bad-format";
  15515. {
  15516. std::ofstream ofs(fname);
  15517. ofs << content;
  15518. ASSERT_TRUE(ofs.good());
  15519. }
  15520. Server svr;
  15521. svr.set_mount_point("/static", ".");
  15522. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15523. svr.wait_until_ready();
  15524. Client cli(HOST, PORT);
  15525. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  15526. ASSERT_TRUE(res1);
  15527. ASSERT_EQ(200, res1->status);
  15528. ASSERT_TRUE(res1->has_header("Last-Modified"));
  15529. // If-Modified-Since with invalid format should not result in 304
  15530. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  15531. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  15532. ASSERT_TRUE(res_bad);
  15533. EXPECT_EQ(200, res_bad->status);
  15534. // If-Range with invalid date format should be treated as mismatch -> full
  15535. // content (200)
  15536. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  15537. {"If-Range", "invalid-date"}};
  15538. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  15539. ASSERT_TRUE(res_ifrange);
  15540. EXPECT_EQ(200, res_ifrange->status);
  15541. svr.stop();
  15542. t.join();
  15543. std::remove(fname);
  15544. }
  15545. TEST(ETagTest, IfRangeWithMalformedETag) {
  15546. using namespace httplib;
  15547. const char *fname = "ifrange_malformed.txt";
  15548. const std::string content = "0123456789";
  15549. {
  15550. std::ofstream ofs(fname);
  15551. ofs << content;
  15552. ASSERT_TRUE(ofs.good());
  15553. }
  15554. Server svr;
  15555. svr.set_mount_point("/static", ".");
  15556. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15557. svr.wait_until_ready();
  15558. Client cli(HOST, PORT);
  15559. // First request: get ETag
  15560. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  15561. ASSERT_TRUE(res1);
  15562. ASSERT_EQ(200, res1->status);
  15563. ASSERT_TRUE(res1->has_header("ETag"));
  15564. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  15565. // full content (200)
  15566. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  15567. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  15568. ASSERT_TRUE(res2);
  15569. EXPECT_EQ(200, res2->status);
  15570. EXPECT_EQ(content, res2->body);
  15571. svr.stop();
  15572. t.join();
  15573. std::remove(fname);
  15574. }
  15575. TEST(ETagTest, ExtremeLargeDateValues) {
  15576. using namespace httplib;
  15577. const char *fname = "ims_extreme_date.txt";
  15578. const char *content = "ims-extreme-date";
  15579. {
  15580. std::ofstream ofs(fname);
  15581. ofs << content;
  15582. ASSERT_TRUE(ofs.good());
  15583. }
  15584. Server svr;
  15585. svr.set_mount_point("/static", ".");
  15586. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15587. svr.wait_until_ready();
  15588. Client cli(HOST, PORT);
  15589. auto res1 = cli.Get(std::string("/static/") + fname);
  15590. ASSERT_TRUE(res1);
  15591. ASSERT_EQ(200, res1->status);
  15592. ASSERT_TRUE(res1->has_header("Last-Modified"));
  15593. // Extremely large year that may overflow date parsing routines.
  15594. Headers h_large_date = {
  15595. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  15596. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  15597. ASSERT_TRUE(res_bad);
  15598. // Expect server to treat this as invalid/mismatch and return full content
  15599. EXPECT_EQ(200, res_bad->status);
  15600. // If-Range with extremely large date should be treated as mismatch -> full
  15601. // content (200)
  15602. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  15603. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  15604. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  15605. ASSERT_TRUE(res_ifrange);
  15606. EXPECT_EQ(200, res_ifrange->status);
  15607. svr.stop();
  15608. t.join();
  15609. std::remove(fname);
  15610. }
  15611. TEST(ETagTest, NegativeFileModificationTime) {
  15612. using namespace httplib;
  15613. const char *fname = "ims_negative_mtime.txt";
  15614. const std::string content = "negative-mtime";
  15615. {
  15616. std::ofstream ofs(fname);
  15617. ofs << content;
  15618. ASSERT_TRUE(ofs.good());
  15619. }
  15620. // Try to set file mtime to a negative value. This may fail on some
  15621. // platforms/filesystems; if it fails, the test will still verify server
  15622. // behaves safely by performing a regular conditional request.
  15623. #if defined(__APPLE__) || defined(__linux__)
  15624. bool set_negative = false;
  15625. do {
  15626. struct timeval times[2];
  15627. // access time: now
  15628. times[0].tv_sec = time(nullptr);
  15629. times[0].tv_usec = 0;
  15630. // modification time: negative (e.g., -1)
  15631. times[1].tv_sec = -1;
  15632. times[1].tv_usec = 0;
  15633. if (utimes(fname, times) == 0) { set_negative = true; }
  15634. } while (0);
  15635. #else
  15636. bool set_negative = false;
  15637. #endif
  15638. Server svr;
  15639. svr.set_mount_point("/static", ".");
  15640. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15641. svr.wait_until_ready();
  15642. Client cli(HOST, PORT);
  15643. auto res1 = cli.Get(std::string("/static/") + fname);
  15644. ASSERT_TRUE(res1);
  15645. ASSERT_EQ(200, res1->status);
  15646. bool has_last_modified = res1->has_header("Last-Modified");
  15647. std::string last_modified;
  15648. if (has_last_modified) {
  15649. last_modified = res1->get_header_value("Last-Modified");
  15650. }
  15651. if (set_negative) {
  15652. // If we successfully set a negative mtime, ensure server returns a
  15653. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  15654. // with an old date and ensure server handles it without crash.
  15655. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  15656. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  15657. ASSERT_TRUE(res2);
  15658. // Behavior may vary; at minimum ensure server responds (200 or 304).
  15659. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  15660. } else {
  15661. // Could not set negative mtime on this platform; fall back to verifying
  15662. // that normal invalid/malformed dates are treated safely (non-304).
  15663. Headers h_bad_date = {
  15664. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  15665. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  15666. ASSERT_TRUE(res_bad);
  15667. EXPECT_EQ(200, res_bad->status);
  15668. }
  15669. svr.stop();
  15670. t.join();
  15671. std::remove(fname);
  15672. }
  15673. //==============================================================================
  15674. // SSE Parsing Tests
  15675. //==============================================================================
  15676. class SSEParsingTest : public ::testing::Test {
  15677. protected:
  15678. // Test helper that mimics SSE parsing behavior
  15679. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  15680. int &retry_ms) {
  15681. // Blank line signals end of event
  15682. if (line.empty() || line == "\r") { return true; }
  15683. // Lines starting with ':' are comments (ignored)
  15684. if (!line.empty() && line[0] == ':') { return false; }
  15685. // Find the colon separator
  15686. auto colon_pos = line.find(':');
  15687. if (colon_pos == std::string::npos) {
  15688. // Line with no colon is treated as field name with empty value
  15689. return false;
  15690. }
  15691. std::string field = line.substr(0, colon_pos);
  15692. std::string value;
  15693. // Value starts after colon, skip optional single space
  15694. if (colon_pos + 1 < line.size()) {
  15695. size_t value_start = colon_pos + 1;
  15696. if (line[value_start] == ' ') { value_start++; }
  15697. value = line.substr(value_start);
  15698. // Remove trailing \r if present
  15699. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  15700. }
  15701. // Handle known fields
  15702. if (field == "event") {
  15703. msg.event = value;
  15704. } else if (field == "data") {
  15705. // Multiple data lines are concatenated with newlines
  15706. if (!msg.data.empty()) { msg.data += "\n"; }
  15707. msg.data += value;
  15708. } else if (field == "id") {
  15709. // Empty id is valid (clears the last event ID)
  15710. msg.id = value;
  15711. } else if (field == "retry") {
  15712. // Parse retry interval in milliseconds
  15713. {
  15714. int v = 0;
  15715. auto res =
  15716. detail::from_chars(value.data(), value.data() + value.size(), v);
  15717. if (res.ec == std::errc{}) { retry_ms = v; }
  15718. }
  15719. }
  15720. // Unknown fields are ignored per SSE spec
  15721. return false;
  15722. }
  15723. };
  15724. // Test: Single-line data
  15725. TEST_F(SSEParsingTest, SingleLineData) {
  15726. sse::SSEMessage msg;
  15727. int retry_ms = 3000;
  15728. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  15729. EXPECT_EQ(msg.data, "hello");
  15730. EXPECT_EQ(msg.event, "message");
  15731. // Blank line ends event
  15732. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  15733. }
  15734. // Test: Multi-line data
  15735. TEST_F(SSEParsingTest, MultiLineData) {
  15736. sse::SSEMessage msg;
  15737. int retry_ms = 3000;
  15738. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  15739. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  15740. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  15741. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  15742. }
  15743. // Test: Custom event types
  15744. TEST_F(SSEParsingTest, CustomEventType) {
  15745. sse::SSEMessage msg;
  15746. int retry_ms = 3000;
  15747. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  15748. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  15749. EXPECT_EQ(msg.event, "update");
  15750. EXPECT_EQ(msg.data, "payload");
  15751. }
  15752. // Test: Event ID handling
  15753. TEST_F(SSEParsingTest, EventIdHandling) {
  15754. sse::SSEMessage msg;
  15755. int retry_ms = 3000;
  15756. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  15757. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  15758. EXPECT_EQ(msg.id, "12345");
  15759. }
  15760. // Test: Empty event ID (clears last event ID)
  15761. TEST_F(SSEParsingTest, EmptyEventId) {
  15762. sse::SSEMessage msg;
  15763. msg.id = "previous";
  15764. int retry_ms = 3000;
  15765. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  15766. EXPECT_EQ(msg.id, "");
  15767. }
  15768. // Test: Retry field parsing
  15769. TEST_F(SSEParsingTest, RetryFieldParsing) {
  15770. sse::SSEMessage msg;
  15771. int retry_ms = 3000;
  15772. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  15773. EXPECT_EQ(retry_ms, 5000);
  15774. }
  15775. // Test: Invalid retry value
  15776. TEST_F(SSEParsingTest, InvalidRetryValue) {
  15777. sse::SSEMessage msg;
  15778. int retry_ms = 3000;
  15779. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  15780. EXPECT_EQ(retry_ms, 3000); // Unchanged
  15781. }
  15782. // Test: Comments (lines starting with :)
  15783. TEST_F(SSEParsingTest, CommentsIgnored) {
  15784. sse::SSEMessage msg;
  15785. int retry_ms = 3000;
  15786. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  15787. EXPECT_EQ(msg.data, "");
  15788. EXPECT_EQ(msg.event, "message");
  15789. }
  15790. // Test: Colon in value
  15791. TEST_F(SSEParsingTest, ColonInValue) {
  15792. sse::SSEMessage msg;
  15793. int retry_ms = 3000;
  15794. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  15795. EXPECT_EQ(msg.data, "hello:world:test");
  15796. }
  15797. // Test: Line with no colon (field name only)
  15798. TEST_F(SSEParsingTest, FieldNameOnly) {
  15799. sse::SSEMessage msg;
  15800. int retry_ms = 3000;
  15801. // According to SSE spec, this is treated as field name with empty value
  15802. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  15803. // Since we don't recognize "data" without colon, data should be empty
  15804. EXPECT_EQ(msg.data, "");
  15805. }
  15806. // Test: Trailing \r handling
  15807. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  15808. sse::SSEMessage msg;
  15809. int retry_ms = 3000;
  15810. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  15811. EXPECT_EQ(msg.data, "hello");
  15812. }
  15813. // Test: Unknown fields ignored
  15814. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  15815. sse::SSEMessage msg;
  15816. int retry_ms = 3000;
  15817. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  15818. EXPECT_EQ(msg.data, "");
  15819. EXPECT_EQ(msg.event, "message");
  15820. }
  15821. // Test: Space after colon is optional
  15822. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  15823. sse::SSEMessage msg1, msg2;
  15824. int retry_ms = 3000;
  15825. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  15826. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  15827. EXPECT_EQ(msg1.data, "hello");
  15828. EXPECT_EQ(msg2.data, "hello");
  15829. }
  15830. // Test: SSEMessage clear
  15831. TEST_F(SSEParsingTest, MessageClear) {
  15832. sse::SSEMessage msg;
  15833. msg.event = "custom";
  15834. msg.data = "some data";
  15835. msg.id = "123";
  15836. msg.clear();
  15837. EXPECT_EQ(msg.event, "message");
  15838. EXPECT_EQ(msg.data, "");
  15839. EXPECT_EQ(msg.id, "");
  15840. }
  15841. // Test: Complete event parsing
  15842. TEST_F(SSEParsingTest, CompleteEventParsing) {
  15843. sse::SSEMessage msg;
  15844. int retry_ms = 3000;
  15845. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  15846. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  15847. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  15848. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  15849. // Blank line ends event
  15850. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  15851. EXPECT_EQ(msg.event, "notification");
  15852. EXPECT_EQ(msg.id, "evt-42");
  15853. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  15854. EXPECT_EQ(retry_ms, 1000);
  15855. }
  15856. //==============================================================================
  15857. // Integration Tests with Server
  15858. //==============================================================================
  15859. class SSEIntegrationTest : public ::testing::Test {
  15860. protected:
  15861. void SetUp() override {
  15862. stop_server_.store(false);
  15863. events_.clear();
  15864. server_ = httplib::detail::make_unique<Server>();
  15865. setup_server();
  15866. start_server();
  15867. }
  15868. void TearDown() override {
  15869. stop_server_.store(true);
  15870. event_cv_.notify_all();
  15871. server_->stop();
  15872. if (server_thread_.joinable()) { server_thread_.join(); }
  15873. }
  15874. void setup_server() {
  15875. // Simple SSE endpoint
  15876. server_->Get("/events", [this](const Request &req, Response &res) {
  15877. auto last_id = req.get_header_value("Last-Event-ID");
  15878. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  15879. res.set_chunked_content_provider(
  15880. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  15881. std::unique_lock<std::mutex> lock(event_mutex_);
  15882. if (event_cv_.wait_for(
  15883. lock, std::chrono::milliseconds(200), [this] {
  15884. return !events_.empty() || stop_server_.load();
  15885. })) {
  15886. if (stop_server_.load()) { return false; }
  15887. if (!events_.empty()) {
  15888. std::string event = events_.front();
  15889. events_.erase(events_.begin());
  15890. sink.write(event.data(), event.size());
  15891. return true;
  15892. }
  15893. }
  15894. return !stop_server_.load();
  15895. });
  15896. });
  15897. // Endpoint that returns error
  15898. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  15899. res.status = 500;
  15900. res.set_content("Internal Server Error", "text/plain");
  15901. });
  15902. // Endpoint for custom event types
  15903. server_->Get("/custom-events", [](const Request &, Response &res) {
  15904. res.set_chunked_content_provider(
  15905. "text/event-stream", [](size_t offset, DataSink &sink) {
  15906. if (offset == 0) {
  15907. std::string event = "event: update\ndata: updated\n\n"
  15908. "event: delete\ndata: deleted\n\n";
  15909. sink.write(event.data(), event.size());
  15910. }
  15911. return false; // End stream after sending
  15912. });
  15913. });
  15914. }
  15915. void start_server() {
  15916. port_ = server_->bind_to_any_port(HOST);
  15917. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  15918. // Wait for server to start
  15919. while (!server_->is_running()) {
  15920. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  15921. }
  15922. }
  15923. int get_port() const { return port_; }
  15924. void send_event(const std::string &event) {
  15925. std::lock_guard<std::mutex> lock(event_mutex_);
  15926. events_.push_back(event);
  15927. event_cv_.notify_all();
  15928. }
  15929. std::unique_ptr<Server> server_;
  15930. std::thread server_thread_;
  15931. std::mutex event_mutex_;
  15932. std::condition_variable event_cv_;
  15933. std::vector<std::string> events_;
  15934. std::atomic<bool> stop_server_{false};
  15935. std::string last_received_event_id_;
  15936. int port_ = 0;
  15937. };
  15938. // Test: Successful connection and on_open callback
  15939. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  15940. // Add a simple endpoint that sends one event and closes
  15941. server_->Get("/simple-event", [](const Request &, Response &res) {
  15942. res.set_chunked_content_provider(
  15943. "text/event-stream", [](size_t offset, DataSink &sink) {
  15944. if (offset == 0) {
  15945. std::string event = "data: hello\n\n";
  15946. sink.write(event.data(), event.size());
  15947. }
  15948. return false; // Close stream after sending
  15949. });
  15950. });
  15951. Client client("localhost", get_port());
  15952. sse::SSEClient sse(client, "/simple-event");
  15953. std::atomic<bool> open_called{false};
  15954. std::atomic<bool> message_received{false};
  15955. sse.on_open([&open_called]() { open_called.store(true); });
  15956. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  15957. if (msg.data == "hello") { message_received.store(true); }
  15958. });
  15959. sse.set_reconnect_interval(100);
  15960. sse.set_max_reconnect_attempts(1);
  15961. // Start async
  15962. sse.start_async();
  15963. // Wait for message to be processed
  15964. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  15965. sse.stop();
  15966. EXPECT_TRUE(open_called.load());
  15967. EXPECT_TRUE(message_received.load());
  15968. }
  15969. // Test: on_message callback
  15970. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  15971. // Endpoint that sends multiple events then closes
  15972. server_->Get("/multi-event", [](const Request &, Response &res) {
  15973. res.set_chunked_content_provider(
  15974. "text/event-stream", [](size_t offset, DataSink &sink) {
  15975. if (offset == 0) {
  15976. std::string events = "data: message1\n\ndata: message2\n\n";
  15977. sink.write(events.data(), events.size());
  15978. }
  15979. return false;
  15980. });
  15981. });
  15982. Client client("localhost", get_port());
  15983. sse::SSEClient sse(client, "/multi-event");
  15984. std::vector<std::string> received_messages;
  15985. std::mutex messages_mutex;
  15986. sse.on_message([&](const sse::SSEMessage &msg) {
  15987. std::lock_guard<std::mutex> lock(messages_mutex);
  15988. received_messages.push_back(msg.data);
  15989. });
  15990. sse.set_reconnect_interval(100);
  15991. sse.set_max_reconnect_attempts(1);
  15992. sse.start_async();
  15993. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  15994. sse.stop();
  15995. std::lock_guard<std::mutex> lock(messages_mutex);
  15996. EXPECT_GE(received_messages.size(), 2u);
  15997. if (received_messages.size() >= 2) {
  15998. EXPECT_EQ(received_messages[0], "message1");
  15999. EXPECT_EQ(received_messages[1], "message2");
  16000. }
  16001. }
  16002. // Test: on_event for specific types
  16003. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  16004. Client client("localhost", get_port());
  16005. sse::SSEClient sse(client, "/custom-events");
  16006. std::atomic<bool> update_received{false};
  16007. std::atomic<bool> delete_received{false};
  16008. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  16009. if (msg.data == "updated") { update_received.store(true); }
  16010. });
  16011. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  16012. if (msg.data == "deleted") { delete_received.store(true); }
  16013. });
  16014. sse.set_max_reconnect_attempts(1);
  16015. sse.start_async();
  16016. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  16017. sse.stop();
  16018. EXPECT_TRUE(update_received.load());
  16019. EXPECT_TRUE(delete_received.load());
  16020. }
  16021. // Test: on_error callback on connection failure
  16022. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  16023. // Connect to a non-existent port
  16024. Client client("localhost", 59999);
  16025. sse::SSEClient sse(client, "/events");
  16026. std::atomic<bool> error_called{false};
  16027. Error received_error = Error::Success;
  16028. sse.on_error([&](Error err) {
  16029. error_called.store(true);
  16030. received_error = err;
  16031. });
  16032. sse.set_reconnect_interval(50);
  16033. sse.set_max_reconnect_attempts(1);
  16034. sse.start_async();
  16035. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  16036. sse.stop();
  16037. EXPECT_TRUE(error_called.load());
  16038. EXPECT_NE(received_error, Error::Success);
  16039. }
  16040. // Test: Last-Event-ID header sent on reconnect
  16041. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  16042. // Endpoint that sends event with ID
  16043. server_->Get("/event-with-id", [](const Request &, Response &res) {
  16044. res.set_chunked_content_provider(
  16045. "text/event-stream", [](size_t offset, DataSink &sink) {
  16046. if (offset == 0) {
  16047. std::string event = "id: evt-123\ndata: test\n\n";
  16048. sink.write(event.data(), event.size());
  16049. }
  16050. return false;
  16051. });
  16052. });
  16053. Client client("localhost", get_port());
  16054. sse::SSEClient sse(client, "/event-with-id");
  16055. std::atomic<bool> id_received{false};
  16056. sse.on_message([&](const sse::SSEMessage &msg) {
  16057. if (!msg.id.empty()) { id_received.store(true); }
  16058. });
  16059. sse.set_reconnect_interval(100);
  16060. sse.set_max_reconnect_attempts(1);
  16061. sse.start_async();
  16062. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  16063. sse.stop();
  16064. EXPECT_TRUE(id_received.load());
  16065. EXPECT_EQ(sse.last_event_id(), "evt-123");
  16066. }
  16067. // Test: Manual stop
  16068. TEST_F(SSEIntegrationTest, ManualStop) {
  16069. // Endpoint that sends one event and stays open briefly
  16070. std::atomic<bool> handler_running{true};
  16071. server_->Get("/stay-open", [&handler_running](const Request &,
  16072. Response &res) {
  16073. res.set_chunked_content_provider(
  16074. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  16075. if (offset == 0) {
  16076. std::string event = "data: connected\n\n";
  16077. sink.write(event.data(), event.size());
  16078. }
  16079. // Keep connection open while handler_running is true
  16080. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  16081. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  16082. }
  16083. return false;
  16084. });
  16085. });
  16086. Client client("localhost", get_port());
  16087. sse::SSEClient sse(client, "/stay-open");
  16088. std::atomic<bool> connected{false};
  16089. sse.on_open([&connected]() { connected.store(true); });
  16090. sse.set_reconnect_interval(100);
  16091. sse.set_max_reconnect_attempts(1);
  16092. sse.start_async();
  16093. // Wait for connection to establish
  16094. for (int i = 0; i < 20 && !connected.load(); ++i) {
  16095. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  16096. }
  16097. EXPECT_TRUE(connected.load());
  16098. EXPECT_TRUE(sse.is_connected());
  16099. // Signal handler to stop
  16100. handler_running.store(false);
  16101. // Stop SSE client
  16102. sse.stop();
  16103. EXPECT_FALSE(sse.is_connected());
  16104. }
  16105. // Test: SSEClient with custom headers
  16106. TEST_F(SSEIntegrationTest, CustomHeaders) {
  16107. // Setup a server endpoint that checks for custom header
  16108. std::atomic<bool> header_received{false};
  16109. server_->Get("/header-check", [&](const Request &req, Response &res) {
  16110. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  16111. header_received.store(true);
  16112. }
  16113. res.set_chunked_content_provider("text/event-stream",
  16114. [](size_t, DataSink &) { return false; });
  16115. });
  16116. Client client("localhost", get_port());
  16117. Headers headers = {{"X-Custom-Header", "custom-value"}};
  16118. sse::SSEClient sse(client, "/header-check", headers);
  16119. sse.set_max_reconnect_attempts(1);
  16120. sse.start_async();
  16121. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  16122. sse.stop();
  16123. EXPECT_TRUE(header_received.load());
  16124. }
  16125. // Test: Reconnect interval configuration
  16126. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  16127. Client client("localhost", get_port());
  16128. sse::SSEClient sse(client, "/events");
  16129. auto &result = sse.set_reconnect_interval(500);
  16130. // Builder pattern should return reference to self
  16131. EXPECT_EQ(&result, &sse);
  16132. }
  16133. // Test: Max reconnect attempts
  16134. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  16135. // Connect to non-existent port to force reconnects
  16136. Client client("localhost", 59998);
  16137. sse::SSEClient sse(client, "/events");
  16138. std::atomic<int> error_count{0};
  16139. sse.on_error([&](Error) { error_count.fetch_add(1); });
  16140. sse.set_reconnect_interval(50);
  16141. sse.set_max_reconnect_attempts(2);
  16142. auto start = std::chrono::steady_clock::now();
  16143. sse.start(); // Blocking call
  16144. auto end = std::chrono::steady_clock::now();
  16145. // Should have stopped after 2 failed attempts
  16146. EXPECT_GE(error_count.load(), 2);
  16147. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  16148. auto duration =
  16149. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  16150. #ifdef _WIN32
  16151. // Windows is much slower for socket connection failures
  16152. EXPECT_LT(duration.count(), 7000);
  16153. #else
  16154. EXPECT_LT(duration.count(), 1000);
  16155. #endif
  16156. }
  16157. // Test: Multi-line data in integration
  16158. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  16159. // Endpoint with multi-line data
  16160. server_->Get("/multiline-data", [](const Request &, Response &res) {
  16161. res.set_chunked_content_provider(
  16162. "text/event-stream", [](size_t offset, DataSink &sink) {
  16163. if (offset == 0) {
  16164. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  16165. sink.write(event.data(), event.size());
  16166. }
  16167. return false;
  16168. });
  16169. });
  16170. Client client("localhost", get_port());
  16171. sse::SSEClient sse(client, "/multiline-data");
  16172. std::string received_data;
  16173. std::mutex data_mutex;
  16174. sse.on_message([&](const sse::SSEMessage &msg) {
  16175. std::lock_guard<std::mutex> lock(data_mutex);
  16176. received_data = msg.data;
  16177. });
  16178. sse.set_reconnect_interval(100);
  16179. sse.set_max_reconnect_attempts(1);
  16180. sse.start_async();
  16181. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  16182. sse.stop();
  16183. std::lock_guard<std::mutex> lock(data_mutex);
  16184. EXPECT_EQ(received_data, "line1\nline2\nline3");
  16185. }
  16186. // Test: Auto-reconnect after server disconnection
  16187. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  16188. std::atomic<int> connection_count{0};
  16189. std::atomic<int> message_count{0};
  16190. // Endpoint that sends one event and closes, forcing reconnect
  16191. server_->Get("/reconnect-test",
  16192. [&connection_count](const Request &, Response &res) {
  16193. connection_count.fetch_add(1);
  16194. res.set_chunked_content_provider(
  16195. "text/event-stream", [](size_t offset, DataSink &sink) {
  16196. if (offset == 0) {
  16197. std::string event = "data: hello\n\n";
  16198. sink.write(event.data(), event.size());
  16199. }
  16200. return false; // Close connection after sending
  16201. });
  16202. });
  16203. Client client("localhost", get_port());
  16204. sse::SSEClient sse(client, "/reconnect-test");
  16205. sse.on_message([&message_count](const sse::SSEMessage &) {
  16206. message_count.fetch_add(1);
  16207. });
  16208. sse.set_reconnect_interval(100);
  16209. sse.set_max_reconnect_attempts(3);
  16210. sse.start_async();
  16211. // Wait long enough for multiple reconnects
  16212. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  16213. sse.stop();
  16214. // Should have connected multiple times (initial + reconnects)
  16215. EXPECT_GE(connection_count.load(), 2);
  16216. // Should have received messages from multiple connections
  16217. EXPECT_GE(message_count.load(), 2);
  16218. }
  16219. // Test: Last-Event-ID sent on reconnect
  16220. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  16221. std::atomic<int> connection_count{0};
  16222. std::vector<std::string> received_last_event_ids;
  16223. std::mutex id_mutex;
  16224. // Endpoint that checks Last-Event-ID header and sends event with ID
  16225. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  16226. int conn = connection_count.fetch_add(1);
  16227. // Capture the Last-Event-ID header from each connection
  16228. {
  16229. std::lock_guard<std::mutex> lock(id_mutex);
  16230. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  16231. }
  16232. res.set_chunked_content_provider(
  16233. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  16234. if (offset == 0) {
  16235. std::string event =
  16236. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  16237. sink.write(event.data(), event.size());
  16238. }
  16239. return false;
  16240. });
  16241. });
  16242. Client client("localhost", get_port());
  16243. sse::SSEClient sse(client, "/reconnect-with-id");
  16244. sse.set_reconnect_interval(100);
  16245. sse.set_max_reconnect_attempts(3);
  16246. sse.start_async();
  16247. // Wait for at least 2 connections
  16248. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  16249. sse.stop();
  16250. // Verify behavior
  16251. std::lock_guard<std::mutex> lock(id_mutex);
  16252. EXPECT_GE(received_last_event_ids.size(), 2u);
  16253. // First connection should have no Last-Event-ID
  16254. if (!received_last_event_ids.empty()) {
  16255. EXPECT_EQ(received_last_event_ids[0], "");
  16256. }
  16257. // Second connection should have Last-Event-ID from first connection
  16258. if (received_last_event_ids.size() >= 2) {
  16259. EXPECT_EQ(received_last_event_ids[1], "event-0");
  16260. }
  16261. }
  16262. // Test: set_headers updates headers used on reconnect
  16263. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  16264. std::vector<std::string> received_tokens;
  16265. std::mutex token_mutex;
  16266. // Endpoint that captures Authorization header
  16267. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  16268. {
  16269. std::lock_guard<std::mutex> lock(token_mutex);
  16270. received_tokens.push_back(req.get_header_value("Authorization"));
  16271. }
  16272. res.set_chunked_content_provider(
  16273. "text/event-stream", [](size_t offset, DataSink &sink) {
  16274. if (offset == 0) {
  16275. std::string event = "data: hello\n\n";
  16276. sink.write(event.data(), event.size());
  16277. }
  16278. return false; // Close connection to trigger reconnect
  16279. });
  16280. });
  16281. Client client("localhost", get_port());
  16282. Headers headers = {{"Authorization", "Bearer old-token"}};
  16283. sse::SSEClient sse(client, "/auth-check", headers);
  16284. // Update headers on each successful connection
  16285. sse.on_open(
  16286. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  16287. sse.set_reconnect_interval(100);
  16288. sse.set_max_reconnect_attempts(3);
  16289. sse.start_async();
  16290. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  16291. sse.stop();
  16292. std::lock_guard<std::mutex> lock(token_mutex);
  16293. ASSERT_GE(received_tokens.size(), 2u);
  16294. // First connection uses original header
  16295. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  16296. // Second connection uses updated header from set_headers
  16297. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  16298. }
  16299. // Test: 401 allows reconnection (so on_error can refresh headers)
  16300. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  16301. std::atomic<int> connection_count{0};
  16302. // Endpoint: returns 401 on first attempt, 200 on second
  16303. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  16304. int conn = connection_count.fetch_add(1);
  16305. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  16306. res.status = StatusCode::Unauthorized_401;
  16307. res.set_content("Unauthorized", "text/plain");
  16308. return;
  16309. }
  16310. res.set_chunked_content_provider(
  16311. "text/event-stream", [](size_t offset, DataSink &sink) {
  16312. if (offset == 0) {
  16313. std::string event = "data: authenticated\n\n";
  16314. sink.write(event.data(), event.size());
  16315. }
  16316. return false;
  16317. });
  16318. });
  16319. Client client("localhost", get_port());
  16320. Headers headers = {{"Authorization", "Bearer expired"}};
  16321. sse::SSEClient sse(client, "/auth-retry", headers);
  16322. std::atomic<bool> message_received{false};
  16323. // Refresh token on error
  16324. sse.on_error(
  16325. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  16326. sse.on_message([&](const sse::SSEMessage &msg) {
  16327. if (msg.data == "authenticated") { message_received.store(true); }
  16328. });
  16329. sse.set_reconnect_interval(100);
  16330. sse.set_max_reconnect_attempts(3);
  16331. sse.start_async();
  16332. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  16333. sse.stop();
  16334. // Should have reconnected after 401 and succeeded with new token
  16335. EXPECT_GE(connection_count.load(), 2);
  16336. EXPECT_TRUE(message_received.load());
  16337. }
  16338. TEST(Issue2318Test, EmptyHostString) {
  16339. {
  16340. httplib::Client cli_empty("", PORT);
  16341. auto res = cli_empty.Get("/");
  16342. ASSERT_FALSE(res);
  16343. EXPECT_EQ(httplib::Error::Connection, res.error());
  16344. }
  16345. {
  16346. httplib::Client cli(" ", PORT);
  16347. auto res = cli.Get("/");
  16348. ASSERT_FALSE(res);
  16349. EXPECT_EQ(httplib::Error::Connection, res.error());
  16350. }
  16351. }
  16352. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  16353. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  16354. Server svr;
  16355. // Set a small payload limit (1KB)
  16356. svr.set_payload_max_length(1024);
  16357. svr.Post("/test", [&](const Request &req, Response &res) {
  16358. res.set_content("Body size: " + std::to_string(req.body.size()),
  16359. "text/plain");
  16360. });
  16361. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16362. auto se = detail::scope_exit([&] {
  16363. svr.stop();
  16364. listen_thread.join();
  16365. });
  16366. svr.wait_until_ready();
  16367. // Create data that compresses well but exceeds limit when decompressed
  16368. // 8KB of repeated null bytes compresses to a very small size
  16369. std::string original_data(8 * 1024, '\0');
  16370. // Compress the data using gzip
  16371. std::string compressed_data;
  16372. detail::gzip_compressor compressor;
  16373. compressor.compress(original_data.data(), original_data.size(), true,
  16374. [&](const char *data, size_t size) {
  16375. compressed_data.append(data, size);
  16376. return true;
  16377. });
  16378. // Verify compression worked (compressed should be much smaller)
  16379. ASSERT_LT(compressed_data.size(), original_data.size());
  16380. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  16381. // Send compressed data with Content-Encoding: gzip
  16382. Client cli(HOST, PORT);
  16383. Headers headers = {{"Content-Encoding", "gzip"}};
  16384. auto res =
  16385. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  16386. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  16387. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16388. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  16389. }
  16390. #endif
  16391. // ============================================================================
  16392. // OpenSSL-Specific Tests
  16393. // ============================================================================
  16394. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  16395. X509 *readCertificate(const std::string &strFileName) {
  16396. std::ifstream inStream(strFileName);
  16397. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  16398. std::istreambuf_iterator<char>());
  16399. if (strCertPEM.empty()) return (nullptr);
  16400. BIO *pbCert = BIO_new(BIO_s_mem());
  16401. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  16402. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  16403. BIO_free(pbCert);
  16404. return (pCert);
  16405. }
  16406. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  16407. std::ifstream inStream(strFileName);
  16408. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  16409. std::istreambuf_iterator<char>());
  16410. if (strPrivateKeyPEM.empty()) return (nullptr);
  16411. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  16412. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  16413. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  16414. BIO_free(pbPrivKey);
  16415. return (pPrivateKey);
  16416. }
  16417. TEST(BindServerTest, UpdateCerts) {
  16418. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  16419. int port = svr.bind_to_any_port("0.0.0.0");
  16420. ASSERT_TRUE(svr.is_valid());
  16421. ASSERT_TRUE(port > 0);
  16422. X509 *cert = readCertificate(SERVER_CERT_FILE);
  16423. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  16424. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  16425. ASSERT_TRUE(cert != nullptr);
  16426. ASSERT_TRUE(ca_cert != nullptr);
  16427. ASSERT_TRUE(key != nullptr);
  16428. X509_STORE *cert_store = X509_STORE_new();
  16429. X509_STORE_add_cert(cert_store, ca_cert);
  16430. // svr.update_certs(cert, key, cert_store); // deprecated
  16431. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  16432. CLIENT_CA_CERT_FILE);
  16433. ASSERT_TRUE(svr.is_valid());
  16434. svr.stop();
  16435. X509_STORE_free(cert_store);
  16436. X509_free(cert);
  16437. X509_free(ca_cert);
  16438. EVP_PKEY_free(key);
  16439. }
  16440. // Test that update_certs() updates client CA list correctly
  16441. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  16442. // Start with file-based constructor
  16443. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16444. ASSERT_TRUE(svr.is_valid());
  16445. // Initially no client CA list should be set
  16446. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  16447. ASSERT_TRUE(ssl_ctx != nullptr);
  16448. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  16449. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  16450. EXPECT_EQ(0, count_before);
  16451. // Now update with client CA (PEM string)
  16452. std::string cert_pem, key_pem, ca_pem;
  16453. read_file(SERVER_CERT_FILE, cert_pem);
  16454. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  16455. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  16456. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  16457. ASSERT_TRUE(svr.is_valid());
  16458. // Now client CA list should be set
  16459. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  16460. ASSERT_TRUE(ca_list_after != nullptr);
  16461. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  16462. }
  16463. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  16464. // Test that the file-path SSLServer constructor properly sets the client CA
  16465. // list that is sent to clients during the TLS handshake (CertificateRequest)
  16466. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  16467. ASSERT_TRUE(svr.is_valid());
  16468. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  16469. ASSERT_TRUE(ssl_ctx != nullptr);
  16470. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  16471. ASSERT_TRUE(ca_list != nullptr);
  16472. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  16473. }
  16474. #endif
  16475. // ============================================================================
  16476. // MbedTLS-Specific Tests
  16477. // ============================================================================
  16478. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  16479. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  16480. using namespace httplib::tls;
  16481. // Track if callback was invoked
  16482. bool callback_invoked = false;
  16483. // The callback receives void* ctx which is actually MbedTlsContext*
  16484. // We can access the mbedtls_ssl_config via the context
  16485. auto setup_callback = [&callback_invoked](void *ctx) {
  16486. callback_invoked = true;
  16487. // Cast to MbedTlsContext* to access the ssl config
  16488. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  16489. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  16490. // Use static variables to hold certificate data (simplified for test)
  16491. static mbedtls_x509_crt own_cert;
  16492. static mbedtls_pk_context own_key;
  16493. static mbedtls_x509_crt ca_chain;
  16494. static bool initialized = false;
  16495. if (!initialized) {
  16496. mbedtls_x509_crt_init(&own_cert);
  16497. mbedtls_pk_init(&own_key);
  16498. mbedtls_x509_crt_init(&ca_chain);
  16499. // Load server certificate
  16500. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  16501. return false;
  16502. }
  16503. // Load server private key.
  16504. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  16505. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  16506. #if MBEDTLS_VERSION_MAJOR == 3
  16507. ,
  16508. mbedtls_ctr_drbg_random, nullptr
  16509. #endif
  16510. ) != 0) {
  16511. return false;
  16512. }
  16513. // Load CA chain for client verification
  16514. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  16515. return false;
  16516. }
  16517. initialized = true;
  16518. }
  16519. // Configure the SSL config
  16520. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  16521. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  16522. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  16523. // Set minimum TLS version using mbedTLS native API
  16524. #if MBEDTLS_VERSION_MAJOR >= 3
  16525. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  16526. #else
  16527. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  16528. MBEDTLS_SSL_MINOR_VERSION_3);
  16529. #endif
  16530. return true;
  16531. };
  16532. SSLServer svr(setup_callback);
  16533. ASSERT_TRUE(svr.is_valid());
  16534. ASSERT_TRUE(callback_invoked);
  16535. svr.Get("/test", [&](const Request &req, Response &res) {
  16536. res.set_content("test", "text/plain");
  16537. auto cert = req.peer_cert();
  16538. ASSERT_TRUE(static_cast<bool>(cert));
  16539. auto common_name = cert.subject_cn();
  16540. EXPECT_EQ("Common Name", common_name);
  16541. });
  16542. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  16543. auto se = detail::scope_exit([&] {
  16544. svr.stop();
  16545. t.join();
  16546. ASSERT_FALSE(svr.is_running());
  16547. });
  16548. svr.wait_until_ready();
  16549. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  16550. cli.enable_server_certificate_verification(false);
  16551. cli.set_connection_timeout(30);
  16552. auto res = cli.Get("/test");
  16553. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16554. ASSERT_EQ(StatusCode::OK_200, res->status);
  16555. }
  16556. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  16557. // context (owning mbedtls_ssl_config) before shutting down a still-open
  16558. // keep-alive SSL session, which reads through that config in
  16559. // mbedtls_ssl_close_notify.
  16560. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  16561. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16562. ASSERT_TRUE(svr.is_valid());
  16563. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  16564. res.set_content("test", "text/plain");
  16565. });
  16566. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  16567. auto se = detail::scope_exit([&] {
  16568. svr.stop();
  16569. t.join();
  16570. ASSERT_FALSE(svr.is_running());
  16571. });
  16572. svr.wait_until_ready();
  16573. {
  16574. SSLClient cli(HOST, PORT);
  16575. cli.enable_server_certificate_verification(false);
  16576. cli.set_keep_alive(true);
  16577. auto res = cli.Get("/test");
  16578. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16579. ASSERT_EQ(StatusCode::OK_200, res->status);
  16580. // cli is destructed here with the keep-alive SSL session still open.
  16581. }
  16582. }
  16583. #endif
  16584. // WebSocket Tests
  16585. TEST(WebSocketTest, RSVBitsMustBeZero) {
  16586. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  16587. // defining the meaning of these bits has been negotiated.
  16588. auto make_frame = [](uint8_t first_byte) {
  16589. std::string frame;
  16590. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  16591. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  16592. frame += "Hello";
  16593. return frame;
  16594. };
  16595. // RSV1 set (0x40)
  16596. {
  16597. detail::BufferStream strm;
  16598. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  16599. ws::Opcode opcode;
  16600. std::string payload;
  16601. bool fin;
  16602. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16603. false, 1024));
  16604. }
  16605. // RSV2 set (0x20)
  16606. {
  16607. detail::BufferStream strm;
  16608. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  16609. ws::Opcode opcode;
  16610. std::string payload;
  16611. bool fin;
  16612. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16613. false, 1024));
  16614. }
  16615. // RSV3 set (0x10)
  16616. {
  16617. detail::BufferStream strm;
  16618. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  16619. ws::Opcode opcode;
  16620. std::string payload;
  16621. bool fin;
  16622. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16623. false, 1024));
  16624. }
  16625. // No RSV bits set - should succeed
  16626. {
  16627. detail::BufferStream strm;
  16628. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  16629. ws::Opcode opcode;
  16630. std::string payload;
  16631. bool fin;
  16632. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16633. false, 1024));
  16634. EXPECT_EQ(ws::Opcode::Text, opcode);
  16635. EXPECT_EQ("Hello", payload);
  16636. EXPECT_TRUE(fin);
  16637. }
  16638. }
  16639. TEST(WebSocketTest, ControlFrameValidation) {
  16640. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  16641. // payload length <= 125.
  16642. // Ping with FIN=0 - must be rejected
  16643. {
  16644. detail::BufferStream strm;
  16645. std::string frame;
  16646. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  16647. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  16648. strm.write(frame.data(), frame.size());
  16649. ws::Opcode opcode;
  16650. std::string payload;
  16651. bool fin;
  16652. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16653. false, 1024));
  16654. }
  16655. // Close with FIN=0 - must be rejected
  16656. {
  16657. detail::BufferStream strm;
  16658. std::string frame;
  16659. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  16660. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  16661. strm.write(frame.data(), frame.size());
  16662. ws::Opcode opcode;
  16663. std::string payload;
  16664. bool fin;
  16665. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16666. false, 1024));
  16667. }
  16668. // Ping with payload_len=126 (extended length) - must be rejected
  16669. {
  16670. detail::BufferStream strm;
  16671. std::string frame;
  16672. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  16673. frame += static_cast<char>(126); // payload_len=126 (>125)
  16674. frame += static_cast<char>(0x00); // extended length high byte
  16675. frame += static_cast<char>(126); // extended length low byte
  16676. frame += std::string(126, 'x');
  16677. strm.write(frame.data(), frame.size());
  16678. ws::Opcode opcode;
  16679. std::string payload;
  16680. bool fin;
  16681. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16682. false, 1024));
  16683. }
  16684. // Ping with FIN=1 and payload_len=125 - should succeed
  16685. {
  16686. detail::BufferStream strm;
  16687. std::string frame;
  16688. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  16689. frame += static_cast<char>(125); // payload_len=125
  16690. frame += std::string(125, 'x');
  16691. strm.write(frame.data(), frame.size());
  16692. ws::Opcode opcode;
  16693. std::string payload;
  16694. bool fin;
  16695. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16696. false, 1024));
  16697. EXPECT_EQ(ws::Opcode::Ping, opcode);
  16698. EXPECT_EQ(125u, payload.size());
  16699. EXPECT_TRUE(fin);
  16700. }
  16701. }
  16702. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  16703. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  16704. // length MUST be 0.
  16705. // MSB set - must be rejected
  16706. {
  16707. detail::BufferStream strm;
  16708. std::string frame;
  16709. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  16710. frame += static_cast<char>(127); // 64-bit extended length
  16711. frame += static_cast<char>(0x80); // MSB set (invalid)
  16712. frame += std::string(7, '\0'); // remaining 7 bytes of length
  16713. strm.write(frame.data(), frame.size());
  16714. ws::Opcode opcode;
  16715. std::string payload;
  16716. bool fin;
  16717. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16718. false, 1024));
  16719. }
  16720. // MSB clear - should pass length parsing (will be rejected by max_len,
  16721. // but that's a different check; use a small length to verify)
  16722. {
  16723. detail::BufferStream strm;
  16724. std::string frame;
  16725. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  16726. frame += static_cast<char>(127); // 64-bit extended length
  16727. frame += std::string(7, '\0'); // high bytes = 0
  16728. frame += static_cast<char>(0x03); // length = 3
  16729. frame += "abc";
  16730. strm.write(frame.data(), frame.size());
  16731. ws::Opcode opcode;
  16732. std::string payload;
  16733. bool fin;
  16734. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16735. false, 1024));
  16736. EXPECT_EQ(ws::Opcode::Text, opcode);
  16737. EXPECT_EQ("abc", payload);
  16738. }
  16739. }
  16740. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  16741. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  16742. // Valid UTF-8
  16743. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  16744. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  16745. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  16746. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  16747. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  16748. // Invalid UTF-8
  16749. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  16750. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  16751. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  16752. EXPECT_FALSE(
  16753. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  16754. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  16755. }
  16756. TEST(WebSocketTest, ConnectAndDisconnect) {
  16757. Server svr;
  16758. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  16759. std::string msg;
  16760. while (ws.read(msg)) {}
  16761. });
  16762. auto port = svr.bind_to_any_port(HOST);
  16763. std::thread t([&]() { svr.listen_after_bind(); });
  16764. svr.wait_until_ready();
  16765. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  16766. auto res = client.connect();
  16767. ASSERT_TRUE(res);
  16768. EXPECT_EQ(Error::Success, res.error());
  16769. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  16770. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  16771. EXPECT_TRUE(client.is_open());
  16772. client.close();
  16773. EXPECT_FALSE(client.is_open());
  16774. svr.stop();
  16775. t.join();
  16776. }
  16777. TEST(WebSocketTest, ValidURL) {
  16778. ws::WebSocketClient ws1("ws://localhost:8080/path");
  16779. EXPECT_TRUE(ws1.is_valid());
  16780. ws::WebSocketClient ws2("ws://example.com/path");
  16781. EXPECT_TRUE(ws2.is_valid());
  16782. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  16783. EXPECT_TRUE(ws3.is_valid());
  16784. #ifdef CPPHTTPLIB_SSL_ENABLED
  16785. ws::WebSocketClient wss1("wss://example.com/path");
  16786. EXPECT_TRUE(wss1.is_valid());
  16787. ws::WebSocketClient wss2("wss://example.com:443/path");
  16788. EXPECT_TRUE(wss2.is_valid());
  16789. #endif
  16790. }
  16791. TEST(WebSocketTest, InvalidURL) {
  16792. // No scheme
  16793. ws::WebSocketClient ws1("localhost:8080/path");
  16794. EXPECT_FALSE(ws1.is_valid());
  16795. // No path
  16796. ws::WebSocketClient ws2("ws://localhost:8080");
  16797. EXPECT_FALSE(ws2.is_valid());
  16798. // Empty string
  16799. ws::WebSocketClient ws3("");
  16800. EXPECT_FALSE(ws3.is_valid());
  16801. // Missing host
  16802. ws::WebSocketClient ws4("ws://:8080/path");
  16803. EXPECT_FALSE(ws4.is_valid());
  16804. // Port number overflow — should not crash
  16805. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  16806. EXPECT_FALSE(ws5.is_valid());
  16807. // Port out of range
  16808. ws::WebSocketClient ws6("ws://localhost:99999/path");
  16809. EXPECT_FALSE(ws6.is_valid());
  16810. }
  16811. TEST(WebSocketTest, UnsupportedScheme) {
  16812. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16813. ws::WebSocketClient ws1("http://localhost:8080/path");
  16814. EXPECT_FALSE(ws1.is_valid());
  16815. ws::WebSocketClient ws2("https://localhost:8080/path");
  16816. EXPECT_FALSE(ws2.is_valid());
  16817. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  16818. EXPECT_FALSE(ws3.is_valid());
  16819. #else
  16820. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  16821. std::invalid_argument);
  16822. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  16823. std::invalid_argument);
  16824. #endif
  16825. }
  16826. TEST(WebSocketTest, ConnectWhenInvalid) {
  16827. ws::WebSocketClient ws("not a valid url");
  16828. EXPECT_FALSE(ws.is_valid());
  16829. auto res = ws.connect();
  16830. EXPECT_FALSE(res);
  16831. EXPECT_EQ(Error::Connection, res.error());
  16832. EXPECT_EQ(-1, res.status());
  16833. }
  16834. TEST(WebSocketTest, ConnectRefusedReportsError) {
  16835. // Grab a port that is free, then close it again so nothing listens there
  16836. Server svr;
  16837. auto port = svr.bind_to_any_port(HOST);
  16838. svr.stop();
  16839. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  16840. auto res = client.connect();
  16841. ASSERT_FALSE(res);
  16842. EXPECT_EQ(Error::Connection, res.error());
  16843. EXPECT_EQ(-1, res.status());
  16844. }
  16845. TEST(WebSocketTest, DefaultPort) {
  16846. ws::WebSocketClient ws1("ws://example.com/path");
  16847. EXPECT_TRUE(ws1.is_valid());
  16848. // ws:// defaults to port 80 (verified by successful parse)
  16849. #ifdef CPPHTTPLIB_SSL_ENABLED
  16850. ws::WebSocketClient ws2("wss://example.com/path");
  16851. EXPECT_TRUE(ws2.is_valid());
  16852. // wss:// defaults to port 443 (verified by successful parse)
  16853. #endif
  16854. }
  16855. TEST(WebSocketTest, IPv6LiteralAddress) {
  16856. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  16857. EXPECT_TRUE(ws1.is_valid());
  16858. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  16859. EXPECT_TRUE(ws2.is_valid());
  16860. }
  16861. TEST(WebSocketTest, ComplexPath) {
  16862. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  16863. EXPECT_TRUE(ws1.is_valid());
  16864. ws::WebSocketClient ws2("ws://localhost:8080/");
  16865. EXPECT_TRUE(ws2.is_valid());
  16866. }
  16867. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  16868. Server svr;
  16869. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  16870. std::string msg;
  16871. while (ws.read(msg)) {}
  16872. });
  16873. auto port = svr.bind_to_any_port(HOST);
  16874. std::thread t([&]() { svr.listen_after_bind(); });
  16875. svr.wait_until_ready();
  16876. auto another_host = "example.com";
  16877. auto wrong_ip = "192.0.2.1";
  16878. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  16879. client.set_hostname_addr_map({{another_host, wrong_ip}});
  16880. ASSERT_TRUE(client.connect());
  16881. EXPECT_TRUE(client.is_open());
  16882. client.close();
  16883. svr.stop();
  16884. t.join();
  16885. }
  16886. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  16887. Server svr;
  16888. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  16889. std::string msg;
  16890. while (ws.read(msg)) {}
  16891. });
  16892. auto port = svr.bind_to_any_port(HOST);
  16893. std::thread t([&]() { svr.listen_after_bind(); });
  16894. svr.wait_until_ready();
  16895. auto wrong_ip = "192.0.2.1";
  16896. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  16897. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  16898. client.set_connection_timeout(1);
  16899. client.set_read_timeout(1);
  16900. client.set_write_timeout(1);
  16901. EXPECT_FALSE(client.connect());
  16902. EXPECT_FALSE(client.is_open());
  16903. svr.stop();
  16904. t.join();
  16905. }
  16906. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  16907. // A mapped value that is not an IP literal must be resolved. HOST resolves
  16908. // from the hosts file, so this test needs no external DNS. "target.invalid"
  16909. // (RFC 6761) is only a map key and the Host header value.
  16910. auto host = "target.invalid";
  16911. Server svr;
  16912. std::string received_host;
  16913. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  16914. received_host = req.get_header_value("Host");
  16915. std::string msg;
  16916. while (ws.read(msg)) {}
  16917. });
  16918. auto port = svr.bind_to_any_port(HOST);
  16919. std::thread t([&]() { svr.listen_after_bind(); });
  16920. // ASSERT_* below returns from the test body, which would leave t joinable
  16921. // and make ~thread call std::terminate.
  16922. auto se = detail::scope_exit([&] {
  16923. svr.stop();
  16924. if (t.joinable()) { t.join(); }
  16925. });
  16926. svr.wait_until_ready();
  16927. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  16928. std::to_string(port) + "/ws");
  16929. client.set_hostname_addr_map({{host, HOST}});
  16930. ASSERT_TRUE(client.connect());
  16931. EXPECT_TRUE(client.is_open());
  16932. client.close();
  16933. svr.stop();
  16934. t.join();
  16935. // The mapping only redirects the connection; the identity stays host_.
  16936. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  16937. }
  16938. class WebSocketIntegrationTest : public ::testing::Test {
  16939. protected:
  16940. void SetUp() override {
  16941. server_ = httplib::detail::make_unique<Server>();
  16942. setup_server();
  16943. start_server();
  16944. }
  16945. void TearDown() override {
  16946. server_->stop();
  16947. if (server_thread_.joinable()) { server_thread_.join(); }
  16948. }
  16949. void setup_server() {
  16950. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  16951. std::string msg;
  16952. ws::ReadResult ret;
  16953. while ((ret = ws.read(msg))) {
  16954. if (ret == ws::Binary) {
  16955. ws.send(msg.data(), msg.size());
  16956. } else {
  16957. ws.send(msg);
  16958. }
  16959. }
  16960. });
  16961. server_->WebSocket("/ws-echo-string",
  16962. [](const Request &, ws::WebSocket &ws) {
  16963. std::string msg;
  16964. while (ws.read(msg)) {
  16965. ws.send("echo: " + msg);
  16966. }
  16967. });
  16968. server_->WebSocket(
  16969. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  16970. // Echo back request metadata
  16971. ws.send("path:" + req.path);
  16972. ws.send("header:" + req.get_header_value("X-Test-Header"));
  16973. std::string msg;
  16974. while (ws.read(msg)) {}
  16975. });
  16976. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  16977. std::string msg;
  16978. ws.read(msg); // wait for a message
  16979. ws.close();
  16980. });
  16981. server_->WebSocket("/ws-close-status",
  16982. [](const Request &, ws::WebSocket &ws) {
  16983. std::string msg;
  16984. ws.read(msg); // wait for a message
  16985. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  16986. });
  16987. server_->WebSocket(
  16988. "/ws-subprotocol",
  16989. [](const Request &, ws::WebSocket &ws) {
  16990. std::string msg;
  16991. while (ws.read(msg)) {
  16992. ws.send(msg);
  16993. }
  16994. },
  16995. [](const std::vector<std::string> &protocols) -> std::string {
  16996. for (const auto &p : protocols) {
  16997. if (p == "graphql-ws") { return p; }
  16998. }
  16999. return "";
  17000. });
  17001. }
  17002. void start_server() {
  17003. port_ = server_->bind_to_any_port(HOST);
  17004. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  17005. server_->wait_until_ready();
  17006. }
  17007. std::unique_ptr<Server> server_;
  17008. std::thread server_thread_;
  17009. int port_ = 0;
  17010. };
  17011. TEST_F(WebSocketIntegrationTest, TextEcho) {
  17012. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17013. "/ws-echo");
  17014. ASSERT_TRUE(client.connect());
  17015. ASSERT_TRUE(client.is_open());
  17016. ASSERT_TRUE(client.send("Hello WebSocket"));
  17017. std::string msg;
  17018. EXPECT_EQ(ws::Text, client.read(msg));
  17019. EXPECT_EQ("Hello WebSocket", msg);
  17020. client.close();
  17021. }
  17022. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  17023. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17024. "/ws-echo");
  17025. ASSERT_TRUE(client.connect());
  17026. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  17027. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  17028. std::string msg;
  17029. EXPECT_EQ(ws::Binary, client.read(msg));
  17030. EXPECT_EQ(binary_data, msg);
  17031. client.close();
  17032. }
  17033. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  17034. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17035. "/ws-echo");
  17036. ASSERT_TRUE(client.connect());
  17037. for (int i = 0; i < 10; i++) {
  17038. auto text = "message " + std::to_string(i);
  17039. ASSERT_TRUE(client.send(text));
  17040. std::string msg;
  17041. ASSERT_TRUE(client.read(msg));
  17042. EXPECT_EQ(text, msg);
  17043. }
  17044. client.close();
  17045. }
  17046. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  17047. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17048. "/ws-close");
  17049. ASSERT_TRUE(client.connect());
  17050. // Send a message to trigger the server to close
  17051. ASSERT_TRUE(client.send("trigger close"));
  17052. // The server will close, so read should return false
  17053. std::string msg;
  17054. EXPECT_FALSE(client.read(msg));
  17055. EXPECT_FALSE(client.is_open());
  17056. }
  17057. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  17058. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17059. "/ws-echo");
  17060. ASSERT_TRUE(client.connect());
  17061. // 128KB message
  17062. std::string large_data(128 * 1024, 'X');
  17063. ASSERT_TRUE(client.send(large_data));
  17064. std::string msg;
  17065. ASSERT_TRUE(client.read(msg));
  17066. EXPECT_EQ(large_data, msg);
  17067. client.close();
  17068. }
  17069. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  17070. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17071. "/ws-echo");
  17072. ASSERT_TRUE(client.connect());
  17073. const int num_threads = 4;
  17074. std::vector<std::thread> threads;
  17075. std::atomic<int> send_count{0};
  17076. for (int t = 0; t < num_threads; t++) {
  17077. threads.emplace_back([&client, &send_count, t]() {
  17078. for (int i = 0; i < 5; i++) {
  17079. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  17080. if (client.send(text)) { send_count++; }
  17081. }
  17082. });
  17083. }
  17084. for (auto &th : threads) {
  17085. th.join();
  17086. }
  17087. int received = 0;
  17088. std::string msg;
  17089. while (received < send_count.load()) {
  17090. if (!client.read(msg)) { break; }
  17091. received++;
  17092. }
  17093. EXPECT_EQ(send_count.load(), received);
  17094. client.close();
  17095. }
  17096. TEST_F(WebSocketIntegrationTest, ReadString) {
  17097. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17098. "/ws-echo-string");
  17099. ASSERT_TRUE(client.connect());
  17100. ASSERT_TRUE(client.send("hello"));
  17101. std::string msg;
  17102. ASSERT_TRUE(client.read(msg));
  17103. EXPECT_EQ("echo: hello", msg);
  17104. ASSERT_TRUE(client.send("world"));
  17105. ASSERT_TRUE(client.read(msg));
  17106. EXPECT_EQ("echo: world", msg);
  17107. client.close();
  17108. }
  17109. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  17110. Headers headers = {{"X-Test-Header", "test-value"}};
  17111. ws::WebSocketClient client(
  17112. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  17113. ASSERT_TRUE(client.connect());
  17114. std::string msg;
  17115. ASSERT_TRUE(client.read(msg));
  17116. EXPECT_EQ("path:/ws-request-info", msg);
  17117. ASSERT_TRUE(client.read(msg));
  17118. EXPECT_EQ("header:test-value", msg);
  17119. client.close();
  17120. }
  17121. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  17122. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17123. "/ws-echo");
  17124. client.set_read_timeout(1, 0); // 1 second
  17125. ASSERT_TRUE(client.connect());
  17126. // Don't send anything — server echo handler waits for a message,
  17127. // so read() should time out and return false.
  17128. std::string msg;
  17129. EXPECT_FALSE(client.read(msg));
  17130. }
  17131. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  17132. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17133. "/ws-echo");
  17134. client.set_read_timeout(5, 0);
  17135. ASSERT_TRUE(client.connect());
  17136. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  17137. // The server should reject it and close the connection.
  17138. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  17139. client.send(oversized);
  17140. // The server's read() should have failed due to payload limit,
  17141. // so our read() should return false (connection closed).
  17142. std::string msg;
  17143. EXPECT_FALSE(client.read(msg));
  17144. }
  17145. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  17146. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17147. "/ws-echo");
  17148. client.set_read_timeout(10, 0);
  17149. ASSERT_TRUE(client.connect());
  17150. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  17151. // This should succeed.
  17152. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  17153. ASSERT_TRUE(client.send(at_limit));
  17154. std::string msg;
  17155. ASSERT_TRUE(client.read(msg));
  17156. EXPECT_EQ(at_limit.size(), msg.size());
  17157. client.close();
  17158. }
  17159. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  17160. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17161. "/nonexistent");
  17162. auto res = client.connect();
  17163. EXPECT_FALSE(res);
  17164. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  17165. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  17166. EXPECT_FALSE(client.is_open());
  17167. }
  17168. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  17169. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17170. "/ws-echo");
  17171. ASSERT_TRUE(client.connect());
  17172. ASSERT_TRUE(client.send(""));
  17173. std::string msg;
  17174. EXPECT_EQ(ws::Text, client.read(msg));
  17175. EXPECT_EQ("", msg);
  17176. client.close();
  17177. }
  17178. TEST_F(WebSocketIntegrationTest, Reconnect) {
  17179. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17180. "/ws-echo");
  17181. // First connection
  17182. ASSERT_TRUE(client.connect());
  17183. ASSERT_TRUE(client.send("first"));
  17184. std::string msg;
  17185. ASSERT_TRUE(client.read(msg));
  17186. EXPECT_EQ("first", msg);
  17187. client.close();
  17188. EXPECT_FALSE(client.is_open());
  17189. // Reconnect using the same client object
  17190. ASSERT_TRUE(client.connect());
  17191. ASSERT_TRUE(client.is_open());
  17192. ASSERT_TRUE(client.send("second"));
  17193. ASSERT_TRUE(client.read(msg));
  17194. EXPECT_EQ("second", msg);
  17195. client.close();
  17196. }
  17197. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  17198. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17199. "/ws-close-status");
  17200. ASSERT_TRUE(client.connect());
  17201. // Trigger the server to close with GoingAway status
  17202. ASSERT_TRUE(client.send("trigger"));
  17203. // read() should return false after receiving the close frame
  17204. std::string msg;
  17205. EXPECT_FALSE(client.read(msg));
  17206. EXPECT_FALSE(client.is_open());
  17207. }
  17208. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  17209. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17210. "/ws-echo");
  17211. ASSERT_TRUE(client.connect());
  17212. client.close(ws::CloseStatus::GoingAway, "client leaving");
  17213. EXPECT_FALSE(client.is_open());
  17214. }
  17215. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  17216. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  17217. ws::WebSocketClient client(
  17218. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  17219. ASSERT_TRUE(client.connect());
  17220. // Server should have selected graphql-ws
  17221. EXPECT_EQ("graphql-ws", client.subprotocol());
  17222. client.close();
  17223. }
  17224. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  17225. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  17226. ws::WebSocketClient client(
  17227. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  17228. ASSERT_TRUE(client.connect());
  17229. // Server should not have selected any subprotocol
  17230. EXPECT_TRUE(client.subprotocol().empty());
  17231. client.close();
  17232. }
  17233. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  17234. // Connect without requesting any subprotocol
  17235. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17236. "/ws-subprotocol");
  17237. ASSERT_TRUE(client.connect());
  17238. EXPECT_TRUE(client.subprotocol().empty());
  17239. client.close();
  17240. }
  17241. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  17242. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17243. "/ws-echo");
  17244. client.set_tcp_nodelay(true);
  17245. client.set_connection_timeout(3, 0);
  17246. bool socket_options_called = false;
  17247. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  17248. ASSERT_TRUE(client.connect());
  17249. ASSERT_TRUE(client.is_open());
  17250. EXPECT_TRUE(socket_options_called);
  17251. ASSERT_TRUE(client.send("hello"));
  17252. std::string msg;
  17253. auto result = client.read(msg);
  17254. EXPECT_EQ(result, ws::ReadResult::Text);
  17255. EXPECT_EQ(msg, "hello");
  17256. client.close();
  17257. }
  17258. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  17259. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17260. "/ws-echo");
  17261. client.set_connection_timeout(std::chrono::seconds(3));
  17262. client.set_write_timeout(std::chrono::seconds(3));
  17263. // A sub-second remainder exercises the seconds/microseconds split.
  17264. client.set_read_timeout(std::chrono::milliseconds(1500));
  17265. ASSERT_TRUE(client.connect());
  17266. auto start = std::chrono::steady_clock::now();
  17267. std::string msg;
  17268. EXPECT_EQ(client.read(msg), ws::ReadResult::Fail);
  17269. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17270. std::chrono::steady_clock::now() - start)
  17271. .count();
  17272. // Above 1s so that dropping the microseconds half of the split fails here,
  17273. // and well under the 300s default so that ignoring the setter fails too.
  17274. EXPECT_GE(elapsed, 1400);
  17275. EXPECT_LT(elapsed, 30000);
  17276. }
  17277. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  17278. Server svr;
  17279. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  17280. if (!req.has_header("Authorization")) {
  17281. res.status = StatusCode::Unauthorized_401;
  17282. res.set_content("Unauthorized", "text/plain");
  17283. return Server::HandlerResponse::Handled;
  17284. }
  17285. return Server::HandlerResponse::Unhandled;
  17286. });
  17287. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  17288. std::string msg;
  17289. while (ws.read(msg)) {
  17290. ws.send(msg);
  17291. }
  17292. });
  17293. auto port = svr.bind_to_any_port("localhost");
  17294. std::thread t([&]() { svr.listen_after_bind(); });
  17295. svr.wait_until_ready();
  17296. // Without Authorization header - should be rejected before upgrade
  17297. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  17298. EXPECT_FALSE(client1.connect());
  17299. // With Authorization header - should succeed
  17300. Headers headers = {{"Authorization", "Bearer token123"}};
  17301. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  17302. headers);
  17303. ASSERT_TRUE(client2.connect());
  17304. ASSERT_TRUE(client2.send("hello"));
  17305. std::string msg;
  17306. ASSERT_TRUE(client2.read(msg));
  17307. EXPECT_EQ("hello", msg);
  17308. client2.close();
  17309. svr.stop();
  17310. t.join();
  17311. }
  17312. TEST(WebSocketTest, QueryStringInHandshake) {
  17313. Server svr;
  17314. std::mutex mtx;
  17315. std::string received_target;
  17316. std::string received_token;
  17317. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  17318. {
  17319. std::lock_guard<std::mutex> lock(mtx);
  17320. received_target = req.target;
  17321. if (req.has_param("token")) {
  17322. received_token = req.get_param_value("token");
  17323. }
  17324. }
  17325. std::string msg;
  17326. while (ws.read(msg)) {
  17327. ws.send(msg);
  17328. }
  17329. });
  17330. auto port = svr.bind_to_any_port("localhost");
  17331. std::thread t([&]() { svr.listen_after_bind(); });
  17332. svr.wait_until_ready();
  17333. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  17334. "/ws?token=ABC&session=123");
  17335. ASSERT_TRUE(client.connect());
  17336. // Round-trip ensures the handler has run and captured the request.
  17337. ASSERT_TRUE(client.send("hello"));
  17338. std::string msg;
  17339. ASSERT_TRUE(client.read(msg));
  17340. EXPECT_EQ("hello", msg);
  17341. client.close();
  17342. {
  17343. std::lock_guard<std::mutex> lock(mtx);
  17344. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  17345. EXPECT_EQ("ABC", received_token);
  17346. }
  17347. svr.stop();
  17348. t.join();
  17349. }
  17350. // Run a handshake against a throwaway server and hand the request the server
  17351. // received back to the caller, so tests can assert on the headers the client
  17352. // actually put on the wire.
  17353. static void capture_websocket_handshake_request(
  17354. const Headers &client_headers,
  17355. std::function<void(const Request &, int port)> verify) {
  17356. Server svr;
  17357. std::mutex mtx;
  17358. Request received;
  17359. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  17360. {
  17361. std::lock_guard<std::mutex> lock(mtx);
  17362. received = req;
  17363. }
  17364. std::string msg;
  17365. while (ws.read(msg)) {
  17366. ws.send(msg);
  17367. }
  17368. });
  17369. auto port = svr.bind_to_any_port("localhost");
  17370. std::thread t([&]() { svr.listen_after_bind(); });
  17371. auto se = detail::scope_exit([&] {
  17372. svr.stop();
  17373. t.join();
  17374. });
  17375. svr.wait_until_ready();
  17376. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  17377. client_headers);
  17378. ASSERT_TRUE(client.connect());
  17379. ASSERT_TRUE(client.send("hello"));
  17380. std::string msg;
  17381. ASSERT_TRUE(client.read(msg));
  17382. client.close();
  17383. {
  17384. std::lock_guard<std::mutex> lock(mtx);
  17385. verify(received, port);
  17386. }
  17387. }
  17388. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  17389. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  17390. // Non-default port must be present in the Host header. Default ports
  17391. // (80/443) are omitted; that logic is covered by
  17392. // MakeHostAndPortStringTest.
  17393. EXPECT_EQ("localhost:" + std::to_string(port),
  17394. req.get_header_value("Host"));
  17395. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  17396. req.get_header_value("User-Agent"));
  17397. EXPECT_FALSE(req.has_header("Accept"));
  17398. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  17399. EXPECT_FALSE(req.has_header("Content-Length"));
  17400. });
  17401. }
  17402. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  17403. capture_websocket_handshake_request(
  17404. {{"Host", "example.com"},
  17405. {"User-Agent", "custom-agent"},
  17406. {"X-Custom", "value"}},
  17407. [](const Request &req, int) {
  17408. EXPECT_EQ("example.com", req.get_header_value("Host"));
  17409. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  17410. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  17411. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  17412. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  17413. });
  17414. }
  17415. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  17416. capture_websocket_handshake_request(
  17417. {{"Upgrade", "bogus"},
  17418. {"Connection", "close"},
  17419. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  17420. {"Sec-WebSocket-Version", "8"}},
  17421. [](const Request &req, int) {
  17422. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  17423. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  17424. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  17425. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  17426. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  17427. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  17428. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  17429. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  17430. req.get_header_value("Sec-WebSocket-Key"));
  17431. });
  17432. }
  17433. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  17434. // A header the client refuses to send must abort the handshake before any
  17435. // part of it reaches the wire; a lone request line would otherwise sit in
  17436. // the peer's buffer as a truncated request.
  17437. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17438. ASSERT_NE(INVALID_SOCKET, srv);
  17439. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  17440. sockaddr_in addr{};
  17441. addr.sin_family = AF_INET;
  17442. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  17443. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17444. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17445. ASSERT_EQ(0, ::listen(srv, 1));
  17446. sockaddr_in bound{};
  17447. socklen_t bound_len = sizeof(bound);
  17448. ASSERT_EQ(
  17449. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  17450. auto port = ntohs(bound.sin_port);
  17451. ssize_t received = -1;
  17452. std::thread t([&] {
  17453. // Bound every blocking call so a regression fails the test with a bad
  17454. // value instead of hanging the suite.
  17455. fd_set rfds;
  17456. FD_ZERO(&rfds);
  17457. FD_SET(srv, &rfds);
  17458. timeval tv{5, 0};
  17459. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  17460. 0) {
  17461. return;
  17462. }
  17463. sockaddr_in cli_addr{};
  17464. socklen_t cli_len = sizeof(cli_addr);
  17465. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17466. if (cli == INVALID_SOCKET) { return; }
  17467. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  17468. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  17469. char buf[4096];
  17470. received = ::recv(cli, buf, sizeof(buf), 0);
  17471. });
  17472. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  17473. // connect() has already shut the socket down by the time it returns false,
  17474. // so the peer sees EOF without waiting for the client to be destroyed.
  17475. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  17476. {{"X-Bad", "a\r\nInjected: 1"}});
  17477. EXPECT_FALSE(client.connect());
  17478. t.join();
  17479. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  17480. EXPECT_EQ(0, received);
  17481. }
  17482. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  17483. // The socket path doubles as the URL host, so it must not contain '/'.
  17484. const char *shard = getenv("GTEST_SHARD_INDEX");
  17485. const std::string sock_path =
  17486. shard ? std::string("httplib-ws-") + shard + ".sock"
  17487. : std::string("httplib-ws.sock");
  17488. std::remove(sock_path.c_str());
  17489. Server svr;
  17490. std::mutex mtx;
  17491. std::string received_host;
  17492. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  17493. {
  17494. std::lock_guard<std::mutex> lock(mtx);
  17495. received_host = req.get_header_value("Host");
  17496. }
  17497. std::string msg;
  17498. while (ws.read(msg)) {
  17499. ws.send(msg);
  17500. }
  17501. });
  17502. svr.set_address_family(AF_UNIX);
  17503. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  17504. auto se = detail::scope_exit([&] {
  17505. svr.stop();
  17506. t.join();
  17507. std::remove(sock_path.c_str());
  17508. });
  17509. svr.wait_until_ready();
  17510. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  17511. client.set_address_family(AF_UNIX);
  17512. ASSERT_TRUE(client.connect());
  17513. ASSERT_TRUE(client.send("hello"));
  17514. std::string msg;
  17515. ASSERT_TRUE(client.read(msg));
  17516. client.close();
  17517. {
  17518. std::lock_guard<std::mutex> lock(mtx);
  17519. // There is no host:port for a Unix socket, so the same "localhost"
  17520. // placeholder the HTTP client uses is expected.
  17521. EXPECT_EQ("localhost", received_host);
  17522. }
  17523. }
  17524. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  17525. class WebSocketSSLIntegrationTest : public ::testing::Test {
  17526. protected:
  17527. void SetUp() override {
  17528. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  17529. SERVER_PRIVATE_KEY_FILE);
  17530. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  17531. std::string msg;
  17532. ws::ReadResult ret;
  17533. while ((ret = ws.read(msg))) {
  17534. if (ret == ws::Binary) {
  17535. ws.send(msg.data(), msg.size());
  17536. } else {
  17537. ws.send(msg);
  17538. }
  17539. }
  17540. });
  17541. port_ = server_->bind_to_any_port(HOST);
  17542. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  17543. server_->wait_until_ready();
  17544. }
  17545. void TearDown() override {
  17546. server_->stop();
  17547. if (server_thread_.joinable()) { server_thread_.join(); }
  17548. }
  17549. std::unique_ptr<SSLServer> server_;
  17550. std::thread server_thread_;
  17551. int port_ = 0;
  17552. };
  17553. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  17554. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  17555. "/ws-echo");
  17556. client.enable_server_certificate_verification(false);
  17557. ASSERT_TRUE(client.connect());
  17558. ASSERT_TRUE(client.is_open());
  17559. ASSERT_TRUE(client.send("Hello WSS"));
  17560. std::string msg;
  17561. EXPECT_EQ(ws::Text, client.read(msg));
  17562. EXPECT_EQ("Hello WSS", msg);
  17563. client.close();
  17564. }
  17565. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  17566. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  17567. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  17568. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  17569. // client (without calling close() first) is the only path that runs
  17570. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  17571. // bug exactly.
  17572. //
  17573. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  17574. // when linked against an instrumented libssl; run under Valgrind to catch it
  17575. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  17576. // suite (the freed session otherwise stalls on the close handshake) — this test
  17577. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  17578. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  17579. {
  17580. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  17581. "/ws-echo");
  17582. client.enable_server_certificate_verification(false);
  17583. client.set_read_timeout(2, 0);
  17584. client.set_write_timeout(2, 0);
  17585. ASSERT_TRUE(client.connect());
  17586. ASSERT_TRUE(client.is_open());
  17587. ASSERT_TRUE(client.send("still open"));
  17588. // Intentionally do NOT call client.close(): leaving scope runs
  17589. // shutdown_and_close() with the WebSocket still open, which must send the
  17590. // close frame while the TLS session is still alive.
  17591. }
  17592. }
  17593. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  17594. // shutdown_and_close() at the start of connect(), reproducing the same
  17595. // use-after-free within the test body rather than at scope exit. The second
  17596. // connect must succeed and echo, proving the close handshake ran over a live
  17597. // session. See the note above about memory-tool requirements.
  17598. TEST_F(WebSocketSSLIntegrationTest,
  17599. ReconnectWhileOpenSendsCloseOverLiveSession) {
  17600. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  17601. "/ws-echo");
  17602. client.enable_server_certificate_verification(false);
  17603. client.set_read_timeout(2, 0);
  17604. client.set_write_timeout(2, 0);
  17605. ASSERT_TRUE(client.connect());
  17606. ASSERT_TRUE(client.is_open());
  17607. ASSERT_TRUE(client.send("still open"));
  17608. // Reconnect without closing first: connect() calls shutdown_and_close() on
  17609. // the still-open connection, which must not touch a freed TLS session.
  17610. ASSERT_TRUE(client.connect());
  17611. ASSERT_TRUE(client.is_open());
  17612. ASSERT_TRUE(client.send("after reconnect"));
  17613. std::string msg;
  17614. EXPECT_EQ(ws::Text, client.read(msg));
  17615. EXPECT_EQ("after reconnect", msg);
  17616. client.close();
  17617. }
  17618. #endif
  17619. #ifdef CPPHTTPLIB_SSL_ENABLED
  17620. class WebSocketSSLCATest : public ::testing::Test {
  17621. protected:
  17622. void SetUp() override {
  17623. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  17624. SERVER_PRIVATE_KEY_FILE);
  17625. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  17626. std::string msg;
  17627. while (ws.read(msg)) {
  17628. ws.send(msg);
  17629. }
  17630. });
  17631. port_ = server_->bind_to_any_port("127.0.0.1");
  17632. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  17633. server_->wait_until_ready();
  17634. }
  17635. void TearDown() override {
  17636. server_->stop();
  17637. if (server_thread_.joinable()) { server_thread_.join(); }
  17638. }
  17639. std::string url() const {
  17640. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  17641. }
  17642. std::unique_ptr<SSLServer> server_;
  17643. std::thread server_thread_;
  17644. int port_ = 0;
  17645. };
  17646. // A custom CA loaded as PEM verifies the server with full certificate
  17647. // verification enabled
  17648. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  17649. ws::WebSocketClient client(url());
  17650. std::string cert;
  17651. read_file(SERVER_CERT2_FILE, cert);
  17652. client.load_ca_cert_store(cert.c_str(), cert.size());
  17653. ASSERT_TRUE(client.connect());
  17654. ASSERT_TRUE(client.send("hello"));
  17655. std::string msg;
  17656. EXPECT_EQ(ws::Text, client.read(msg));
  17657. EXPECT_EQ("hello", msg);
  17658. client.close();
  17659. }
  17660. // A custom CA that does not cover the server must fail verification (the
  17661. // custom CA is exclusive; system certs are not loaded alongside it)
  17662. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  17663. ws::WebSocketClient client(url());
  17664. std::string cert;
  17665. read_file(CLIENT_CA_CERT_FILE, cert);
  17666. client.load_ca_cert_store(cert.c_str(), cert.size());
  17667. auto res = client.connect();
  17668. ASSERT_FALSE(res);
  17669. EXPECT_EQ(Error::SSLServerVerification, res.error());
  17670. EXPECT_EQ(-1, res.status());
  17671. EXPECT_NE(0u, res.ssl_backend_error());
  17672. }
  17673. // The same CA as a file path rather than PEM in memory
  17674. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  17675. ws::WebSocketClient client(url());
  17676. client.set_ca_cert_path(SERVER_CERT2_FILE);
  17677. ASSERT_TRUE(client.connect());
  17678. ASSERT_TRUE(client.send("hello"));
  17679. std::string msg;
  17680. EXPECT_EQ(ws::Text, client.read(msg));
  17681. EXPECT_EQ("hello", msg);
  17682. client.close();
  17683. }
  17684. // ...and a CA file that does not cover the server still fails, so it is the
  17685. // path above that decides the outcome
  17686. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  17687. ws::WebSocketClient client(url());
  17688. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  17689. ASSERT_FALSE(client.connect());
  17690. }
  17691. // Regression test: reconnecting with a native custom CA store used to reuse
  17692. // a store handle the previous TLS context had already freed (use-after-free
  17693. // under the OpenSSL backend). The context now lives as long as the client.
  17694. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  17695. ws::WebSocketClient client(url());
  17696. std::string cert;
  17697. read_file(SERVER_CERT2_FILE, cert);
  17698. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  17699. ASSERT_TRUE(client.connect());
  17700. client.close();
  17701. ASSERT_TRUE(client.connect());
  17702. ASSERT_TRUE(client.send("again"));
  17703. std::string msg;
  17704. EXPECT_EQ(ws::Text, client.read(msg));
  17705. EXPECT_EQ("again", msg);
  17706. client.close();
  17707. }
  17708. // Regression test: a certificate with a trusted chain but no identity match
  17709. // for the server IP must be rejected. The Mbed TLS backend used to skip
  17710. // verification entirely for IP hosts, so this connection succeeded there.
  17711. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  17712. // chain verification while the identity check must still fail.
  17713. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  17714. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17715. ASSERT_TRUE(svr.is_valid());
  17716. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  17717. std::string msg;
  17718. while (ws.read(msg)) {
  17719. ws.send(msg);
  17720. }
  17721. });
  17722. auto port = svr.bind_to_any_port("127.0.0.1");
  17723. auto t = std::thread([&]() { svr.listen_after_bind(); });
  17724. auto se = detail::scope_exit([&] {
  17725. svr.stop();
  17726. t.join();
  17727. });
  17728. svr.wait_until_ready();
  17729. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  17730. "/echo");
  17731. std::string cert;
  17732. read_file(SERVER_CERT_FILE, cert);
  17733. client.load_ca_cert_store(cert.c_str(), cert.size());
  17734. ASSERT_FALSE(client.connect());
  17735. }
  17736. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  17737. // SNI, so nothing binds the host name to the TLS session. These bind the
  17738. // server to "localhost" instead, the only shape that exercises the SNI and
  17739. // hostname-verification path with certificate verification left enabled.
  17740. class WebSocketSSLDnsHostTest : public ::testing::Test {
  17741. protected:
  17742. void Start(const char *cert_file) {
  17743. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  17744. SERVER_PRIVATE_KEY_FILE);
  17745. ASSERT_TRUE(server_->is_valid());
  17746. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  17747. std::string msg;
  17748. while (ws.read(msg)) {
  17749. ws.send(msg);
  17750. }
  17751. });
  17752. port_ = server_->bind_to_any_port("localhost");
  17753. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  17754. server_->wait_until_ready();
  17755. }
  17756. void TearDown() override {
  17757. if (server_) { server_->stop(); }
  17758. if (server_thread_.joinable()) { server_thread_.join(); }
  17759. }
  17760. std::string url() const {
  17761. return "wss://localhost:" + std::to_string(port_) + "/echo";
  17762. }
  17763. std::unique_ptr<SSLServer> server_;
  17764. std::thread server_thread_;
  17765. int port_ = 0;
  17766. };
  17767. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  17768. // out and the connection is usable
  17769. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  17770. Start(SERVER_CERT2_FILE);
  17771. ws::WebSocketClient client(url());
  17772. client.set_ca_cert_path(SERVER_CERT2_FILE);
  17773. ASSERT_TRUE(client.connect());
  17774. ASSERT_TRUE(client.send("hello"));
  17775. std::string msg;
  17776. EXPECT_EQ(ws::Text, client.read(msg));
  17777. EXPECT_EQ("hello", msg);
  17778. client.close();
  17779. }
  17780. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  17781. // while the identity check must still reject "localhost"
  17782. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  17783. Start(SERVER_CERT_FILE);
  17784. ws::WebSocketClient client(url());
  17785. client.set_ca_cert_path(SERVER_CERT_FILE);
  17786. auto res = client.connect();
  17787. ASSERT_FALSE(res);
  17788. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  17789. EXPECT_EQ(-1, res.status());
  17790. }
  17791. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  17792. // disabled: the chain is still checked, only the identity check is skipped
  17793. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  17794. Start(SERVER_CERT_FILE);
  17795. ws::WebSocketClient client(url());
  17796. client.set_ca_cert_path(SERVER_CERT_FILE);
  17797. client.enable_server_hostname_verification(false);
  17798. ASSERT_TRUE(client.connect());
  17799. ASSERT_TRUE(client.send("hello"));
  17800. std::string msg;
  17801. EXPECT_EQ(ws::Text, client.read(msg));
  17802. EXPECT_EQ("hello", msg);
  17803. client.close();
  17804. }
  17805. // A CA that did not sign the server certificate fails the chain, even though
  17806. // the name would match
  17807. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  17808. Start(SERVER_CERT2_FILE);
  17809. ws::WebSocketClient client(url());
  17810. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  17811. ASSERT_FALSE(client.connect());
  17812. }
  17813. // With verification disabled, neither the chain nor the name is checked
  17814. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  17815. Start(SERVER_CERT_FILE);
  17816. ws::WebSocketClient client(url());
  17817. client.enable_server_certificate_verification(false);
  17818. ASSERT_TRUE(client.connect());
  17819. ASSERT_TRUE(client.send("hello"));
  17820. std::string msg;
  17821. EXPECT_EQ(ws::Text, client.read(msg));
  17822. EXPECT_EQ("hello", msg);
  17823. client.close();
  17824. }
  17825. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  17826. protected:
  17827. void SetUp() override {
  17828. server_ = httplib::detail::make_unique<SSLServer>(
  17829. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  17830. ASSERT_TRUE(server_->is_valid());
  17831. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  17832. std::string msg;
  17833. while (ws.read(msg)) {
  17834. ws.send(msg);
  17835. }
  17836. });
  17837. port_ = server_->bind_to_any_port("localhost");
  17838. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  17839. server_->wait_until_ready();
  17840. }
  17841. void TearDown() override {
  17842. server_->stop();
  17843. if (server_thread_.joinable()) { server_thread_.join(); }
  17844. }
  17845. std::string url() const {
  17846. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  17847. }
  17848. void ConnectWithClientCert(const std::string &client_cert_file,
  17849. const std::string &client_private_key_file,
  17850. const char *private_key_password) {
  17851. std::string cert_pem, key_pem;
  17852. read_file(client_cert_file, cert_pem);
  17853. read_file(client_private_key_file, key_pem);
  17854. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  17855. key_pem.c_str(), key_pem.size(),
  17856. private_key_password};
  17857. ws::WebSocketClient client(url(), pem);
  17858. ASSERT_TRUE(client.is_valid());
  17859. client.enable_server_certificate_verification(false);
  17860. ASSERT_TRUE(client.connect());
  17861. ASSERT_TRUE(client.send("hello"));
  17862. std::string msg;
  17863. EXPECT_EQ(ws::Text, client.read(msg));
  17864. EXPECT_EQ("hello", msg);
  17865. client.close();
  17866. }
  17867. std::unique_ptr<SSLServer> server_;
  17868. std::thread server_thread_;
  17869. int port_ = 0;
  17870. };
  17871. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  17872. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  17873. }
  17874. // Control for the tests above: the fixture's server really does require a
  17875. // client certificate, so it is the PEM the constructor installed that decides
  17876. // the outcome.
  17877. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  17878. ws::WebSocketClient client(url());
  17879. ASSERT_TRUE(client.is_valid());
  17880. client.enable_server_certificate_verification(false);
  17881. EXPECT_FALSE(client.connect());
  17882. }
  17883. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  17884. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  17885. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  17886. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  17887. }
  17888. #endif
  17889. #if !defined(_WIN32)
  17890. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  17891. auto secret_dir = std::string("./symlink_test_secret");
  17892. auto served_dir = std::string("./symlink_test_served");
  17893. auto secret_file = secret_dir + "/secret.txt";
  17894. auto symlink_path = served_dir + "/escape";
  17895. // Setup: create directories and files
  17896. mkdir(secret_dir.c_str(), 0755);
  17897. mkdir(served_dir.c_str(), 0755);
  17898. {
  17899. std::ofstream ofs(secret_file);
  17900. ofs << "SECRET_DATA";
  17901. }
  17902. // Create symlink using absolute path so it resolves correctly
  17903. #ifdef PATH_MAX
  17904. char abs_secret[PATH_MAX];
  17905. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  17906. #else
  17907. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  17908. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  17909. ASSERT_NE(nullptr, abs_secret);
  17910. #endif
  17911. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  17912. auto se = detail::scope_exit([&] {
  17913. unlink(symlink_path.c_str());
  17914. unlink(secret_file.c_str());
  17915. rmdir(served_dir.c_str());
  17916. rmdir(secret_dir.c_str());
  17917. });
  17918. Server svr;
  17919. svr.set_mount_point("/", served_dir);
  17920. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  17921. auto se2 = detail::scope_exit([&] {
  17922. svr.stop();
  17923. listen_thread.join();
  17924. });
  17925. svr.wait_until_ready();
  17926. Client cli("localhost", PORT);
  17927. // Symlink pointing outside base dir should be blocked
  17928. auto res = cli.Get("/escape/secret.txt");
  17929. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17930. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  17931. }
  17932. #endif
  17933. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  17934. // A GET request with Content-Length to a static file handler must have its
  17935. // body drained before the keep-alive connection is reused. Otherwise the
  17936. // unread body bytes are interpreted as the next HTTP request.
  17937. //
  17938. // The body is sent AFTER receiving the first response (as in the original
  17939. // PoC) so that the stream_line_reader cannot buffer it together with the
  17940. // headers of the first request.
  17941. Server svr;
  17942. svr.set_mount_point("/", "./www");
  17943. std::atomic<int> smuggled_count(0);
  17944. svr.Get("/smuggled", [&](const Request &, Response &res) {
  17945. smuggled_count++;
  17946. res.set_content("oops", "text/plain");
  17947. });
  17948. auto port = svr.bind_to_any_port("localhost");
  17949. thread t = thread([&] { svr.listen_after_bind(); });
  17950. auto se = detail::scope_exit([&] {
  17951. svr.stop();
  17952. t.join();
  17953. });
  17954. svr.wait_until_ready();
  17955. auto error = Error::Success;
  17956. auto sock = detail::create_client_socket(
  17957. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  17958. /*connection_timeout_sec=*/2, 0,
  17959. /*read_timeout_sec=*/2, 0,
  17960. /*write_timeout_sec=*/2, 0, std::string(), error);
  17961. ASSERT_NE(INVALID_SOCKET, sock);
  17962. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  17963. // The "smuggled" request will be sent as the body of the outer GET
  17964. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  17965. "Host: localhost\r\n"
  17966. "Connection: close\r\n"
  17967. "\r\n";
  17968. // Step 1: Send only the outer request headers (no body yet)
  17969. std::string outer_headers = "GET /file HTTP/1.1\r\n"
  17970. "Host: localhost\r\n"
  17971. "Content-Length: " +
  17972. std::to_string(smuggled.size()) +
  17973. "\r\n"
  17974. "\r\n";
  17975. auto sent = send(sock, outer_headers.data(), outer_headers.size(), 0);
  17976. ASSERT_EQ(static_cast<ssize_t>(outer_headers.size()), sent);
  17977. // Step 2: Read the first response (server serves file without reading body)
  17978. std::string first_response;
  17979. char buf[4096];
  17980. for (;;) {
  17981. auto n = recv(sock, buf, sizeof(buf), 0);
  17982. if (n <= 0) break;
  17983. first_response.append(buf, static_cast<size_t>(n));
  17984. // Stop once we have a complete response (headers + body)
  17985. auto hdr_end = first_response.find("\r\n\r\n");
  17986. if (hdr_end != std::string::npos) {
  17987. // Check for Content-Length to know when the body is complete
  17988. auto cl_pos = first_response.find("Content-Length:");
  17989. if (cl_pos != std::string::npos) {
  17990. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  17991. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  17992. auto cl = std::stoul(
  17993. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  17994. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  17995. } else {
  17996. break; // No Content-Length, assume headers-only response
  17997. }
  17998. }
  17999. }
  18000. ASSERT_TRUE(first_response.find("HTTP/1.1 200") != std::string::npos);
  18001. // Step 3: Now send the body, which looks like a new HTTP request.
  18002. // On a vulnerable server the keep-alive loop reads this as a second request.
  18003. sent = send(sock, smuggled.data(), smuggled.size(), 0);
  18004. ASSERT_EQ(static_cast<ssize_t>(smuggled.size()), sent);
  18005. // Step 4: Try to read a second response (should NOT exist after fix)
  18006. std::string second_response;
  18007. for (;;) {
  18008. auto n = recv(sock, buf, sizeof(buf), 0);
  18009. if (n <= 0) break;
  18010. second_response.append(buf, static_cast<size_t>(n));
  18011. }
  18012. // The smuggled request must NOT have been processed
  18013. EXPECT_EQ(0, smuggled_count.load());
  18014. }
  18015. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  18016. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  18017. // must be rejected with 400 Bad Request.
  18018. Server svr;
  18019. svr.Post("/test", [&](const Request &, Response &res) {
  18020. res.set_content("ok", "text/plain");
  18021. });
  18022. thread t = thread([&] { svr.listen(HOST, PORT); });
  18023. auto se = detail::scope_exit([&] {
  18024. svr.stop();
  18025. t.join();
  18026. ASSERT_FALSE(svr.is_running());
  18027. });
  18028. svr.wait_until_ready();
  18029. // Exact "chunked"
  18030. {
  18031. auto req = "POST /test HTTP/1.1\r\n"
  18032. "Host: localhost\r\n"
  18033. "Content-Length: 5\r\n"
  18034. "Transfer-Encoding: chunked\r\n"
  18035. "Connection: close\r\n"
  18036. "\r\n"
  18037. "hello";
  18038. std::string response;
  18039. ASSERT_TRUE(send_request(1, req, &response));
  18040. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  18041. response.substr(0, response.find("\r\n")));
  18042. }
  18043. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  18044. {
  18045. auto req = "POST /test HTTP/1.1\r\n"
  18046. "Host: localhost\r\n"
  18047. "Content-Length: 5\r\n"
  18048. "Transfer-Encoding: gzip, chunked\r\n"
  18049. "Connection: close\r\n"
  18050. "\r\n"
  18051. "hello";
  18052. std::string response;
  18053. ASSERT_TRUE(send_request(1, req, &response));
  18054. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  18055. response.substr(0, response.find("\r\n")));
  18056. }
  18057. }
  18058. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  18059. Server svr;
  18060. svr.Post("/test", [&](const Request &, Response &res) {
  18061. res.set_content("ok", "text/plain");
  18062. });
  18063. thread t = thread([&] { svr.listen(HOST, PORT); });
  18064. auto se = detail::scope_exit([&] {
  18065. svr.stop();
  18066. t.join();
  18067. ASSERT_FALSE(svr.is_running());
  18068. });
  18069. svr.wait_until_ready();
  18070. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  18071. // length cannot be determined, so the server must answer 400 and close
  18072. // rather than treat the request as bodyless and leave the body in the
  18073. // socket for the next request to pick up.
  18074. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  18075. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  18076. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  18077. std::string response;
  18078. ASSERT_TRUE(send_request(1, req, &response));
  18079. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  18080. response.substr(0, response.find("\r\n")))
  18081. << transfer_encoding;
  18082. }
  18083. // RFC 9110 5.3: the codings may also be split across several
  18084. // Transfer-Encoding lines, which combine in the order they were received.
  18085. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  18086. // just like the single-line "chunked, gzip" above.
  18087. {
  18088. auto req = "POST /test HTTP/1.1\r\n"
  18089. "Host: localhost\r\n"
  18090. "Transfer-Encoding: chunked\r\n"
  18091. "Transfer-Encoding: gzip\r\n"
  18092. "\r\n"
  18093. "0\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. }
  18099. // A sequence ending in chunked stays valid.
  18100. auto req = "POST /test HTTP/1.1\r\n"
  18101. "Host: localhost\r\n"
  18102. "Transfer-Encoding: gzip, chunked\r\n"
  18103. "Connection: close\r\n"
  18104. "\r\n"
  18105. "0\r\n\r\n";
  18106. std::string response;
  18107. ASSERT_TRUE(send_request(1, req, &response));
  18108. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  18109. // ...including when it is spread over several lines.
  18110. auto split_req = "POST /test HTTP/1.1\r\n"
  18111. "Host: localhost\r\n"
  18112. "Transfer-Encoding: gzip\r\n"
  18113. "Transfer-Encoding: chunked\r\n"
  18114. "Connection: close\r\n"
  18115. "\r\n"
  18116. "0\r\n\r\n";
  18117. std::string split_response;
  18118. ASSERT_TRUE(send_request(1, split_req, &split_response));
  18119. EXPECT_EQ("HTTP/1.1 200 OK",
  18120. split_response.substr(0, split_response.find("\r\n")));
  18121. }
  18122. // Regression for issue #2450: a DELETE without Content-Length on a
  18123. // keep-alive connection must not let the post-response drain consume the
  18124. // next request's bytes.
  18125. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  18126. Server svr;
  18127. std::atomic<int> delete_count(0);
  18128. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  18129. delete_count++;
  18130. res.status = StatusCode::NoContent_204;
  18131. });
  18132. auto port = svr.bind_to_any_port(HOST);
  18133. thread t = thread([&] { svr.listen_after_bind(); });
  18134. auto se = detail::scope_exit([&] {
  18135. svr.stop();
  18136. t.join();
  18137. });
  18138. svr.wait_until_ready();
  18139. auto error = Error::Success;
  18140. auto sock = detail::create_client_socket(
  18141. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  18142. /*connection_timeout_sec=*/2, 0,
  18143. /*read_timeout_sec=*/2, 0,
  18144. /*write_timeout_sec=*/2, 0, std::string(), error);
  18145. ASSERT_NE(INVALID_SOCKET, sock);
  18146. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  18147. auto send_request_and_read_response = [&](const std::string &req,
  18148. std::string &out) -> bool {
  18149. auto sent = send(sock, req.data(), req.size(), 0);
  18150. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  18151. char buf[4096];
  18152. for (;;) {
  18153. auto n = recv(sock, buf, sizeof(buf), 0);
  18154. if (n <= 0) { return !out.empty(); }
  18155. out.append(buf, static_cast<size_t>(n));
  18156. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  18157. }
  18158. };
  18159. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  18160. "Host: localhost\r\n"
  18161. "\r\n";
  18162. std::string resp1;
  18163. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  18164. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  18165. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  18166. "Host: localhost\r\n"
  18167. "Connection: close\r\n"
  18168. "\r\n";
  18169. std::string resp2;
  18170. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  18171. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  18172. EXPECT_EQ(2, delete_count.load());
  18173. }
  18174. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  18175. Server svr;
  18176. svr.Post("/ingest", [&](const Request &, Response &res,
  18177. const ContentReader &content_reader) {
  18178. auto consumed = content_reader([](const char *, size_t) { return false; });
  18179. EXPECT_FALSE(consumed);
  18180. res.status = StatusCode::Conflict_409;
  18181. res.set_header("Connection", "close");
  18182. });
  18183. auto port = svr.bind_to_any_port(HOST);
  18184. thread t = thread([&] { svr.listen_after_bind(); });
  18185. auto se = detail::scope_exit([&] {
  18186. svr.stop();
  18187. t.join();
  18188. });
  18189. svr.wait_until_ready();
  18190. auto error = Error::Success;
  18191. auto sock = detail::create_client_socket(
  18192. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  18193. /*connection_timeout_sec=*/2, 0,
  18194. /*read_timeout_sec=*/1, 0,
  18195. /*write_timeout_sec=*/2, 0, std::string(), error);
  18196. ASSERT_NE(INVALID_SOCKET, sock);
  18197. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  18198. std::string request = "POST /ingest HTTP/1.1\r\n"
  18199. "Host: localhost\r\n"
  18200. "Transfer-Encoding: chunked\r\n"
  18201. "\r\n"
  18202. "4\r\n"
  18203. "data\r\n";
  18204. auto sent = send(sock, request.data(), request.size(), 0);
  18205. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  18206. std::string response;
  18207. ssize_t received = 0;
  18208. do {
  18209. char buf[4096];
  18210. received = recv(sock, buf, sizeof(buf), 0);
  18211. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  18212. } while (received > 0);
  18213. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  18214. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  18215. EXPECT_EQ(0, received);
  18216. }
  18217. namespace no_proxy_test {
  18218. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  18219. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  18220. // calling listen().
  18221. class ScopedServer {
  18222. public:
  18223. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  18224. ~ScopedServer() {
  18225. svr_.stop();
  18226. if (th_.joinable()) { th_.join(); }
  18227. }
  18228. Server &svr() { return svr_; }
  18229. int port() const { return port_; }
  18230. void listen() {
  18231. th_ = std::thread([this] { svr_.listen_after_bind(); });
  18232. svr_.wait_until_ready();
  18233. }
  18234. private:
  18235. Server svr_;
  18236. std::thread th_;
  18237. int port_ = 0;
  18238. };
  18239. class ProxyAndTargetServers {
  18240. public:
  18241. ProxyAndTargetServers() {
  18242. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  18243. proxy_hits_++;
  18244. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  18245. res.set_content("via-proxy", "text/plain");
  18246. });
  18247. target_.Get(".*", [this](const Request &req, Response &res) {
  18248. target_hits_++;
  18249. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  18250. res.set_content("direct", "text/plain");
  18251. });
  18252. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  18253. target_port_ = target_.bind_to_any_port("127.0.0.1");
  18254. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  18255. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  18256. proxy_mock_.wait_until_ready();
  18257. target_.wait_until_ready();
  18258. }
  18259. ~ProxyAndTargetServers() {
  18260. proxy_mock_.stop();
  18261. target_.stop();
  18262. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  18263. if (target_thread_.joinable()) { target_thread_.join(); }
  18264. }
  18265. Server &proxy_mock() { return proxy_mock_; }
  18266. Server &target() { return target_; }
  18267. int proxy_port() const { return proxy_port_; }
  18268. int target_port() const { return target_port_; }
  18269. int proxy_hits() const { return proxy_hits_.load(); }
  18270. int target_hits() const { return target_hits_.load(); }
  18271. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  18272. void reset_counters() {
  18273. proxy_hits_ = 0;
  18274. target_hits_ = 0;
  18275. last_had_proxy_authz_ = false;
  18276. }
  18277. private:
  18278. Server proxy_mock_;
  18279. Server target_;
  18280. std::thread proxy_thread_;
  18281. std::thread target_thread_;
  18282. int proxy_port_ = 0;
  18283. int target_port_ = 0;
  18284. std::atomic<int> proxy_hits_{0};
  18285. std::atomic<int> target_hits_{0};
  18286. std::atomic<bool> last_had_proxy_authz_{false};
  18287. };
  18288. inline std::unique_ptr<Client> make_client(const std::string &host,
  18289. ProxyAndTargetServers &s) {
  18290. auto cli = detail::make_unique<Client>(host, s.target_port());
  18291. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  18292. cli->set_proxy("127.0.0.1", s.proxy_port());
  18293. return cli;
  18294. }
  18295. } // namespace no_proxy_test
  18296. using no_proxy_test::make_client;
  18297. using no_proxy_test::ProxyAndTargetServers;
  18298. TEST(NoProxyTest, ExactHostnameBypasses) {
  18299. ProxyAndTargetServers s;
  18300. auto cli = make_client("example.com", s);
  18301. cli->set_no_proxy({"example.com"});
  18302. auto res = cli->Get("/");
  18303. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18304. EXPECT_EQ(0, s.proxy_hits());
  18305. EXPECT_EQ(1, s.target_hits());
  18306. }
  18307. TEST(NoProxyTest, SubdomainBypasses) {
  18308. ProxyAndTargetServers s;
  18309. auto cli = make_client("foo.example.com", s);
  18310. cli->set_no_proxy({"example.com"});
  18311. auto res = cli->Get("/");
  18312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18313. EXPECT_EQ(0, s.proxy_hits());
  18314. EXPECT_EQ(1, s.target_hits());
  18315. }
  18316. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  18317. // Regression guard: "evilexample.com" must not be considered a subdomain
  18318. // of "example.com". Without the dot-boundary rule, a naive endsWith
  18319. // check would let traffic bypass the proxy and leak credentials direct
  18320. // to the attacker host.
  18321. ProxyAndTargetServers s;
  18322. auto cli = make_client("evilexample.com", s);
  18323. cli->set_no_proxy({"example.com"});
  18324. auto res = cli->Get("/");
  18325. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18326. EXPECT_GE(s.proxy_hits(), 1);
  18327. EXPECT_EQ(0, s.target_hits());
  18328. }
  18329. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  18330. ProxyAndTargetServers s;
  18331. auto cli = make_client("example.com.evil.com", s);
  18332. cli->set_no_proxy({"example.com"});
  18333. auto res = cli->Get("/");
  18334. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18335. EXPECT_GE(s.proxy_hits(), 1);
  18336. EXPECT_EQ(0, s.target_hits());
  18337. }
  18338. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  18339. ProxyAndTargetServers s;
  18340. auto cli = make_client("example.com", s);
  18341. cli->set_no_proxy({".example.com"});
  18342. auto res = cli->Get("/");
  18343. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18344. EXPECT_EQ(0, s.proxy_hits());
  18345. EXPECT_EQ(1, s.target_hits());
  18346. }
  18347. TEST(NoProxyTest, CaseInsensitiveHostname) {
  18348. ProxyAndTargetServers s;
  18349. auto cli = make_client("Example.COM", s);
  18350. cli->set_no_proxy({"EXAMPLE.com"});
  18351. auto res = cli->Get("/");
  18352. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18353. EXPECT_EQ(0, s.proxy_hits());
  18354. EXPECT_EQ(1, s.target_hits());
  18355. }
  18356. TEST(NoProxyTest, TrailingDotIsNormalized) {
  18357. ProxyAndTargetServers s;
  18358. auto cli = make_client("example.com.", s);
  18359. cli->set_no_proxy({"example.com"});
  18360. auto res = cli->Get("/");
  18361. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18362. EXPECT_EQ(0, s.proxy_hits());
  18363. EXPECT_EQ(1, s.target_hits());
  18364. }
  18365. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  18366. // Trailing dots must be normalized on BOTH sides — host and entry.
  18367. // An implementation that only strips the host-side trailing dot would
  18368. // fail to match host "example.com" against entry "example.com." because
  18369. // a literal substring search would compare 11 chars against 12.
  18370. ProxyAndTargetServers s;
  18371. auto cli = make_client("example.com", s);
  18372. cli->set_no_proxy({"example.com."});
  18373. auto res = cli->Get("/");
  18374. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18375. EXPECT_EQ(0, s.proxy_hits());
  18376. EXPECT_EQ(1, s.target_hits());
  18377. }
  18378. TEST(NoProxyTest, WildcardBypassesEverything) {
  18379. ProxyAndTargetServers s;
  18380. auto cli = make_client("anything.invalid.test", s);
  18381. cli->set_no_proxy({"*"});
  18382. auto res = cli->Get("/");
  18383. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18384. EXPECT_EQ(0, s.proxy_hits());
  18385. EXPECT_EQ(1, s.target_hits());
  18386. }
  18387. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  18388. ProxyAndTargetServers s;
  18389. Client cli("127.0.0.1", s.target_port());
  18390. cli.set_proxy("127.0.0.1", s.proxy_port());
  18391. cli.set_no_proxy({"127.0.0.1"});
  18392. auto res = cli.Get("/");
  18393. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18394. EXPECT_EQ(0, s.proxy_hits());
  18395. EXPECT_EQ(1, s.target_hits());
  18396. }
  18397. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  18398. ProxyAndTargetServers s;
  18399. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  18400. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  18401. cli.set_proxy("127.0.0.1", s.proxy_port());
  18402. cli.set_no_proxy({"::1"});
  18403. auto res = cli.Get("/");
  18404. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18405. EXPECT_EQ(0, s.proxy_hits());
  18406. EXPECT_EQ(1, s.target_hits());
  18407. }
  18408. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  18409. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  18410. // must still be recognized as IPv6 for CIDR matching. Implementations
  18411. // that detect IPv6 only when the host begins with '[' would parse the
  18412. // host as a hostname and miss the match.
  18413. ProxyAndTargetServers s;
  18414. Client cli("fe80::1", s.target_port());
  18415. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  18416. cli.set_proxy("127.0.0.1", s.proxy_port());
  18417. cli.set_no_proxy({"fe80::/10"});
  18418. auto res = cli.Get("/");
  18419. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18420. EXPECT_EQ(0, s.proxy_hits());
  18421. EXPECT_EQ(1, s.target_hits());
  18422. }
  18423. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  18424. ProxyAndTargetServers s;
  18425. Client cli("::1", s.target_port());
  18426. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  18427. cli.set_proxy("127.0.0.1", s.proxy_port());
  18428. cli.set_no_proxy({"[::1]"});
  18429. auto res = cli.Get("/");
  18430. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18431. EXPECT_EQ(0, s.proxy_hits());
  18432. EXPECT_EQ(1, s.target_hits());
  18433. }
  18434. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  18435. ProxyAndTargetServers s;
  18436. Client cli("fe80::1", s.target_port());
  18437. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  18438. cli.set_proxy("127.0.0.1", s.proxy_port());
  18439. cli.set_no_proxy({"[fe80::]/10"});
  18440. auto res = cli.Get("/");
  18441. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18442. EXPECT_EQ(0, s.proxy_hits());
  18443. EXPECT_EQ(1, s.target_hits());
  18444. }
  18445. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  18446. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  18447. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  18448. // tricks via address-family conversion.
  18449. ProxyAndTargetServers s;
  18450. Client cli("::ffff:127.0.0.1", s.target_port());
  18451. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  18452. cli.set_proxy("127.0.0.1", s.proxy_port());
  18453. cli.set_no_proxy({"127.0.0.1"});
  18454. auto res = cli.Get("/");
  18455. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18456. EXPECT_GE(s.proxy_hits(), 1);
  18457. EXPECT_EQ(0, s.target_hits());
  18458. }
  18459. TEST(NoProxyTest, IPv4CidrMatch) {
  18460. ProxyAndTargetServers s;
  18461. Client cli("127.0.0.1", s.target_port());
  18462. cli.set_proxy("127.0.0.1", s.proxy_port());
  18463. cli.set_no_proxy({"127.0.0.0/8"});
  18464. auto res = cli.Get("/");
  18465. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18466. EXPECT_EQ(0, s.proxy_hits());
  18467. EXPECT_EQ(1, s.target_hits());
  18468. }
  18469. TEST(NoProxyTest, IPv4CidrNonMatch) {
  18470. ProxyAndTargetServers s;
  18471. Client cli("127.0.0.1", s.target_port());
  18472. cli.set_proxy("127.0.0.1", s.proxy_port());
  18473. cli.set_no_proxy({"10.0.0.0/8"});
  18474. auto res = cli.Get("/");
  18475. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18476. EXPECT_GE(s.proxy_hits(), 1);
  18477. EXPECT_EQ(0, s.target_hits());
  18478. }
  18479. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  18480. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  18481. // IPv4 target matches.
  18482. ProxyAndTargetServers s;
  18483. Client cli("127.0.0.1", s.target_port());
  18484. cli.set_proxy("127.0.0.1", s.proxy_port());
  18485. cli.set_no_proxy({"0.0.0.0/0"});
  18486. auto res = cli.Get("/");
  18487. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18488. EXPECT_EQ(0, s.proxy_hits());
  18489. EXPECT_EQ(1, s.target_hits());
  18490. }
  18491. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  18492. ProxyAndTargetServers s;
  18493. Client cli("127.0.0.1", s.target_port());
  18494. cli.set_proxy("127.0.0.1", s.proxy_port());
  18495. cli.set_no_proxy({"127.0.0.1"});
  18496. auto res = cli.Get("/");
  18497. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18498. EXPECT_EQ(0, s.proxy_hits());
  18499. EXPECT_EQ(1, s.target_hits());
  18500. }
  18501. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  18502. ProxyAndTargetServers s;
  18503. Client cli("127.0.0.1", s.target_port());
  18504. cli.set_proxy("127.0.0.1", s.proxy_port());
  18505. cli.set_no_proxy({"127.0.0.0/33"});
  18506. auto res = cli.Get("/");
  18507. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18508. EXPECT_GE(s.proxy_hits(), 1);
  18509. EXPECT_EQ(0, s.target_hits());
  18510. }
  18511. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  18512. // Empty prefix after the slash must be rejected, not silently treated as /32.
  18513. ProxyAndTargetServers s;
  18514. Client cli("127.0.0.1", s.target_port());
  18515. cli.set_proxy("127.0.0.1", s.proxy_port());
  18516. cli.set_no_proxy({"127.0.0.1/"});
  18517. auto res = cli.Get("/");
  18518. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18519. EXPECT_GE(s.proxy_hits(), 1);
  18520. EXPECT_EQ(0, s.target_hits());
  18521. }
  18522. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  18523. ProxyAndTargetServers s;
  18524. auto cli = make_client("internal.corp", s);
  18525. cli->set_proxy_basic_auth("u", "p");
  18526. cli->set_no_proxy({"internal.corp"});
  18527. auto res = cli->Get("/");
  18528. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18529. EXPECT_EQ(1, s.target_hits());
  18530. EXPECT_EQ(0, s.proxy_hits());
  18531. EXPECT_FALSE(s.last_had_proxy_authz())
  18532. << "Proxy-Authorization must not be sent direct to the target";
  18533. }
  18534. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  18535. ProxyAndTargetServers s;
  18536. auto cli = make_client("public.example", s);
  18537. cli->set_proxy_basic_auth("u", "p");
  18538. cli->set_no_proxy({"internal.corp"}); // does not match
  18539. auto res = cli->Get("/");
  18540. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18541. EXPECT_GE(s.proxy_hits(), 1);
  18542. EXPECT_TRUE(s.last_had_proxy_authz());
  18543. }
  18544. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  18545. ProxyAndTargetServers s;
  18546. auto cli = make_client("anything.test", s);
  18547. auto res = cli->Get("/");
  18548. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18549. EXPECT_GE(s.proxy_hits(), 1);
  18550. EXPECT_EQ(0, s.target_hits());
  18551. }
  18552. TEST(NoProxyTest, PortSpecificEntryRejected) {
  18553. ProxyAndTargetServers s;
  18554. auto cli = make_client("example.com", s);
  18555. cli->set_no_proxy({"example.com:8080"});
  18556. auto res = cli->Get("/");
  18557. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18558. EXPECT_GE(s.proxy_hits(), 1);
  18559. EXPECT_EQ(0, s.target_hits());
  18560. }
  18561. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  18562. ProxyAndTargetServers s;
  18563. auto cli = make_client("anything.test", s);
  18564. cli->set_no_proxy({"", " ", "\t"});
  18565. auto res = cli->Get("/");
  18566. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18567. EXPECT_GE(s.proxy_hits(), 1);
  18568. EXPECT_EQ(0, s.target_hits());
  18569. }
  18570. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  18571. // An entry with leading/trailing whitespace must still match — env-style
  18572. // values are commonly pasted with stray spaces and an implementation
  18573. // that feeds the raw token directly to inet_pton would fail to match
  18574. // valid CIDRs because of the spaces.
  18575. ProxyAndTargetServers s;
  18576. Client cli("127.0.0.1", s.target_port());
  18577. cli.set_proxy("127.0.0.1", s.proxy_port());
  18578. cli.set_no_proxy({" 127.0.0.0/8 "});
  18579. auto res = cli.Get("/");
  18580. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18581. EXPECT_EQ(0, s.proxy_hits());
  18582. EXPECT_EQ(1, s.target_hits());
  18583. }
  18584. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  18585. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  18586. // go direct and must NOT carry Proxy-Authorization.
  18587. std::atomic<int> proxy_hits{0};
  18588. std::atomic<int> target_hits{0};
  18589. std::atomic<bool> target_saw_authz{false};
  18590. no_proxy_test::ScopedServer proxy_mock, target;
  18591. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  18592. proxy_hits++;
  18593. res.status = 302;
  18594. res.set_header("Location", "http://127.0.0.1:" +
  18595. std::to_string(target.port()) + "/landed");
  18596. });
  18597. target.svr().Get(".*", [&](const Request &req, Response &res) {
  18598. target_hits++;
  18599. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  18600. res.set_content("direct", "text/plain");
  18601. });
  18602. proxy_mock.listen();
  18603. target.listen();
  18604. Client cli("public.example", target.port());
  18605. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  18606. cli.set_proxy("127.0.0.1", proxy_mock.port());
  18607. cli.set_proxy_basic_auth("u", "p");
  18608. cli.set_no_proxy({"127.0.0.1"});
  18609. cli.set_follow_location(true);
  18610. auto res = cli.Get("/redir");
  18611. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18612. EXPECT_GE(proxy_hits.load(), 1);
  18613. EXPECT_GE(target_hits.load(), 1);
  18614. EXPECT_FALSE(target_saw_authz.load());
  18615. }
  18616. #ifdef CPPHTTPLIB_SSL_ENABLED
  18617. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  18618. // Direct origin replying 407 must not trigger the digest retry; otherwise
  18619. // proxy creds would be sent to the (possibly hostile) origin.
  18620. std::atomic<int> target_hits{0};
  18621. std::atomic<bool> target_saw_proxy_authz{false};
  18622. no_proxy_test::ScopedServer target;
  18623. target.svr().Get(".*", [&](const Request &req, Response &res) {
  18624. target_hits++;
  18625. if (req.has_header("Proxy-Authorization")) {
  18626. target_saw_proxy_authz = true;
  18627. }
  18628. res.status = StatusCode::ProxyAuthenticationRequired_407;
  18629. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  18630. "nonce=\"abc\", algorithm=MD5");
  18631. });
  18632. target.listen();
  18633. // The proxy address is set to the target's port: the bypass MUST kick in;
  18634. // if it doesn't, the test still routes "via proxy" to the same server and
  18635. // the Proxy-Authorization assertion below catches the leak.
  18636. Client cli("evil.example", target.port());
  18637. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  18638. cli.set_proxy("127.0.0.1", target.port());
  18639. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  18640. cli.set_no_proxy({"evil.example"});
  18641. auto res = cli.Get("/x");
  18642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18643. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  18644. EXPECT_EQ(1, target_hits.load());
  18645. EXPECT_FALSE(target_saw_proxy_authz.load());
  18646. }
  18647. #endif
  18648. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  18649. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  18650. std::atomic<int> proxy_hits{0};
  18651. std::atomic<int> bypass_hits{0};
  18652. std::atomic<bool> proxy_saw_c_url{false};
  18653. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  18654. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  18655. proxy_hits++;
  18656. if (req.path.find("/start") != std::string::npos) {
  18657. res.status = 302;
  18658. res.set_header("Location", "http://127.0.0.1:" +
  18659. std::to_string(bypass_server.port()) +
  18660. "/middle");
  18661. return;
  18662. }
  18663. if (req.path.find("/end") != std::string::npos) {
  18664. proxy_saw_c_url = true;
  18665. res.set_content("c-via-proxy", "text/plain");
  18666. return;
  18667. }
  18668. res.set_content("unexpected", "text/plain");
  18669. });
  18670. // public.example's "advertised" port is arbitrary (the request never lands
  18671. // there — it goes through the proxy), but use a dynamic value to stay
  18672. // friendly with sharded parallel runs.
  18673. int public_port = bypass_server.port();
  18674. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  18675. bypass_hits++;
  18676. res.status = 302;
  18677. res.set_header("Location", "http://public.example:" +
  18678. std::to_string(public_port) + "/end");
  18679. });
  18680. proxy_mock.listen();
  18681. bypass_server.listen();
  18682. Client cli("public.example", public_port);
  18683. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  18684. cli.set_proxy("127.0.0.1", proxy_mock.port());
  18685. cli.set_no_proxy({"127.0.0.1"});
  18686. cli.set_follow_location(true);
  18687. auto res = cli.Get("/start");
  18688. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18689. EXPECT_EQ(StatusCode::OK_200, res->status);
  18690. EXPECT_EQ("c-via-proxy", res->body);
  18691. EXPECT_GE(proxy_hits.load(), 2);
  18692. EXPECT_GE(bypass_hits.load(), 1);
  18693. EXPECT_TRUE(proxy_saw_c_url.load());
  18694. }
  18695. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  18696. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  18697. // request reconnects to the correct endpoint.
  18698. std::atomic<int> proxy_hits{0};
  18699. std::atomic<int> target_hits{0};
  18700. no_proxy_test::ScopedServer proxy_mock, target;
  18701. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  18702. proxy_hits++;
  18703. res.set_content("via-proxy", "text/plain");
  18704. });
  18705. target.svr().Get(".*", [&](const Request &, Response &res) {
  18706. target_hits++;
  18707. res.set_content("direct", "text/plain");
  18708. });
  18709. proxy_mock.listen();
  18710. target.listen();
  18711. Client cli("public.example", target.port());
  18712. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  18713. cli.set_proxy("127.0.0.1", proxy_mock.port());
  18714. cli.set_keep_alive(true);
  18715. auto res1 = cli.Get("/a");
  18716. ASSERT_TRUE(res1);
  18717. EXPECT_EQ("via-proxy", res1->body);
  18718. EXPECT_EQ(1, proxy_hits.load());
  18719. EXPECT_EQ(0, target_hits.load());
  18720. cli.set_no_proxy({"public.example"});
  18721. auto res2 = cli.Get("/b");
  18722. ASSERT_TRUE(res2);
  18723. EXPECT_EQ("direct", res2->body);
  18724. EXPECT_EQ(1, proxy_hits.load());
  18725. EXPECT_EQ(1, target_hits.load());
  18726. }
  18727. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  18728. namespace proxy_tunnel_test {
  18729. // SSLServer counterpart to no_proxy_test::ScopedServer.
  18730. class ScopedSSLServer {
  18731. public:
  18732. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  18733. port_ = svr_.bind_to_any_port("127.0.0.1");
  18734. }
  18735. ~ScopedSSLServer() {
  18736. svr_.stop();
  18737. if (th_.joinable()) { th_.join(); }
  18738. }
  18739. SSLServer &svr() { return svr_; }
  18740. int port() const { return port_; }
  18741. void listen() {
  18742. th_ = std::thread([this] { svr_.listen_after_bind(); });
  18743. svr_.wait_until_ready();
  18744. }
  18745. private:
  18746. SSLServer svr_;
  18747. std::thread th_;
  18748. int port_ = 0;
  18749. };
  18750. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  18751. class ScopedConnectProxy {
  18752. public:
  18753. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  18754. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  18755. if (listen_fd_ < 0) { return; }
  18756. int yes = 1;
  18757. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  18758. sockaddr_in a{};
  18759. a.sin_family = AF_INET;
  18760. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  18761. a.sin_port = 0;
  18762. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  18763. return;
  18764. }
  18765. socklen_t alen = sizeof(a);
  18766. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  18767. 0) {
  18768. return;
  18769. }
  18770. port_ = ntohs(a.sin_port);
  18771. if (::listen(listen_fd_, 1) != 0) { return; }
  18772. th_ = std::thread([this] { run(); });
  18773. }
  18774. ~ScopedConnectProxy() {
  18775. stop_ = true;
  18776. if (listen_fd_ >= 0) {
  18777. ::shutdown(listen_fd_, SHUT_RDWR);
  18778. ::close(listen_fd_);
  18779. }
  18780. if (th_.joinable()) { th_.join(); }
  18781. }
  18782. int port() const { return port_; }
  18783. int connect_hits() const { return connect_hits_.load(); }
  18784. private:
  18785. void run() {
  18786. while (!stop_.load()) {
  18787. fd_set rfds;
  18788. FD_ZERO(&rfds);
  18789. FD_SET(listen_fd_, &rfds);
  18790. timeval tv{0, 100 * 1000};
  18791. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  18792. if (sel <= 0) { continue; }
  18793. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  18794. if (client_fd < 0) { continue; }
  18795. std::string req;
  18796. char buf[2048];
  18797. while (req.find("\r\n\r\n") == std::string::npos) {
  18798. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  18799. if (n <= 0) { break; }
  18800. req.append(buf, static_cast<size_t>(n));
  18801. }
  18802. if (req.compare(0, 7, "CONNECT") != 0) {
  18803. ::close(client_fd);
  18804. continue;
  18805. }
  18806. connect_hits_++;
  18807. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  18808. ::send(client_fd, ok, std::strlen(ok), 0);
  18809. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  18810. sockaddr_in o{};
  18811. o.sin_family = AF_INET;
  18812. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  18813. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  18814. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  18815. 0) {
  18816. ::close(client_fd);
  18817. ::close(origin_fd);
  18818. continue;
  18819. }
  18820. auto forward = [](int from, int to) {
  18821. char b[8192];
  18822. for (;;) {
  18823. ssize_t n = ::recv(from, b, sizeof(b), 0);
  18824. if (n <= 0) { break; }
  18825. ssize_t off = 0;
  18826. while (off < n) {
  18827. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  18828. if (s <= 0) {
  18829. off = n;
  18830. break;
  18831. }
  18832. off += s;
  18833. }
  18834. }
  18835. ::shutdown(to, SHUT_WR);
  18836. };
  18837. std::thread t1([&] { forward(client_fd, origin_fd); });
  18838. std::thread t2([&] { forward(origin_fd, client_fd); });
  18839. t1.join();
  18840. t2.join();
  18841. ::close(client_fd);
  18842. ::close(origin_fd);
  18843. }
  18844. }
  18845. int forward_port_ = -1;
  18846. int listen_fd_ = -1;
  18847. int port_ = 0;
  18848. std::thread th_;
  18849. std::atomic<bool> stop_{false};
  18850. std::atomic<int> connect_hits_{0};
  18851. };
  18852. } // namespace proxy_tunnel_test
  18853. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  18854. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  18855. // retry; otherwise proxy creds would be sent to the origin.
  18856. std::atomic<int> origin_hits{0};
  18857. std::atomic<bool> origin_saw_proxy_authz{false};
  18858. proxy_tunnel_test::ScopedSSLServer origin;
  18859. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  18860. origin_hits++;
  18861. if (req.has_header("Proxy-Authorization")) {
  18862. origin_saw_proxy_authz = true;
  18863. }
  18864. res.status = StatusCode::ProxyAuthenticationRequired_407;
  18865. res.set_header("Proxy-Authenticate",
  18866. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  18867. "algorithm=MD5");
  18868. });
  18869. origin.listen();
  18870. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  18871. ASSERT_NE(0, proxy.port());
  18872. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  18873. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  18874. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  18875. // and answer with its own status, making this test flaky.
  18876. SSLClient cli("127.0.0.1", origin.port());
  18877. cli.enable_server_certificate_verification(false);
  18878. cli.set_proxy("127.0.0.1", proxy.port());
  18879. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  18880. auto res = cli.Get("/x");
  18881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18882. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  18883. EXPECT_EQ(1, origin_hits.load());
  18884. EXPECT_FALSE(origin_saw_proxy_authz.load());
  18885. EXPECT_EQ(1, proxy.connect_hits());
  18886. }
  18887. #endif