test.cc 645 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813
  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 <chrono>
  17. #include <cstdio>
  18. #include <fstream>
  19. #include <future>
  20. #include <limits>
  21. #include <memory>
  22. #include <sstream>
  23. #include <stdexcept>
  24. #include <thread>
  25. #include <type_traits>
  26. #include <vector>
  27. #if __cplusplus >= 202002L
  28. inline std::string u8_to_string(const char8_t *s) {
  29. return std::string(reinterpret_cast<const char *>(s));
  30. }
  31. #define U8(x) u8_to_string(u8##x)
  32. #else
  33. #define U8(x) u8##x
  34. #endif
  35. #define SERVER_CERT_FILE "./cert.pem"
  36. #define SERVER_CERT2_FILE "./cert2.pem"
  37. #define SERVER_CERT_IP_CN_FILE "./cert_ip_cn.pem"
  38. #define SERVER_CERT_IPV6_FILE "./cert_ipv6.pem"
  39. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  40. #define CA_CERT_FILE "./ca-bundle.crt"
  41. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  42. #define CLIENT_CA_CERT_DIR "."
  43. #define CLIENT_CERT_FILE "./client.cert.pem"
  44. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  45. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  46. // Mbed TLS < 3.6 (e.g. Ubuntu's 2.28) has no PBES2-AES and needs the PBES1-3DES
  47. // key; 3.6+/4.x (4.x dropped DES) and OpenSSL/wolfSSL use the PBES2 AES key.
  48. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) && (MBEDTLS_VERSION_NUMBER < 0x03060000)
  49. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted_pbes1.key.pem"
  50. #else
  51. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  52. #endif
  53. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  54. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  55. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  56. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  57. #ifdef CPPHTTPLIB_SSL_ENABLED
  58. namespace httplib {
  59. namespace tls {
  60. // Declared here for the split build, where the TLS abstraction declarations
  61. // live below the split border; the definition is linked from httplib.cc.
  62. ca_store_t create_ca_store(const char *pem, size_t len);
  63. } // namespace tls
  64. } // namespace httplib
  65. #endif
  66. using namespace std;
  67. using namespace httplib;
  68. const char *HOST = "localhost";
  69. static int get_base_port() {
  70. const char *shard = getenv("GTEST_SHARD_INDEX");
  71. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  72. }
  73. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  74. // New standalone tests MUST use svr.bind_to_any_port() instead.
  75. const int PORT = get_base_port();
  76. const string LONG_QUERY_VALUE = string(25000, '@');
  77. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  78. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  79. const string TOO_LONG_QUERY_URL =
  80. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  81. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  82. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  83. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  84. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  85. return file.name == key;
  86. });
  87. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  88. return *it;
  89. #else
  90. if (it != items.end()) { return *it; }
  91. throw std::runtime_error("invalid multipart form data name error");
  92. #endif
  93. }
  94. static void read_file(const std::string &path, std::string &out) {
  95. std::ifstream fs(path, std::ios_base::binary);
  96. if (!fs) {
  97. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  98. return;
  99. #else
  100. throw std::runtime_error("File not found: " + path);
  101. #endif
  102. }
  103. fs.seekg(0, std::ios_base::end);
  104. auto size = fs.tellg();
  105. fs.seekg(0);
  106. out.resize(static_cast<size_t>(size));
  107. fs.read(&out[0], static_cast<std::streamsize>(size));
  108. }
  109. class UnixSocketTest : public ::testing::Test {
  110. protected:
  111. void TearDown() override { std::remove(pathname_.c_str()); }
  112. void client_GET(const std::string &addr) {
  113. httplib::Client cli{addr};
  114. cli.set_address_family(AF_UNIX);
  115. ASSERT_TRUE(cli.is_valid());
  116. const auto &result = cli.Get(pattern_);
  117. ASSERT_TRUE(result) << "error: " << result.error();
  118. const auto &resp = result.value();
  119. EXPECT_EQ(resp.status, StatusCode::OK_200);
  120. EXPECT_EQ(resp.body, content_);
  121. }
  122. static std::string make_sock_path() {
  123. const char *shard = getenv("GTEST_SHARD_INDEX");
  124. return shard ? std::string("./httplib-server-") + shard + ".sock"
  125. : "./httplib-server.sock";
  126. }
  127. const std::string pathname_{make_sock_path()};
  128. const std::string pattern_{"/hi"};
  129. const std::string content_{"Hello World!"};
  130. };
  131. TEST_F(UnixSocketTest, pathname) {
  132. httplib::Server svr;
  133. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  134. res.set_content(content_, "text/plain");
  135. });
  136. std::thread t{[&] {
  137. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  138. }};
  139. auto se = detail::scope_exit([&] {
  140. svr.stop();
  141. t.join();
  142. ASSERT_FALSE(svr.is_running());
  143. });
  144. svr.wait_until_ready();
  145. ASSERT_TRUE(svr.is_running());
  146. client_GET(pathname_);
  147. }
  148. #if defined(__linux__) || \
  149. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  150. TEST_F(UnixSocketTest, PeerPid) {
  151. httplib::Server svr;
  152. std::string remote_port_val;
  153. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  154. res.set_content(content_, "text/plain");
  155. remote_port_val = std::to_string(req.remote_port);
  156. });
  157. std::thread t{[&] {
  158. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  159. }};
  160. auto se = detail::scope_exit([&] {
  161. svr.stop();
  162. t.join();
  163. ASSERT_FALSE(svr.is_running());
  164. });
  165. svr.wait_until_ready();
  166. ASSERT_TRUE(svr.is_running());
  167. client_GET(pathname_);
  168. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  169. }
  170. #endif
  171. #ifdef __linux__
  172. TEST_F(UnixSocketTest, abstract) {
  173. constexpr char svr_path[]{"\x00httplib-server.sock"};
  174. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  175. httplib::Server svr;
  176. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  177. res.set_content(content_, "text/plain");
  178. });
  179. std::thread t{[&] {
  180. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  181. }};
  182. auto se = detail::scope_exit([&] {
  183. svr.stop();
  184. t.join();
  185. ASSERT_FALSE(svr.is_running());
  186. });
  187. svr.wait_until_ready();
  188. ASSERT_TRUE(svr.is_running());
  189. client_GET(abstract_addr);
  190. }
  191. #endif
  192. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  193. httplib::Server svr;
  194. std::string received_host_header;
  195. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  196. // Capture the Host header sent by the client
  197. auto host_iter = req.headers.find("Host");
  198. if (host_iter != req.headers.end()) {
  199. received_host_header = host_iter->second;
  200. }
  201. res.set_content(content_, "text/plain");
  202. });
  203. std::thread t{[&] {
  204. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  205. }};
  206. auto se = detail::scope_exit([&] {
  207. svr.stop();
  208. t.join();
  209. ASSERT_FALSE(svr.is_running());
  210. });
  211. svr.wait_until_ready();
  212. ASSERT_TRUE(svr.is_running());
  213. // Test that Host header is automatically set to "localhost" for Unix socket
  214. // connections
  215. httplib::Client cli{pathname_};
  216. cli.set_address_family(AF_UNIX);
  217. ASSERT_TRUE(cli.is_valid());
  218. const auto &result = cli.Get(pattern_);
  219. ASSERT_TRUE(result) << "error: " << result.error();
  220. const auto &resp = result.value();
  221. EXPECT_EQ(resp.status, StatusCode::OK_200);
  222. EXPECT_EQ(resp.body, content_);
  223. // Verify that Host header was automatically set to "localhost"
  224. EXPECT_EQ(received_host_header, "localhost");
  225. }
  226. #ifndef _WIN32
  227. TEST(SocketStream, wait_writable_UNIX) {
  228. int fds[2];
  229. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  230. const auto asSocketStream = [&](socket_t fd,
  231. std::function<bool(Stream &)> func) {
  232. return detail::process_client_socket(
  233. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  234. };
  235. asSocketStream(fds[0], [&](Stream &s0) {
  236. EXPECT_EQ(s0.socket(), fds[0]);
  237. EXPECT_TRUE(s0.wait_writable());
  238. EXPECT_TRUE(s0.is_peer_alive());
  239. EXPECT_EQ(0, close(fds[1]));
  240. EXPECT_FALSE(s0.is_peer_alive());
  241. return true;
  242. });
  243. EXPECT_EQ(0, close(fds[0]));
  244. }
  245. TEST(SocketStream, wait_writable_INET) {
  246. sockaddr_in addr;
  247. memset(&addr, 0, sizeof(addr));
  248. addr.sin_family = AF_INET;
  249. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  250. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  251. int disconnected_svr_sock = -1;
  252. std::thread svr{[&] {
  253. const int s = socket(AF_INET, SOCK_STREAM, 0);
  254. ASSERT_LE(0, s);
  255. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  256. ASSERT_EQ(0, listen(s, 1));
  257. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  258. ASSERT_EQ(0, close(s));
  259. }};
  260. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  261. std::thread cli{[&] {
  262. const int s = socket(AF_INET, SOCK_STREAM, 0);
  263. ASSERT_LE(0, s);
  264. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  265. ASSERT_EQ(0, close(s));
  266. }};
  267. cli.join();
  268. svr.join();
  269. ASSERT_NE(disconnected_svr_sock, -1);
  270. const auto asSocketStream = [&](socket_t fd,
  271. std::function<bool(Stream &)> func) {
  272. return detail::process_client_socket(
  273. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  274. };
  275. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  276. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  277. // wait_writable() returns true because select_write() only checks if the
  278. // send buffer has space. Peer disconnection is detected later by send().
  279. EXPECT_TRUE(ss.wait_writable());
  280. return true;
  281. });
  282. ASSERT_EQ(0, close(disconnected_svr_sock));
  283. }
  284. #endif // #ifndef _WIN32
  285. TEST(SetSocketOptTest, TcpNoDelay) {
  286. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  287. ASSERT_NE(sock, INVALID_SOCKET);
  288. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  289. int val = 0;
  290. socklen_t len = sizeof(val);
  291. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  292. reinterpret_cast<char *>(&val), &len));
  293. EXPECT_NE(val, 0);
  294. detail::close_socket(sock);
  295. }
  296. TEST(ClientTest, MoveConstructible) {
  297. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  298. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  299. }
  300. TEST(ClientTest, MoveAssignable) {
  301. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  302. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  303. }
  304. #ifdef _WIN32
  305. TEST(StartupTest, WSAStartup) {
  306. WSADATA wsaData;
  307. int ret = WSAStartup(0x0002, &wsaData);
  308. ASSERT_EQ(0, ret);
  309. }
  310. #endif
  311. TEST(DecodePathTest, PercentCharacter) {
  312. EXPECT_EQ(
  313. decode_path_component(
  314. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  315. U8("descrip=Gastos áéíóúñÑ 6"));
  316. }
  317. TEST(DecodePathTest, PercentCharacterNUL) {
  318. string expected;
  319. expected.push_back('x');
  320. expected.push_back('\0');
  321. expected.push_back('x');
  322. EXPECT_EQ(decode_path_component("x%00x"), expected);
  323. }
  324. TEST(DecodePathTest, UnicodeEncoding) {
  325. // %u0041 = 'A' (1-byte UTF-8)
  326. EXPECT_EQ("A", decode_path_component("%u0041"));
  327. // %u00E9 = 'é' (2-byte UTF-8)
  328. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  329. // %u3042 = 'あ' (3-byte UTF-8)
  330. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  331. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  332. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  333. // %uD800 = surrogate (invalid, silently dropped)
  334. EXPECT_EQ("", decode_path_component("%uD800"));
  335. }
  336. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  337. // A sign or whitespace inside the two-character escape window must not be
  338. // accepted as a valid percent-encoding; the sequence is passed through
  339. // literally, matching decode_uri_component / decode_path_component.
  340. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  341. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  342. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  343. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  344. // Well-formed escapes still decode.
  345. EXPECT_EQ("-", decode_query_component("%2D", false));
  346. EXPECT_EQ("A", decode_query_component("%41", false));
  347. }
  348. TEST(SanitizeFilenameTest, VariousPatterns) {
  349. // Path traversal
  350. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  351. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  352. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  353. // Normal and edge cases
  354. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  355. EXPECT_EQ("filename.txt",
  356. httplib::sanitize_filename("/path/to/filename.txt"));
  357. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  358. EXPECT_EQ("", httplib::sanitize_filename(".."));
  359. EXPECT_EQ("", httplib::sanitize_filename(""));
  360. // Null bytes stripped
  361. EXPECT_EQ("safe.txt",
  362. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  363. // Whitespace-only rejected
  364. EXPECT_EQ("", httplib::sanitize_filename(" "));
  365. }
  366. // Forward declaration (see the base64_encode note below): split builds move the
  367. // definition into httplib.cc, so re-declaring it here lets the test link.
  368. namespace httplib {
  369. namespace detail {
  370. bool is_chunked_transfer_encoding(const Headers &headers);
  371. } // namespace detail
  372. } // namespace httplib
  373. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  374. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  375. auto make = [](std::initializer_list<const char *> lines) {
  376. Headers h;
  377. for (auto te : lines) {
  378. if (te) { h.emplace("Transfer-Encoding", te); }
  379. }
  380. return h;
  381. };
  382. // Sole coding, matched case-insensitively.
  383. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  384. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  385. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  386. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  387. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  388. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  389. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  390. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  391. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  392. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  393. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  394. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  395. // Multiple Transfer-Encoding lines: iteration order for duplicate keys is not
  396. // portable, so any line naming chunked is treated as chunked (fail safe).
  397. // The result must not depend on the order the lines were added.
  398. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  399. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  400. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  401. }
  402. // Forward declaration: in split builds split.py strips `inline` and moves the
  403. // definition into httplib.cc, so detail::base64_encode is not visible from the
  404. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  405. // in both header-only and split builds.
  406. namespace httplib {
  407. namespace detail {
  408. std::string base64_encode(const std::string &in);
  409. } // namespace detail
  410. } // namespace httplib
  411. TEST(Base64EncodeTest, KnownAnswers) {
  412. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  413. // where the accumulator's top bit is already set before the next shift.
  414. EXPECT_EQ("", detail::base64_encode(""));
  415. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  416. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  417. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  418. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  419. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  420. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  421. // High bytes keep the top bit set across several rounds.
  422. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  423. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  424. }
  425. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  426. string unescapedCharacters = "-_.!~*'()";
  427. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  428. }
  429. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  430. string reservedCharacters = ";,/?:@&=+$";
  431. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  432. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  433. }
  434. TEST(ClientQueryOrder, PreserveOrder) {
  435. // This test reproduces Issue #2259: client may reorder query parameters
  436. // when sending a GET request. The expected behavior is that the client
  437. // preserves the original query string order when the caller supplied it
  438. // as part of the path.
  439. Server svr;
  440. svr.Get("/", [&](const Request &req, Response &res) {
  441. // Echo back the raw target so the test can assert ordering
  442. res.set_content(req.target, "text/plain");
  443. });
  444. std::thread t{[&] { svr.listen(HOST, PORT); }};
  445. auto se = detail::scope_exit([&] {
  446. svr.stop();
  447. t.join();
  448. ASSERT_FALSE(svr.is_running());
  449. });
  450. svr.wait_until_ready();
  451. Client cli(HOST, PORT);
  452. ASSERT_TRUE(cli.is_valid());
  453. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  454. auto res = cli.Get(original);
  455. ASSERT_TRUE(res);
  456. // Expect the echoed target to exactly match the original path (order
  457. // preserved)
  458. EXPECT_EQ(res->body, original);
  459. }
  460. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  461. string chineseCharacters = U8("中国語");
  462. string russianCharacters = U8("дом");
  463. string brazilianCharacters = U8("óculos");
  464. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  465. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  466. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  467. "%D0%B4%D0%BE%D0%BC");
  468. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  469. }
  470. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  471. string unescapedCharacters = "-_.!~*'()";
  472. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  473. }
  474. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  475. string reservedCharacters = ";,/?:@&=+$";
  476. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  477. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  478. }
  479. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  480. string chineseCharacters = U8("中国語");
  481. string russianCharacters = U8("дом");
  482. string brazilianCharacters = U8("óculos");
  483. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  484. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  485. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  486. "%D0%B4%D0%BE%D0%BC");
  487. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  488. }
  489. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  490. // Issue #2082 use case: encoding path component with ampersand
  491. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  492. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  493. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  494. }
  495. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  496. string unescapedCharacters = "-_.!~*'()";
  497. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  498. }
  499. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  500. string reservedCharacters = ";,/?:@&=+$#";
  501. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  502. }
  503. TEST(EncodeUriTest, TestUTF8Characters) {
  504. string chineseCharacters = U8("中国語");
  505. string russianCharacters = U8("дом");
  506. string brazilianCharacters = U8("óculos");
  507. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  508. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  509. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  510. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  511. }
  512. TEST(EncodeUriTest, TestCompleteUri) {
  513. string uri =
  514. "https://example.com/path/to/resource?query=value&param=test#fragment";
  515. EXPECT_EQ(
  516. httplib::encode_uri(uri),
  517. "https://example.com/path/to/resource?query=value&param=test#fragment");
  518. }
  519. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  520. string uri =
  521. "https://example.com/path with spaces/file name.html?q=hello world";
  522. EXPECT_EQ(httplib::encode_uri(uri),
  523. "https://example.com/path%20with%20spaces/"
  524. "file%20name.html?q=hello%20world");
  525. }
  526. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  527. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  528. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  529. }
  530. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  531. string unescapedCharacters = "-_.!~*'()";
  532. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  533. }
  534. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  535. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  536. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  537. string encodedBrazilian = "%C3%B3culos";
  538. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  539. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  540. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  541. }
  542. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  543. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  544. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  545. "Piri Tommy Villiers - on & on");
  546. }
  547. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  548. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  549. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  550. }
  551. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  552. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  553. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  554. }
  555. TEST(DecodeUriTest, TestUTF8Characters) {
  556. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  557. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  558. string encodedBrazilian = "%C3%B3culos";
  559. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  560. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  561. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  562. }
  563. TEST(DecodeUriTest, TestCompleteUri) {
  564. string encodedUri = "https://example.com/path%20with%20spaces/"
  565. "file%20name.html?q=hello%20world";
  566. EXPECT_EQ(
  567. httplib::decode_uri(encodedUri),
  568. "https://example.com/path with spaces/file name.html?q=hello world");
  569. }
  570. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  571. string original =
  572. "https://example.com/path with spaces/file name.html?q=hello world";
  573. string encoded = httplib::encode_uri(original);
  574. string decoded = httplib::decode_uri(encoded);
  575. EXPECT_EQ(decoded, original);
  576. }
  577. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  578. string original = "Piri Tommy Villiers - on & on";
  579. string encoded = httplib::encode_uri_component(original);
  580. string decoded = httplib::decode_uri_component(encoded);
  581. EXPECT_EQ(decoded, original);
  582. }
  583. TEST(TrimTests, TrimStringTests) {
  584. EXPECT_EQ("abc", detail::trim_copy("abc"));
  585. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  586. EXPECT_TRUE(detail::trim_copy("").empty());
  587. }
  588. TEST(AsciiTest, LocaleIndependentClassification) {
  589. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  590. // which consult the global C locale: std::isalnum(0xC5) can return true
  591. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  592. // helpers must classify every byte by the ASCII grammar alone.
  593. for (int i = 0; i < 256; i++) {
  594. auto c = static_cast<char>(i);
  595. auto is_digit = i >= '0' && i <= '9';
  596. auto is_upper = i >= 'A' && i <= 'Z';
  597. auto is_lower = i >= 'a' && i <= 'z';
  598. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  599. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  600. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  601. << "byte " << i;
  602. }
  603. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  604. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  605. // Non-ASCII bytes must be percent-encoded, never passed through as
  606. // alphanumeric.
  607. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  608. }
  609. TEST(FromCharsTest, Double) {
  610. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  611. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  612. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  613. auto parse = [](const std::string &s, double &v) {
  614. return detail::from_chars(s.data(), s.data() + s.size(), v);
  615. };
  616. double v = -1.0;
  617. // Representative quality values.
  618. EXPECT_EQ(parse("0", v).ec, std::errc{});
  619. EXPECT_DOUBLE_EQ(v, 0.0);
  620. EXPECT_EQ(parse("1", v).ec, std::errc{});
  621. EXPECT_DOUBLE_EQ(v, 1.0);
  622. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  623. EXPECT_DOUBLE_EQ(v, 0.8);
  624. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  625. EXPECT_DOUBLE_EQ(v, 0.001);
  626. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  627. EXPECT_DOUBLE_EQ(v, 1.0);
  628. // A missing integer or fractional part is tolerated.
  629. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  630. EXPECT_DOUBLE_EQ(v, 0.5);
  631. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  632. EXPECT_DOUBLE_EQ(v, 5.0);
  633. // Values outside [0, 1] still parse; the caller range-checks them.
  634. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  635. EXPECT_DOUBLE_EQ(v, 123.456);
  636. // Stops at the first byte that is not part of the number and reports where.
  637. std::string trailing = "0.9, text/html";
  638. auto r = parse(trailing, v);
  639. EXPECT_EQ(r.ec, std::errc{});
  640. EXPECT_DOUBLE_EQ(v, 0.9);
  641. EXPECT_EQ(*r.ptr, ',');
  642. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  643. // outright, and an 'e'/'E' simply ends the number.
  644. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  645. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  646. std::string exp_input = "1.5e3";
  647. r = parse(exp_input, v);
  648. EXPECT_EQ(r.ec, std::errc{});
  649. EXPECT_DOUBLE_EQ(v, 1.5);
  650. EXPECT_EQ(*r.ptr, 'e');
  651. // Invalid inputs.
  652. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  653. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  654. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  655. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  656. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  657. // Pathological but well-formed inputs must stay bounded (no overflow, no
  658. // out-of-bounds table access) and stay within [0, 1] for the caller.
  659. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  660. std::errc{});
  661. EXPECT_DOUBLE_EQ(v, 0.0);
  662. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  663. std::errc{});
  664. EXPECT_GE(v, 0.0);
  665. EXPECT_LE(v, 1.0);
  666. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  667. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  668. }
  669. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  670. // Simple case without quality values
  671. std::vector<std::string> result1;
  672. EXPECT_TRUE(detail::parse_accept_header(
  673. "text/html,application/json,text/plain", result1));
  674. EXPECT_EQ(result1.size(), 3U);
  675. EXPECT_EQ(result1[0], "text/html");
  676. EXPECT_EQ(result1[1], "application/json");
  677. EXPECT_EQ(result1[2], "text/plain");
  678. // With quality values
  679. std::vector<std::string> result2;
  680. EXPECT_TRUE(detail::parse_accept_header(
  681. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  682. EXPECT_EQ(result2.size(), 3U);
  683. EXPECT_EQ(result2[0], "application/json"); // highest q value
  684. EXPECT_EQ(result2[1], "text/html");
  685. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  686. }
  687. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  688. // Mixed with and without quality values
  689. std::vector<std::string> result;
  690. EXPECT_TRUE(detail::parse_accept_header(
  691. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  692. EXPECT_EQ(result.size(), 3U);
  693. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  694. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  695. EXPECT_EQ(result[2], "application/json"); // q=0.5
  696. }
  697. TEST(ParseAcceptHeaderTest, EdgeCases) {
  698. // Empty header
  699. std::vector<std::string> empty_result;
  700. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  701. EXPECT_TRUE(empty_result.empty());
  702. // Single type
  703. std::vector<std::string> single_result;
  704. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  705. EXPECT_EQ(single_result.size(), 1U);
  706. EXPECT_EQ(single_result[0], "application/json");
  707. // Wildcard types
  708. std::vector<std::string> wildcard_result;
  709. EXPECT_TRUE(detail::parse_accept_header(
  710. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  711. EXPECT_EQ(wildcard_result.size(), 3U);
  712. EXPECT_EQ(wildcard_result[0], "application/json");
  713. EXPECT_EQ(wildcard_result[1], "text/*");
  714. EXPECT_EQ(wildcard_result[2], "*/*");
  715. }
  716. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  717. // Common browser Accept header
  718. std::vector<std::string> browser_result;
  719. EXPECT_TRUE(
  720. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  721. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  722. browser_result));
  723. EXPECT_EQ(browser_result.size(), 6U);
  724. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  725. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  726. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  727. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  728. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  729. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  730. // API client header
  731. std::vector<std::string> api_result;
  732. EXPECT_TRUE(detail::parse_accept_header(
  733. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  734. api_result));
  735. EXPECT_EQ(api_result.size(), 3U);
  736. EXPECT_EQ(api_result[0], "application/json");
  737. EXPECT_EQ(api_result[1], "application/xml");
  738. EXPECT_EQ(api_result[2], "text/plain");
  739. }
  740. TEST(ParseAcceptHeaderTest, SpecialCases) {
  741. // Quality value with 3 decimal places
  742. std::vector<std::string> decimal_result;
  743. EXPECT_TRUE(detail::parse_accept_header(
  744. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  745. EXPECT_EQ(decimal_result.size(), 2U);
  746. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  747. EXPECT_EQ(decimal_result[1], "text/html");
  748. // Zero quality (should still be included but with lowest priority)
  749. std::vector<std::string> zero_q_result;
  750. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  751. zero_q_result));
  752. EXPECT_EQ(zero_q_result.size(), 2U);
  753. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  754. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  755. // No spaces around commas
  756. std::vector<std::string> no_space_result;
  757. EXPECT_TRUE(detail::parse_accept_header(
  758. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  759. no_space_result));
  760. EXPECT_EQ(no_space_result.size(), 3U);
  761. EXPECT_EQ(no_space_result[0], "text/html");
  762. EXPECT_EQ(no_space_result[1], "application/json");
  763. EXPECT_EQ(no_space_result[2], "text/plain");
  764. }
  765. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  766. // Quality values always use '.' as the decimal separator, so parsing must
  767. // not depend on the process locale. An embedding application may have
  768. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  769. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  770. std::string saved = cur ? cur : "C";
  771. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  772. "fr_FR.UTF-8"};
  773. bool switched = false;
  774. for (const auto loc : comma_locales) {
  775. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  776. std::localeconv()->decimal_point[0] == ',') {
  777. switched = true;
  778. break;
  779. }
  780. }
  781. if (!switched) {
  782. std::setlocale(LC_NUMERIC, saved.c_str());
  783. GTEST_SKIP() << "no comma-decimal locale available on this host";
  784. }
  785. // The higher-weighted type appears later in the list, so a correct parse
  786. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  787. // sensitive parse reads both weights as 0 and leaves the original order.
  788. std::vector<std::string> result;
  789. EXPECT_TRUE(detail::parse_accept_header(
  790. "application/json;q=0.1,text/html;q=0.9", result));
  791. ASSERT_EQ(result.size(), 2U);
  792. EXPECT_EQ(result[0], "text/html");
  793. EXPECT_EQ(result[1], "application/json");
  794. std::setlocale(LC_NUMERIC, saved.c_str());
  795. }
  796. TEST(ParseAcceptHeaderTest, InvalidCases) {
  797. std::vector<std::string> result;
  798. // Invalid quality value (> 1.0)
  799. EXPECT_FALSE(
  800. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  801. // Invalid quality value (< 0.0)
  802. EXPECT_FALSE(
  803. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  804. // Invalid quality value (not a number)
  805. EXPECT_FALSE(detail::parse_accept_header(
  806. "text/html;q=invalid,application/json", result));
  807. // Empty quality value
  808. EXPECT_FALSE(
  809. detail::parse_accept_header("text/html;q=,application/json", result));
  810. // Invalid media type format (no slash and not wildcard)
  811. EXPECT_FALSE(
  812. detail::parse_accept_header("invalidtype,application/json", result));
  813. // Empty media type
  814. result.clear();
  815. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  816. // Only commas
  817. result.clear();
  818. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  819. // Valid cases should still work
  820. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  821. EXPECT_EQ(result.size(), 1U);
  822. EXPECT_EQ(result[0], "*/*");
  823. EXPECT_TRUE(detail::parse_accept_header("*", result));
  824. EXPECT_EQ(result.size(), 1U);
  825. EXPECT_EQ(result[0], "*");
  826. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  827. EXPECT_EQ(result.size(), 1U);
  828. EXPECT_EQ(result[0], "text/*");
  829. }
  830. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  831. Server svr;
  832. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  833. EXPECT_EQ(req.accept_content_types.size(), 3U);
  834. EXPECT_EQ(req.accept_content_types[0], "application/json");
  835. EXPECT_EQ(req.accept_content_types[1], "text/html");
  836. EXPECT_EQ(req.accept_content_types[2], "*/*");
  837. res.set_content("ok", "text/plain");
  838. });
  839. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  840. EXPECT_TRUE(false);
  841. res.set_content("bad request", "text/plain");
  842. });
  843. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  844. auto se = detail::scope_exit([&] {
  845. svr.stop();
  846. listen_thread.join();
  847. ASSERT_FALSE(svr.is_running());
  848. });
  849. svr.wait_until_ready();
  850. Client cli("localhost", PORT);
  851. {
  852. auto res = cli.Get(
  853. "/accept_ok",
  854. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  855. ASSERT_TRUE(res);
  856. EXPECT_EQ(StatusCode::OK_200, res->status);
  857. }
  858. {
  859. auto res = cli.Get("/accept_bad_request",
  860. Headers{{"Accept", "text/html;q=abc,application/json"}});
  861. ASSERT_TRUE(res);
  862. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  863. }
  864. }
  865. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  866. Server svr;
  867. svr.Get("/", [](const Request & /*req*/, Response &res) {
  868. res.set_content("ok", "text/plain");
  869. });
  870. std::atomic<int> start_count{0};
  871. std::atomic<bool> running_when_called{false};
  872. svr.set_start_handler([&]() {
  873. running_when_called = svr.is_running();
  874. start_count++;
  875. });
  876. auto port = svr.bind_to_any_port(HOST);
  877. std::thread t([&]() { svr.listen_after_bind(); });
  878. auto se = detail::scope_exit([&] {
  879. svr.stop();
  880. t.join();
  881. ASSERT_FALSE(svr.is_running());
  882. });
  883. svr.wait_until_ready();
  884. // A successful request proves the accept loop is running, which the start
  885. // handler precedes; so by now the handler must have run exactly once.
  886. Client cli(HOST, port);
  887. cli.set_connection_timeout(std::chrono::seconds(5));
  888. auto res = cli.Get("/");
  889. ASSERT_TRUE(res);
  890. EXPECT_EQ(StatusCode::OK_200, res->status);
  891. EXPECT_EQ(1, start_count.load());
  892. EXPECT_TRUE(running_when_called.load());
  893. }
  894. TEST(DivideTest, DivideStringTests) {
  895. auto divide = [](const std::string &str, char d) {
  896. std::string lhs;
  897. std::string rhs;
  898. detail::divide(str, d,
  899. [&](const char *lhs_data, std::size_t lhs_size,
  900. const char *rhs_data, std::size_t rhs_size) {
  901. lhs.assign(lhs_data, lhs_size);
  902. rhs.assign(rhs_data, rhs_size);
  903. });
  904. return std::make_pair(std::move(lhs), std::move(rhs));
  905. };
  906. {
  907. const auto res = divide("", '=');
  908. EXPECT_EQ(res.first, "");
  909. EXPECT_EQ(res.second, "");
  910. }
  911. {
  912. const auto res = divide("=", '=');
  913. EXPECT_EQ(res.first, "");
  914. EXPECT_EQ(res.second, "");
  915. }
  916. {
  917. const auto res = divide(" ", '=');
  918. EXPECT_EQ(res.first, " ");
  919. EXPECT_EQ(res.second, "");
  920. }
  921. {
  922. const auto res = divide("a", '=');
  923. EXPECT_EQ(res.first, "a");
  924. EXPECT_EQ(res.second, "");
  925. }
  926. {
  927. const auto res = divide("a=", '=');
  928. EXPECT_EQ(res.first, "a");
  929. EXPECT_EQ(res.second, "");
  930. }
  931. {
  932. const auto res = divide("=b", '=');
  933. EXPECT_EQ(res.first, "");
  934. EXPECT_EQ(res.second, "b");
  935. }
  936. {
  937. const auto res = divide("a=b", '=');
  938. EXPECT_EQ(res.first, "a");
  939. EXPECT_EQ(res.second, "b");
  940. }
  941. {
  942. const auto res = divide("a=b=", '=');
  943. EXPECT_EQ(res.first, "a");
  944. EXPECT_EQ(res.second, "b=");
  945. }
  946. {
  947. const auto res = divide("a=b=c", '=');
  948. EXPECT_EQ(res.first, "a");
  949. EXPECT_EQ(res.second, "b=c");
  950. }
  951. }
  952. TEST(SplitTest, ParseQueryString) {
  953. string s = "key1=val1&key2=val2&key3=val3";
  954. Params dic;
  955. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  956. [&](const char *b, const char *e) {
  957. string key, val;
  958. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  959. if (key.empty()) {
  960. key.assign(b2, e2);
  961. } else {
  962. val.assign(b2, e2);
  963. }
  964. });
  965. dic.emplace(key, val);
  966. });
  967. EXPECT_EQ("val1", dic.find("key1")->second);
  968. EXPECT_EQ("val2", dic.find("key2")->second);
  969. EXPECT_EQ("val3", dic.find("key3")->second);
  970. }
  971. TEST(SplitTest, ParseInvalidQueryTests) {
  972. {
  973. string s = " ";
  974. Params dict;
  975. detail::parse_query_text(s, dict);
  976. EXPECT_TRUE(dict.empty());
  977. }
  978. {
  979. string s = " = =";
  980. Params dict;
  981. detail::parse_query_text(s, dict);
  982. EXPECT_TRUE(dict.empty());
  983. }
  984. }
  985. TEST(ParseQueryTest, ParseQueryString) {
  986. {
  987. std::string s = "key1=val1&key2=val2&key3=val3";
  988. Params dic;
  989. detail::parse_query_text(s, dic);
  990. EXPECT_EQ("val1", dic.find("key1")->second);
  991. EXPECT_EQ("val2", dic.find("key2")->second);
  992. EXPECT_EQ("val3", dic.find("key3")->second);
  993. }
  994. {
  995. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  996. Params dic;
  997. detail::parse_query_text(s, dic);
  998. EXPECT_EQ("", dic.find("key1")->second);
  999. EXPECT_EQ("val1", dic.find("key2")->second);
  1000. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1001. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1002. }
  1003. }
  1004. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1005. Params dic;
  1006. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1007. dic.emplace("key1", "val1");
  1008. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1009. dic.emplace("key2", "val2");
  1010. dic.emplace("key3", "val3");
  1011. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1012. }
  1013. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1014. string content_type = "multipart/form-data; boundary=something";
  1015. string boundary;
  1016. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1017. EXPECT_TRUE(ret);
  1018. EXPECT_EQ(boundary, "something");
  1019. }
  1020. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1021. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1022. string boundary;
  1023. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1024. EXPECT_TRUE(ret);
  1025. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1026. }
  1027. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1028. string content_type =
  1029. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1030. string boundary;
  1031. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1032. EXPECT_TRUE(ret);
  1033. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1034. }
  1035. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1036. string content_type =
  1037. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1038. string boundary;
  1039. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1040. EXPECT_TRUE(ret);
  1041. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1042. }
  1043. TEST(GetHeaderValueTest, DefaultValue) {
  1044. Headers headers = {{"Dummy", "Dummy"}};
  1045. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1046. EXPECT_STREQ("text/plain", val);
  1047. }
  1048. TEST(GetHeaderValueTest, DefaultValueInt) {
  1049. Headers headers = {{"Dummy", "Dummy"}};
  1050. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1051. EXPECT_EQ(100ull, val);
  1052. }
  1053. TEST(GetHeaderValueTest, RegularValue) {
  1054. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1055. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1056. EXPECT_STREQ("text/html", val);
  1057. }
  1058. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1059. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1060. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1061. EXPECT_STREQ("text/html", val);
  1062. }
  1063. TEST(GetHeaderValueTest, SetContent) {
  1064. Response res;
  1065. res.set_content("html", "text/html");
  1066. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1067. res.set_content("text", "text/plain");
  1068. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1069. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1070. }
  1071. TEST(GetHeaderValueTest, RegularValueInt) {
  1072. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1073. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1074. EXPECT_EQ(100ull, val);
  1075. }
  1076. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1077. Headers headers = {{"Content-Length", "x"}};
  1078. auto is_invalid_value = false;
  1079. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1080. is_invalid_value);
  1081. EXPECT_EQ(0ull, val);
  1082. EXPECT_TRUE(is_invalid_value);
  1083. }
  1084. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1085. // An all-digit value that overflows size_t must be reported as invalid, not
  1086. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1087. // a large length to a small one on 32-bit builds, leaving the framing length
  1088. // wrong while is_invalid_value stayed false.
  1089. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1090. auto is_invalid_value = false;
  1091. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1092. is_invalid_value);
  1093. EXPECT_TRUE(is_invalid_value);
  1094. // A well-formed length is unaffected.
  1095. Headers ok = {{"Content-Length", "1234"}};
  1096. is_invalid_value = false;
  1097. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1098. is_invalid_value);
  1099. EXPECT_EQ(1234ull, val);
  1100. EXPECT_FALSE(is_invalid_value);
  1101. }
  1102. TEST(GetHeaderValueTest, Range) {
  1103. {
  1104. Headers headers = {make_range_header({{1, -1}})};
  1105. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1106. EXPECT_STREQ("bytes=1-", val);
  1107. }
  1108. {
  1109. Headers headers = {make_range_header({{-1, 1}})};
  1110. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1111. EXPECT_STREQ("bytes=-1", val);
  1112. }
  1113. {
  1114. Headers headers = {make_range_header({{1, 10}})};
  1115. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1116. EXPECT_STREQ("bytes=1-10", val);
  1117. }
  1118. {
  1119. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1120. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1121. EXPECT_STREQ("bytes=1-10, 100-", val);
  1122. }
  1123. {
  1124. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1125. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1126. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1127. }
  1128. {
  1129. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1130. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1131. EXPECT_STREQ("bytes=0-0, -1", val);
  1132. }
  1133. }
  1134. TEST(ParseHeaderValueTest, Range) {
  1135. {
  1136. Ranges ranges;
  1137. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1138. EXPECT_TRUE(ret);
  1139. EXPECT_EQ(1u, ranges.size());
  1140. EXPECT_EQ(1u, ranges[0].first);
  1141. EXPECT_EQ(-1, ranges[0].second);
  1142. }
  1143. {
  1144. Ranges ranges;
  1145. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1146. EXPECT_TRUE(ret);
  1147. EXPECT_EQ(1u, ranges.size());
  1148. EXPECT_EQ(-1, ranges[0].first);
  1149. EXPECT_EQ(1u, ranges[0].second);
  1150. }
  1151. {
  1152. Ranges ranges;
  1153. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1154. EXPECT_TRUE(ret);
  1155. EXPECT_EQ(1u, ranges.size());
  1156. EXPECT_EQ(1u, ranges[0].first);
  1157. EXPECT_EQ(10u, ranges[0].second);
  1158. }
  1159. {
  1160. Ranges ranges;
  1161. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1162. EXPECT_FALSE(ret);
  1163. }
  1164. {
  1165. Ranges ranges;
  1166. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1167. EXPECT_TRUE(ret);
  1168. EXPECT_EQ(2u, ranges.size());
  1169. EXPECT_EQ(1u, ranges[0].first);
  1170. EXPECT_EQ(10u, ranges[0].second);
  1171. EXPECT_EQ(100u, ranges[1].first);
  1172. EXPECT_EQ(-1, ranges[1].second);
  1173. }
  1174. {
  1175. Ranges ranges;
  1176. auto ret =
  1177. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1178. EXPECT_TRUE(ret);
  1179. EXPECT_EQ(3u, ranges.size());
  1180. EXPECT_EQ(1u, ranges[0].first);
  1181. EXPECT_EQ(10u, ranges[0].second);
  1182. EXPECT_EQ(100u, ranges[1].first);
  1183. EXPECT_EQ(200u, ranges[1].second);
  1184. EXPECT_EQ(300u, ranges[2].first);
  1185. EXPECT_EQ(400u, ranges[2].second);
  1186. }
  1187. {
  1188. Ranges ranges;
  1189. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1190. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1191. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1192. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1193. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1194. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1195. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1196. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1197. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1198. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1199. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1200. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1201. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1202. EXPECT_TRUE(ranges.empty());
  1203. }
  1204. }
  1205. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  1206. Request req;
  1207. req.set_header("Accept-Encoding", "gzip");
  1208. Response res;
  1209. res.set_header("Content-Type", "text/plain");
  1210. auto ret = detail::encoding_type(req, res);
  1211. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1212. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1213. #else
  1214. EXPECT_TRUE(ret == detail::EncodingType::None);
  1215. #endif
  1216. }
  1217. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1218. Request req;
  1219. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  1220. Response res;
  1221. res.set_header("Content-Type", "text/plain");
  1222. auto ret = detail::encoding_type(req, res);
  1223. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1224. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1225. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1226. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1227. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1228. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1229. #else
  1230. EXPECT_TRUE(ret == detail::EncodingType::None);
  1231. #endif
  1232. }
  1233. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  1234. Request req;
  1235. req.set_header("Accept-Encoding",
  1236. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  1237. Response res;
  1238. res.set_header("Content-Type", "text/plain");
  1239. auto ret = detail::encoding_type(req, res);
  1240. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1241. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1242. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1243. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1244. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1245. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1246. #else
  1247. EXPECT_TRUE(ret == detail::EncodingType::None);
  1248. #endif
  1249. }
  1250. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  1251. // All supported encodings rejected with q=0 should return None
  1252. Request req;
  1253. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  1254. Response res;
  1255. res.set_header("Content-Type", "text/plain");
  1256. auto ret = detail::encoding_type(req, res);
  1257. EXPECT_TRUE(ret == detail::EncodingType::None);
  1258. }
  1259. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1260. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1261. Request req;
  1262. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1263. Response res;
  1264. res.set_header("Content-Type", "text/plain");
  1265. auto ret = detail::encoding_type(req, res);
  1266. EXPECT_TRUE(ret == detail::EncodingType::None);
  1267. }
  1268. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1269. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1270. Request req;
  1271. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1272. Response res;
  1273. res.set_header("Content-Type", "text/plain");
  1274. auto ret = detail::encoding_type(req, res);
  1275. EXPECT_TRUE(ret == detail::EncodingType::None);
  1276. }
  1277. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1278. // RFC 7231: Accept-Encoding values are case-insensitive
  1279. Request req;
  1280. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1281. Response res;
  1282. res.set_header("Content-Type", "text/plain");
  1283. auto ret = detail::encoding_type(req, res);
  1284. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1285. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1286. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1287. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1288. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1289. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1290. #else
  1291. EXPECT_TRUE(ret == detail::EncodingType::None);
  1292. #endif
  1293. }
  1294. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1295. // q value should determine priority, not hardcoded order
  1296. Request req;
  1297. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  1298. Response res;
  1299. res.set_header("Content-Type", "text/plain");
  1300. auto ret = detail::encoding_type(req, res);
  1301. // gzip has highest q=1.0, so it should be selected even though
  1302. // br and zstd are also supported
  1303. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1304. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1305. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1306. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1307. #elif CPPHTTPLIB_BROTLI_SUPPORT
  1308. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1309. #else
  1310. EXPECT_TRUE(ret == detail::EncodingType::None);
  1311. #endif
  1312. }
  1313. TEST(BufferStreamTest, read) {
  1314. detail::BufferStream strm1;
  1315. Stream &strm = strm1;
  1316. EXPECT_EQ(5, strm.write("hello"));
  1317. char buf[512];
  1318. EXPECT_EQ(2, strm.read(buf, 2));
  1319. EXPECT_EQ('h', buf[0]);
  1320. EXPECT_EQ('e', buf[1]);
  1321. EXPECT_EQ(2, strm.read(buf, 2));
  1322. EXPECT_EQ('l', buf[0]);
  1323. EXPECT_EQ('l', buf[1]);
  1324. EXPECT_EQ(1, strm.read(buf, 1));
  1325. EXPECT_EQ('o', buf[0]);
  1326. EXPECT_EQ(0, strm.read(buf, 1));
  1327. }
  1328. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1329. auto host = "www.httpwatch.com";
  1330. auto ip = hosted_at(host);
  1331. EXPECT_EQ("23.96.13.243", ip);
  1332. std::vector<std::string> addrs;
  1333. hosted_at(host, addrs);
  1334. EXPECT_EQ(1u, addrs.size());
  1335. }
  1336. #if 0 // It depends on each test environment...
  1337. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1338. auto host = "www.youtube.com";
  1339. std::vector<std::string> addrs;
  1340. hosted_at(host, addrs);
  1341. EXPECT_EQ(20u, addrs.size());
  1342. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1343. EXPECT_TRUE(it != addrs.end());
  1344. }
  1345. #endif
  1346. class ChunkedEncodingTest : public ::testing::Test {
  1347. protected:
  1348. ChunkedEncodingTest()
  1349. : cli_(HOST, PORT)
  1350. #ifdef CPPHTTPLIB_SSL_ENABLED
  1351. ,
  1352. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1353. #endif
  1354. {
  1355. cli_.set_connection_timeout(2);
  1356. #ifdef CPPHTTPLIB_SSL_ENABLED
  1357. cli_.enable_server_certificate_verification(false);
  1358. #endif
  1359. }
  1360. virtual void SetUp() {
  1361. read_file("./image.jpg", image_data_);
  1362. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1363. res.set_content("Hello World!", "text/plain");
  1364. });
  1365. svr_.Get(
  1366. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1367. res.set_chunked_content_provider(
  1368. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1369. size_t remaining = image_data_.size() - offset;
  1370. if (remaining == 0) {
  1371. sink.done();
  1372. } else {
  1373. constexpr size_t CHUNK_SIZE = 1024;
  1374. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1375. sink.write(&image_data_[offset], send_size);
  1376. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1377. }
  1378. return true;
  1379. });
  1380. });
  1381. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1382. svr_.wait_until_ready();
  1383. }
  1384. virtual void TearDown() {
  1385. svr_.stop();
  1386. if (!request_threads_.empty()) {
  1387. std::this_thread::sleep_for(std::chrono::seconds(1));
  1388. for (auto &t : request_threads_) {
  1389. t.join();
  1390. }
  1391. }
  1392. t_.join();
  1393. }
  1394. #ifdef CPPHTTPLIB_SSL_ENABLED
  1395. SSLClient cli_;
  1396. SSLServer svr_;
  1397. #else
  1398. Client cli_;
  1399. Server svr_;
  1400. #endif
  1401. thread t_;
  1402. std::vector<thread> request_threads_;
  1403. std::string image_data_;
  1404. };
  1405. TEST_F(ChunkedEncodingTest, NormalGet) {
  1406. auto res = cli_.Get("/chunked");
  1407. ASSERT_TRUE(res);
  1408. std::string out;
  1409. read_file("./image.jpg", out);
  1410. EXPECT_EQ(StatusCode::OK_200, res->status);
  1411. EXPECT_EQ(out, res->body);
  1412. }
  1413. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1414. std::string body;
  1415. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1416. body.append(data, data_length);
  1417. return true;
  1418. });
  1419. ASSERT_TRUE(res);
  1420. std::string out;
  1421. read_file("./image.jpg", out);
  1422. EXPECT_EQ(StatusCode::OK_200, res->status);
  1423. EXPECT_EQ(out, body);
  1424. }
  1425. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1426. std::string body;
  1427. auto res = cli_.Get(
  1428. "/chunked",
  1429. [&](const Response &response) {
  1430. EXPECT_EQ(StatusCode::OK_200, response.status);
  1431. return true;
  1432. },
  1433. [&](const char *data, size_t data_length) {
  1434. body.append(data, data_length);
  1435. return true;
  1436. });
  1437. ASSERT_TRUE(res);
  1438. std::string out;
  1439. read_file("./image.jpg", out);
  1440. EXPECT_EQ(StatusCode::OK_200, res->status);
  1441. EXPECT_EQ(out, body);
  1442. }
  1443. TEST(RangeTest, FromHTTPBin_Online) {
  1444. auto host = "httpbingo.org";
  1445. auto path = std::string{"/range/32"};
  1446. #ifdef CPPHTTPLIB_SSL_ENABLED
  1447. auto port = 443;
  1448. SSLClient cli(host, port);
  1449. #else
  1450. auto port = 80;
  1451. Client cli(host, port);
  1452. #endif
  1453. cli.set_connection_timeout(5);
  1454. {
  1455. auto res = cli.Get(path);
  1456. ASSERT_TRUE(res);
  1457. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1458. EXPECT_EQ(StatusCode::OK_200, res->status);
  1459. }
  1460. {
  1461. Headers headers = {make_range_header({{1, -1}})};
  1462. auto res = cli.Get(path, headers);
  1463. ASSERT_TRUE(res);
  1464. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1465. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1466. }
  1467. {
  1468. Headers headers = {make_range_header({{1, 10}})};
  1469. auto res = cli.Get(path, headers);
  1470. ASSERT_TRUE(res);
  1471. EXPECT_EQ("bcdefghijk", res->body);
  1472. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1473. }
  1474. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  1475. // entire resource, while the original httpbin returned 200. Both are
  1476. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  1477. {
  1478. Headers headers = {make_range_header({{0, 31}})};
  1479. auto res = cli.Get(path, headers);
  1480. ASSERT_TRUE(res);
  1481. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1482. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1483. res->status == StatusCode::PartialContent_206);
  1484. }
  1485. {
  1486. Headers headers = {make_range_header({{0, -1}})};
  1487. auto res = cli.Get(path, headers);
  1488. ASSERT_TRUE(res);
  1489. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1490. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1491. res->status == StatusCode::PartialContent_206);
  1492. }
  1493. // go-httpbin returns 206 with clamped range for over-range requests,
  1494. // while the original httpbin returned 416. Both behaviors are observed
  1495. // in real servers, so we only verify the request succeeds.
  1496. {
  1497. Headers headers = {make_range_header({{0, 32}})};
  1498. auto res = cli.Get(path, headers);
  1499. ASSERT_TRUE(res);
  1500. }
  1501. }
  1502. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1503. auto host = "unresolvableaddress.local";
  1504. auto path = std::string{"/"};
  1505. #ifdef CPPHTTPLIB_SSL_ENABLED
  1506. auto port = 443;
  1507. SSLClient cli(host, port);
  1508. #else
  1509. auto port = 80;
  1510. Client cli(host, port);
  1511. #endif
  1512. cli.set_connection_timeout(1);
  1513. {
  1514. auto res = cli.Get(path);
  1515. ASSERT_FALSE(res);
  1516. }
  1517. std::this_thread::sleep_for(std::chrono::seconds(8));
  1518. }
  1519. #if defined(__linux__) && defined(__GLIBC__) && \
  1520. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  1521. // Forward declaration: in split builds split.py strips `inline` and moves the
  1522. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  1523. // visible from the public httplib.h. Re-declaring it here lets the tests link
  1524. // against the symbol in both header-only and split builds.
  1525. namespace httplib {
  1526. namespace detail {
  1527. int getaddrinfo_with_timeout(const char *node, const char *service,
  1528. const struct addrinfo *hints,
  1529. struct addrinfo **res, time_t timeout_sec);
  1530. } // namespace detail
  1531. } // namespace httplib
  1532. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  1533. //
  1534. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  1535. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  1536. // gai_suspend() call hits the connection timeout the function calls
  1537. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  1538. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  1539. // still alive and still references the now-destroyed stack frame.
  1540. //
  1541. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  1542. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  1543. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  1544. // and runs them in a container.
  1545. namespace {
  1546. bool should_run_issue_2431_tests() {
  1547. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  1548. return v && *v && std::string(v) != "0";
  1549. }
  1550. std::string unique_unresolvable_host(int n) {
  1551. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  1552. // glibc still asks the configured nameserver — which is exactly the path
  1553. // we want to exercise. A unique label per call avoids the resolver cache.
  1554. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  1555. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  1556. std::to_string(n) + ".invalid";
  1557. }
  1558. } // namespace
  1559. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  1560. if (!should_run_issue_2431_tests()) {
  1561. GTEST_SKIP()
  1562. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1563. }
  1564. for (int i = 0; i < 8; ++i) {
  1565. struct addrinfo hints;
  1566. memset(&hints, 0, sizeof(hints));
  1567. hints.ai_family = AF_UNSPEC;
  1568. hints.ai_socktype = SOCK_STREAM;
  1569. auto host = unique_unresolvable_host(i);
  1570. struct addrinfo *result = nullptr;
  1571. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1572. &result, /*timeout_sec=*/1);
  1573. if (rc == 0 && result) { freeaddrinfo(result); }
  1574. }
  1575. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  1576. // stack region they still believe holds their gaicb.
  1577. std::this_thread::sleep_for(std::chrono::seconds(3));
  1578. }
  1579. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  1580. if (!should_run_issue_2431_tests()) {
  1581. GTEST_SKIP()
  1582. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1583. }
  1584. std::atomic<bool> stop{false};
  1585. std::vector<std::thread> threads;
  1586. for (int t = 0; t < 8; ++t) {
  1587. threads.emplace_back([t, &stop] {
  1588. int i = 0;
  1589. while (!stop.load(std::memory_order_relaxed)) {
  1590. struct addrinfo hints;
  1591. memset(&hints, 0, sizeof(hints));
  1592. hints.ai_family = AF_UNSPEC;
  1593. hints.ai_socktype = SOCK_STREAM;
  1594. auto host = unique_unresolvable_host(t * 100000 + i++);
  1595. struct addrinfo *result = nullptr;
  1596. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1597. &result, /*timeout_sec=*/1);
  1598. if (rc == 0 && result) { freeaddrinfo(result); }
  1599. }
  1600. });
  1601. }
  1602. std::this_thread::sleep_for(std::chrono::seconds(8));
  1603. stop.store(true, std::memory_order_relaxed);
  1604. for (auto &th : threads) {
  1605. th.join();
  1606. }
  1607. std::this_thread::sleep_for(std::chrono::seconds(3));
  1608. }
  1609. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  1610. if (!should_run_issue_2431_tests()) {
  1611. GTEST_SKIP()
  1612. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1613. }
  1614. std::atomic<bool> stop{false};
  1615. std::vector<std::thread> threads;
  1616. for (int t = 0; t < 8; ++t) {
  1617. threads.emplace_back([t, &stop] {
  1618. int i = 0;
  1619. while (!stop.load(std::memory_order_relaxed)) {
  1620. auto host = unique_unresolvable_host(t * 100000 + i++);
  1621. Client cli(host, 80);
  1622. cli.set_connection_timeout(1, 0);
  1623. cli.set_read_timeout(1, 0);
  1624. cli.set_write_timeout(1, 0);
  1625. (void)cli.Get("/");
  1626. }
  1627. });
  1628. }
  1629. std::this_thread::sleep_for(std::chrono::seconds(8));
  1630. stop.store(true, std::memory_order_relaxed);
  1631. for (auto &th : threads) {
  1632. th.join();
  1633. }
  1634. std::this_thread::sleep_for(std::chrono::seconds(3));
  1635. }
  1636. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  1637. TEST(ConnectionErrorTest, InvalidHost) {
  1638. auto host = "-abcde.com";
  1639. #ifdef CPPHTTPLIB_SSL_ENABLED
  1640. auto port = 443;
  1641. SSLClient cli(host, port);
  1642. #else
  1643. auto port = 80;
  1644. Client cli(host, port);
  1645. #endif
  1646. cli.set_connection_timeout(std::chrono::seconds(2));
  1647. auto res = cli.Get("/");
  1648. ASSERT_TRUE(!res);
  1649. EXPECT_EQ(Error::Connection, res.error());
  1650. }
  1651. TEST(ConnectionErrorTest, InvalidHost2) {
  1652. auto host = "httpcan.org/";
  1653. #ifdef CPPHTTPLIB_SSL_ENABLED
  1654. SSLClient cli(host);
  1655. #else
  1656. Client cli(host);
  1657. #endif
  1658. cli.set_connection_timeout(std::chrono::seconds(2));
  1659. auto res = cli.Get("/");
  1660. ASSERT_TRUE(!res);
  1661. EXPECT_EQ(Error::Connection, res.error());
  1662. }
  1663. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1664. auto host = "httpcan.org/";
  1665. #ifdef CPPHTTPLIB_SSL_ENABLED
  1666. SSLClient cli(host);
  1667. #else
  1668. Client cli(host);
  1669. #endif
  1670. cli.set_connection_timeout(std::chrono::seconds(2));
  1671. auto res = cli.Get("/");
  1672. ASSERT_TRUE(!res);
  1673. stringstream s;
  1674. s << "error code: " << res.error();
  1675. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1676. }
  1677. TEST(ConnectionErrorTest, InvalidPort) {
  1678. auto host = "localhost";
  1679. auto port = 44380;
  1680. #ifdef CPPHTTPLIB_SSL_ENABLED
  1681. SSLClient cli(host, port);
  1682. #else
  1683. Client cli(host, port);
  1684. #endif
  1685. cli.set_connection_timeout(std::chrono::seconds(2));
  1686. auto res = cli.Get("/");
  1687. ASSERT_TRUE(!res);
  1688. EXPECT_TRUE(Error::Connection == res.error() ||
  1689. Error::ConnectionTimeout == res.error());
  1690. }
  1691. TEST(ConnectionErrorTest, Timeout_Online) {
  1692. auto host = "google.com";
  1693. #ifdef CPPHTTPLIB_SSL_ENABLED
  1694. auto port = 44380;
  1695. SSLClient cli(host, port);
  1696. #else
  1697. auto port = 8080;
  1698. Client cli(host, port);
  1699. #endif
  1700. cli.set_connection_timeout(std::chrono::seconds(2));
  1701. // only probe one address type so that the error reason
  1702. // correlates to the timed-out IPv4, not the unsupported
  1703. // IPv6 connection attempt
  1704. cli.set_address_family(AF_INET);
  1705. auto res = cli.Get("/");
  1706. ASSERT_TRUE(!res);
  1707. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1708. }
  1709. TEST(CancelTest, NoCancel_Online) {
  1710. auto host = "httpbingo.org";
  1711. auto path = std::string{"/range/32"};
  1712. #ifdef CPPHTTPLIB_SSL_ENABLED
  1713. auto port = 443;
  1714. SSLClient cli(host, port);
  1715. #else
  1716. auto port = 80;
  1717. Client cli(host, port);
  1718. #endif
  1719. cli.set_connection_timeout(std::chrono::seconds(5));
  1720. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1721. ASSERT_TRUE(res);
  1722. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1723. EXPECT_EQ(StatusCode::OK_200, res->status);
  1724. }
  1725. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1726. // Use /bytes with a large payload so that the DownloadProgress callback
  1727. // (which only fires for Content-Length responses) is invoked before the
  1728. // entire body is received, giving cancellation a chance to fire.
  1729. auto host = "httpbingo.org";
  1730. auto path = std::string{"/bytes/524288"};
  1731. #ifdef CPPHTTPLIB_SSL_ENABLED
  1732. auto port = 443;
  1733. SSLClient cli(host, port);
  1734. #else
  1735. auto port = 80;
  1736. Client cli(host, port);
  1737. #endif
  1738. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1739. cli.set_connection_timeout(std::chrono::seconds(5));
  1740. ASSERT_TRUE(!res);
  1741. EXPECT_EQ(Error::Canceled, res.error());
  1742. }
  1743. TEST(CancelTest, WithCancelLargePayload_Online) {
  1744. auto host = "httpbingo.org";
  1745. auto path = std::string{"/bytes/524288"};
  1746. #ifdef CPPHTTPLIB_SSL_ENABLED
  1747. auto port = 443;
  1748. SSLClient cli(host, port);
  1749. #else
  1750. auto port = 80;
  1751. Client cli(host, port);
  1752. #endif
  1753. cli.set_connection_timeout(std::chrono::seconds(5));
  1754. uint32_t count = 0;
  1755. auto res =
  1756. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1757. ASSERT_TRUE(!res);
  1758. EXPECT_EQ(Error::Canceled, res.error());
  1759. }
  1760. TEST(CancelTest, NoCancelPost) {
  1761. Server svr;
  1762. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1763. res.set_content("Hello World!", "text/plain");
  1764. });
  1765. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1766. auto se = detail::scope_exit([&] {
  1767. svr.stop();
  1768. thread.join();
  1769. ASSERT_FALSE(svr.is_running());
  1770. });
  1771. svr.wait_until_ready();
  1772. Client cli(HOST, PORT);
  1773. cli.set_connection_timeout(std::chrono::seconds(5));
  1774. auto res =
  1775. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1776. "application/json", [](uint64_t, uint64_t) { return true; });
  1777. ASSERT_TRUE(res);
  1778. EXPECT_EQ("Hello World!", res->body);
  1779. EXPECT_EQ(StatusCode::OK_200, res->status);
  1780. }
  1781. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1782. Server svr;
  1783. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1784. res.set_content("Hello World!", "text/plain");
  1785. });
  1786. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1787. auto se = detail::scope_exit([&] {
  1788. svr.stop();
  1789. thread.join();
  1790. ASSERT_FALSE(svr.is_running());
  1791. });
  1792. svr.wait_until_ready();
  1793. Client cli(HOST, PORT);
  1794. cli.set_connection_timeout(std::chrono::seconds(5));
  1795. auto res =
  1796. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1797. "application/json", [](uint64_t, uint64_t) { return false; });
  1798. ASSERT_TRUE(!res);
  1799. EXPECT_EQ(Error::Canceled, res.error());
  1800. }
  1801. TEST(CancelTest, WithCancelLargePayloadPost) {
  1802. Server svr;
  1803. svr.set_payload_max_length(200 * 1024 * 1024);
  1804. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1805. res.set_content(LARGE_DATA, "text/plain");
  1806. });
  1807. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1808. auto se = detail::scope_exit([&] {
  1809. svr.stop();
  1810. thread.join();
  1811. ASSERT_FALSE(svr.is_running());
  1812. });
  1813. svr.wait_until_ready();
  1814. Client cli(HOST, PORT);
  1815. cli.set_payload_max_length(200 * 1024 * 1024);
  1816. cli.set_connection_timeout(std::chrono::seconds(5));
  1817. auto res =
  1818. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1819. "application/json", [](uint64_t, uint64_t) { return false; });
  1820. ASSERT_TRUE(!res);
  1821. EXPECT_EQ(Error::Canceled, res.error());
  1822. }
  1823. TEST(CancelTest, NoCancelPut) {
  1824. Server svr;
  1825. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1826. res.set_content("Hello World!", "text/plain");
  1827. });
  1828. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1829. auto se = detail::scope_exit([&] {
  1830. svr.stop();
  1831. thread.join();
  1832. ASSERT_FALSE(svr.is_running());
  1833. });
  1834. svr.wait_until_ready();
  1835. Client cli(HOST, PORT);
  1836. cli.set_connection_timeout(std::chrono::seconds(5));
  1837. auto res =
  1838. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1839. "application/json", [](uint64_t, uint64_t) { return true; });
  1840. ASSERT_TRUE(res);
  1841. EXPECT_EQ("Hello World!", res->body);
  1842. EXPECT_EQ(StatusCode::OK_200, res->status);
  1843. }
  1844. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1845. Server svr;
  1846. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1847. res.set_content("Hello World!", "text/plain");
  1848. });
  1849. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1850. auto se = detail::scope_exit([&] {
  1851. svr.stop();
  1852. thread.join();
  1853. ASSERT_FALSE(svr.is_running());
  1854. });
  1855. svr.wait_until_ready();
  1856. Client cli(HOST, PORT);
  1857. cli.set_connection_timeout(std::chrono::seconds(5));
  1858. auto res =
  1859. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1860. "application/json", [](uint64_t, uint64_t) { return false; });
  1861. ASSERT_TRUE(!res);
  1862. EXPECT_EQ(Error::Canceled, res.error());
  1863. }
  1864. TEST(CancelTest, WithCancelLargePayloadPut) {
  1865. Server svr;
  1866. svr.set_payload_max_length(200 * 1024 * 1024);
  1867. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1868. res.set_content(LARGE_DATA, "text/plain");
  1869. });
  1870. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1871. auto se = detail::scope_exit([&] {
  1872. svr.stop();
  1873. thread.join();
  1874. ASSERT_FALSE(svr.is_running());
  1875. });
  1876. svr.wait_until_ready();
  1877. Client cli(HOST, PORT);
  1878. cli.set_payload_max_length(200 * 1024 * 1024);
  1879. cli.set_connection_timeout(std::chrono::seconds(5));
  1880. auto res =
  1881. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1882. "application/json", [](uint64_t, uint64_t) { return false; });
  1883. ASSERT_TRUE(!res);
  1884. EXPECT_EQ(Error::Canceled, res.error());
  1885. }
  1886. TEST(CancelTest, NoCancelPatch) {
  1887. Server svr;
  1888. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1889. res.set_content("Hello World!", "text/plain");
  1890. });
  1891. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1892. auto se = detail::scope_exit([&] {
  1893. svr.stop();
  1894. thread.join();
  1895. ASSERT_FALSE(svr.is_running());
  1896. });
  1897. svr.wait_until_ready();
  1898. Client cli(HOST, PORT);
  1899. cli.set_connection_timeout(std::chrono::seconds(5));
  1900. auto res =
  1901. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1902. "application/json", [](uint64_t, uint64_t) { return true; });
  1903. ASSERT_TRUE(res);
  1904. EXPECT_EQ("Hello World!", res->body);
  1905. EXPECT_EQ(StatusCode::OK_200, res->status);
  1906. }
  1907. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1908. Server svr;
  1909. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1910. res.set_content("Hello World!", "text/plain");
  1911. });
  1912. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1913. auto se = detail::scope_exit([&] {
  1914. svr.stop();
  1915. thread.join();
  1916. ASSERT_FALSE(svr.is_running());
  1917. });
  1918. svr.wait_until_ready();
  1919. Client cli(HOST, PORT);
  1920. cli.set_connection_timeout(std::chrono::seconds(5));
  1921. auto res =
  1922. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1923. "application/json", [](uint64_t, uint64_t) { return false; });
  1924. ASSERT_TRUE(!res);
  1925. EXPECT_EQ(Error::Canceled, res.error());
  1926. }
  1927. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1928. Server svr;
  1929. svr.set_payload_max_length(200 * 1024 * 1024);
  1930. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1931. res.set_content(LARGE_DATA, "text/plain");
  1932. });
  1933. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1934. auto se = detail::scope_exit([&] {
  1935. svr.stop();
  1936. thread.join();
  1937. ASSERT_FALSE(svr.is_running());
  1938. });
  1939. svr.wait_until_ready();
  1940. Client cli(HOST, PORT);
  1941. cli.set_payload_max_length(200 * 1024 * 1024);
  1942. cli.set_connection_timeout(std::chrono::seconds(5));
  1943. auto res =
  1944. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1945. "application/json", [](uint64_t, uint64_t) { return false; });
  1946. ASSERT_TRUE(!res);
  1947. EXPECT_EQ(Error::Canceled, res.error());
  1948. }
  1949. TEST(CancelTest, NoCancelDelete) {
  1950. Server svr;
  1951. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1952. res.set_content("Hello World!", "text/plain");
  1953. });
  1954. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1955. auto se = detail::scope_exit([&] {
  1956. svr.stop();
  1957. thread.join();
  1958. ASSERT_FALSE(svr.is_running());
  1959. });
  1960. svr.wait_until_ready();
  1961. Client cli(HOST, PORT);
  1962. cli.set_connection_timeout(std::chrono::seconds(5));
  1963. auto res =
  1964. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1965. "application/json", [](uint64_t, uint64_t) { return true; });
  1966. ASSERT_TRUE(res);
  1967. EXPECT_EQ("Hello World!", res->body);
  1968. EXPECT_EQ(StatusCode::OK_200, res->status);
  1969. }
  1970. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1971. Server svr;
  1972. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1973. res.set_content("Hello World!", "text/plain");
  1974. });
  1975. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1976. auto se = detail::scope_exit([&] {
  1977. svr.stop();
  1978. thread.join();
  1979. ASSERT_FALSE(svr.is_running());
  1980. });
  1981. svr.wait_until_ready();
  1982. Client cli(HOST, PORT);
  1983. cli.set_connection_timeout(std::chrono::seconds(5));
  1984. auto res =
  1985. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1986. "application/json", [](uint64_t, uint64_t) { return false; });
  1987. ASSERT_TRUE(!res);
  1988. EXPECT_EQ(Error::Canceled, res.error());
  1989. }
  1990. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1991. Server svr;
  1992. svr.set_payload_max_length(200 * 1024 * 1024);
  1993. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1994. res.set_content(LARGE_DATA, "text/plain");
  1995. });
  1996. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1997. auto se = detail::scope_exit([&] {
  1998. svr.stop();
  1999. thread.join();
  2000. ASSERT_FALSE(svr.is_running());
  2001. });
  2002. svr.wait_until_ready();
  2003. Client cli(HOST, PORT);
  2004. cli.set_payload_max_length(200 * 1024 * 1024);
  2005. cli.set_connection_timeout(std::chrono::seconds(5));
  2006. auto res =
  2007. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2008. "application/json", [](uint64_t, uint64_t) { return false; });
  2009. ASSERT_TRUE(!res);
  2010. EXPECT_EQ(Error::Canceled, res.error());
  2011. }
  2012. static std::string remove_whitespace(const std::string &input) {
  2013. std::string output;
  2014. output.reserve(input.size());
  2015. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2016. [](unsigned char c) { return !std::isspace(c); });
  2017. return output;
  2018. }
  2019. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2020. auto host = "httpbingo.org";
  2021. auto path = std::string{"/basic-auth/hello/world"};
  2022. #ifdef CPPHTTPLIB_SSL_ENABLED
  2023. auto port = 443;
  2024. SSLClient cli(host, port);
  2025. #else
  2026. auto port = 80;
  2027. Client cli(host, port);
  2028. #endif
  2029. {
  2030. auto res = cli.Get(path);
  2031. ASSERT_TRUE(res);
  2032. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2033. }
  2034. {
  2035. auto res = cli.Get(
  2036. path, Headers{make_basic_authentication_header("hello", "world")});
  2037. ASSERT_TRUE(res);
  2038. auto body = remove_whitespace(res->body);
  2039. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2040. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2041. EXPECT_EQ(StatusCode::OK_200, res->status);
  2042. }
  2043. {
  2044. cli.set_basic_auth("hello", "world");
  2045. auto res = cli.Get(path);
  2046. ASSERT_TRUE(res);
  2047. auto body = remove_whitespace(res->body);
  2048. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2049. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2050. EXPECT_EQ(StatusCode::OK_200, res->status);
  2051. }
  2052. {
  2053. cli.set_basic_auth("hello", "bad");
  2054. auto res = cli.Get(path);
  2055. ASSERT_TRUE(res);
  2056. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2057. }
  2058. {
  2059. cli.set_basic_auth("bad", "world");
  2060. auto res = cli.Get(path);
  2061. ASSERT_TRUE(res);
  2062. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2063. }
  2064. }
  2065. #ifdef CPPHTTPLIB_SSL_ENABLED
  2066. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2067. auto host = "httpbingo.org";
  2068. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2069. auto paths = std::vector<std::string>{
  2070. "/digest-auth/auth/hello/world/MD5",
  2071. "/digest-auth/auth/hello/world/SHA-256",
  2072. };
  2073. auto port = 443;
  2074. SSLClient cli(host, port);
  2075. {
  2076. auto res = cli.Get(unauth_path);
  2077. ASSERT_TRUE(res);
  2078. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2079. }
  2080. {
  2081. cli.set_digest_auth("hello", "world");
  2082. for (const auto &path : paths) {
  2083. auto res = cli.Get(path.c_str());
  2084. ASSERT_TRUE(res);
  2085. auto body = remove_whitespace(res->body);
  2086. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2087. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2088. EXPECT_EQ(StatusCode::OK_200, res->status);
  2089. }
  2090. cli.set_digest_auth("hello", "bad");
  2091. for (const auto &path : paths) {
  2092. auto res = cli.Get(path.c_str());
  2093. ASSERT_TRUE(res);
  2094. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2095. }
  2096. }
  2097. }
  2098. #endif
  2099. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  2100. auto host = "google.com";
  2101. auto another_host = "example.com";
  2102. auto wrong_ip = "0.0.0.0";
  2103. #ifdef CPPHTTPLIB_SSL_ENABLED
  2104. SSLClient cli(host);
  2105. #else
  2106. Client cli(host);
  2107. #endif
  2108. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  2109. auto res = cli.Get("/");
  2110. ASSERT_TRUE(res);
  2111. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  2112. }
  2113. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  2114. auto host = "google.com";
  2115. auto wrong_ip = "0.0.0.0";
  2116. #ifdef CPPHTTPLIB_SSL_ENABLED
  2117. SSLClient cli(host);
  2118. #else
  2119. Client cli(host);
  2120. #endif
  2121. cli.set_hostname_addr_map({{host, wrong_ip}});
  2122. auto res = cli.Get("/");
  2123. ASSERT_TRUE(!res);
  2124. EXPECT_EQ(Error::Connection, res.error());
  2125. }
  2126. TEST(AbsoluteRedirectTest, Redirect_Online) {
  2127. auto host = "httpbingo.org";
  2128. auto path = std::string{"/absolute-redirect/3"};
  2129. #ifdef CPPHTTPLIB_SSL_ENABLED
  2130. SSLClient cli(host);
  2131. #else
  2132. Client cli(host);
  2133. #endif
  2134. cli.set_follow_location(true);
  2135. auto res = cli.Get(path);
  2136. ASSERT_TRUE(res);
  2137. EXPECT_EQ(StatusCode::OK_200, res->status);
  2138. }
  2139. TEST(RedirectTest, Redirect_Online) {
  2140. auto host = "httpbingo.org";
  2141. auto path = std::string{"/redirect/3"};
  2142. #ifdef CPPHTTPLIB_SSL_ENABLED
  2143. SSLClient cli(host);
  2144. #else
  2145. Client cli(host);
  2146. #endif
  2147. cli.set_follow_location(true);
  2148. auto res = cli.Get(path);
  2149. ASSERT_TRUE(res);
  2150. EXPECT_EQ(StatusCode::OK_200, res->status);
  2151. }
  2152. TEST(RelativeRedirectTest, Redirect_Online) {
  2153. auto host = "httpbingo.org";
  2154. auto path = std::string{"/relative-redirect/3"};
  2155. #ifdef CPPHTTPLIB_SSL_ENABLED
  2156. SSLClient cli(host);
  2157. #else
  2158. Client cli(host);
  2159. #endif
  2160. cli.set_follow_location(true);
  2161. auto res = cli.Get(path);
  2162. ASSERT_TRUE(res);
  2163. EXPECT_EQ(StatusCode::OK_200, res->status);
  2164. }
  2165. TEST(TooManyRedirectTest, Redirect_Online) {
  2166. auto host = "httpbingo.org";
  2167. auto path = std::string{"/redirect/21"};
  2168. #ifdef CPPHTTPLIB_SSL_ENABLED
  2169. SSLClient cli(host);
  2170. #else
  2171. Client cli(host);
  2172. #endif
  2173. cli.set_follow_location(true);
  2174. auto res = cli.Get(path);
  2175. ASSERT_TRUE(!res);
  2176. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  2177. }
  2178. #ifdef CPPHTTPLIB_SSL_ENABLED
  2179. TEST(YahooRedirectTest, Redirect_Online) {
  2180. Client cli("yahoo.com");
  2181. auto res = cli.Get("/");
  2182. ASSERT_TRUE(res);
  2183. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  2184. cli.set_follow_location(true);
  2185. res = cli.Get("/");
  2186. ASSERT_TRUE(res);
  2187. EXPECT_EQ(StatusCode::OK_200, res->status);
  2188. EXPECT_EQ("https://www.yahoo.com/", res->location);
  2189. }
  2190. // Previously "nghttp2.org" "/httpbin/redirect-to"
  2191. #define REDIR_HOST "httpbingo.org"
  2192. #define REDIR_PATH "/redirect-to"
  2193. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  2194. SSLClient cli(REDIR_HOST);
  2195. cli.set_follow_location(true);
  2196. auto res =
  2197. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  2198. ASSERT_TRUE(res);
  2199. EXPECT_EQ(StatusCode::OK_200, res->status);
  2200. }
  2201. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  2202. SSLClient cli(REDIR_HOST);
  2203. cli.set_follow_location(true);
  2204. Params params;
  2205. params.emplace("url", "http://example.com");
  2206. params.emplace("status_code", "302");
  2207. auto res = cli.Get(REDIR_PATH, params, Headers{});
  2208. ASSERT_TRUE(res);
  2209. EXPECT_EQ(StatusCode::OK_200, res->status);
  2210. }
  2211. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  2212. SSLClient cli(REDIR_HOST);
  2213. cli.set_follow_location(true);
  2214. Params params;
  2215. params.emplace("url", "http://example.com");
  2216. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  2217. ASSERT_TRUE(res);
  2218. EXPECT_EQ(StatusCode::OK_200, res->status);
  2219. }
  2220. TEST(UrlWithSpace, Redirect_Online) {
  2221. SSLClient cli("edge.forgecdn.net");
  2222. cli.set_follow_location(true);
  2223. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  2224. ASSERT_TRUE(res);
  2225. EXPECT_EQ(StatusCode::OK_200, res->status);
  2226. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  2227. }
  2228. #endif
  2229. #if !defined(_WIN32) && !defined(_WIN64)
  2230. TEST(ReceiveSignals, Signal) {
  2231. auto setupSignalHandlers = []() {
  2232. struct sigaction act;
  2233. sigemptyset(&act.sa_mask);
  2234. act.sa_flags = SA_SIGINFO;
  2235. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  2236. switch (sig) {
  2237. case SIGINT:
  2238. default: break;
  2239. }
  2240. };
  2241. ::sigaction(SIGINT, &act, nullptr);
  2242. };
  2243. Server svr;
  2244. int port = 0;
  2245. auto thread = std::thread([&]() {
  2246. setupSignalHandlers();
  2247. port = svr.bind_to_any_port(HOST);
  2248. svr.listen_after_bind();
  2249. });
  2250. auto se = detail::scope_exit([&] {
  2251. svr.stop();
  2252. thread.join();
  2253. ASSERT_FALSE(svr.is_running());
  2254. });
  2255. svr.wait_until_ready();
  2256. ASSERT_TRUE(svr.is_running());
  2257. pthread_kill(thread.native_handle(), SIGINT);
  2258. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  2259. ASSERT_TRUE(svr.is_running());
  2260. }
  2261. #endif
  2262. TEST(RedirectToDifferentPort, Redirect) {
  2263. Server svr1;
  2264. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  2265. res.set_content("Hello World!", "text/plain");
  2266. });
  2267. int svr1_port = 0;
  2268. auto thread1 = std::thread([&]() {
  2269. svr1_port = svr1.bind_to_any_port(HOST);
  2270. svr1.listen_after_bind();
  2271. });
  2272. Server svr2;
  2273. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  2274. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  2275. });
  2276. int svr2_port = 0;
  2277. auto thread2 = std::thread([&]() {
  2278. svr2_port = svr2.bind_to_any_port(HOST);
  2279. svr2.listen_after_bind();
  2280. });
  2281. auto se = detail::scope_exit([&] {
  2282. svr2.stop();
  2283. thread2.join();
  2284. svr1.stop();
  2285. thread1.join();
  2286. ASSERT_FALSE(svr2.is_running());
  2287. ASSERT_FALSE(svr1.is_running());
  2288. });
  2289. svr1.wait_until_ready();
  2290. svr2.wait_until_ready();
  2291. Client cli("localhost", svr2_port);
  2292. cli.set_follow_location(true);
  2293. auto res = cli.Get("/2");
  2294. ASSERT_TRUE(res);
  2295. EXPECT_EQ(StatusCode::OK_200, res->status);
  2296. EXPECT_EQ("Hello World!", res->body);
  2297. }
  2298. static void
  2299. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  2300. Server svr1;
  2301. std::string captured_authorization;
  2302. svr1.Get("/target", [&](const Request &req, Response &res) {
  2303. captured_authorization = req.get_header_value("Authorization");
  2304. res.set_content("OK", "text/plain");
  2305. });
  2306. int svr1_port = 0;
  2307. auto thread1 = std::thread([&]() {
  2308. svr1_port = svr1.bind_to_any_port(HOST);
  2309. svr1.listen_after_bind();
  2310. });
  2311. Server svr2;
  2312. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2313. res.set_redirect(
  2314. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  2315. });
  2316. int svr2_port = 0;
  2317. auto thread2 = std::thread([&]() {
  2318. svr2_port = svr2.bind_to_any_port(HOST);
  2319. svr2.listen_after_bind();
  2320. });
  2321. auto se = detail::scope_exit([&] {
  2322. svr2.stop();
  2323. thread2.join();
  2324. svr1.stop();
  2325. thread1.join();
  2326. ASSERT_FALSE(svr2.is_running());
  2327. ASSERT_FALSE(svr1.is_running());
  2328. });
  2329. svr1.wait_until_ready();
  2330. svr2.wait_until_ready();
  2331. Client cli("localhost", svr2_port);
  2332. cli.set_follow_location(true);
  2333. set_auth(cli);
  2334. auto res = cli.Get("/redir");
  2335. ASSERT_TRUE(res);
  2336. EXPECT_EQ(StatusCode::OK_200, res->status);
  2337. // RFC 9110: credentials MUST NOT be forwarded to a different host
  2338. EXPECT_TRUE(captured_authorization.empty());
  2339. }
  2340. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  2341. TestDoNotForwardCredentialsOnRedirect(
  2342. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  2343. }
  2344. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  2345. TestDoNotForwardCredentialsOnRedirect(
  2346. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  2347. }
  2348. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  2349. Server svr1;
  2350. std::string captured_cookie;
  2351. bool target_hit = false;
  2352. svr1.Get("/target", [&](const Request &req, Response &res) {
  2353. captured_cookie = req.get_header_value("Cookie");
  2354. target_hit = true;
  2355. res.set_content("OK", "text/plain");
  2356. });
  2357. int svr1_port = 0;
  2358. auto thread1 = std::thread([&]() {
  2359. svr1_port = svr1.bind_to_any_port(HOST);
  2360. svr1.listen_after_bind();
  2361. });
  2362. Server svr2;
  2363. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2364. res.set_redirect(
  2365. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  2366. });
  2367. int svr2_port = 0;
  2368. auto thread2 = std::thread([&]() {
  2369. svr2_port = svr2.bind_to_any_port(HOST);
  2370. svr2.listen_after_bind();
  2371. });
  2372. auto se = detail::scope_exit([&] {
  2373. svr2.stop();
  2374. thread2.join();
  2375. svr1.stop();
  2376. thread1.join();
  2377. ASSERT_FALSE(svr2.is_running());
  2378. ASSERT_FALSE(svr1.is_running());
  2379. });
  2380. svr1.wait_until_ready();
  2381. svr2.wait_until_ready();
  2382. Client cli("localhost", svr2_port);
  2383. cli.set_follow_location(true);
  2384. Headers headers = {{"Cookie", "session_id=SECRET; auth=PRIVATE"}};
  2385. auto res = cli.Get("/redir", headers);
  2386. ASSERT_TRUE(res);
  2387. EXPECT_EQ(StatusCode::OK_200, res->status);
  2388. EXPECT_TRUE(target_hit);
  2389. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  2390. EXPECT_TRUE(captured_cookie.empty());
  2391. }
  2392. TEST(RedirectToSamePort, ForwardCookie) {
  2393. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  2394. // header so that ordinary session flows keep working.
  2395. Server svr;
  2396. std::string captured_cookie;
  2397. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2398. res.set_redirect("/target", 302);
  2399. });
  2400. svr.Get("/target", [&](const Request &req, Response &res) {
  2401. captured_cookie = req.get_header_value("Cookie");
  2402. res.set_content("OK", "text/plain");
  2403. });
  2404. auto port = svr.bind_to_any_port(HOST);
  2405. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2406. auto se = detail::scope_exit([&] {
  2407. svr.stop();
  2408. thread.join();
  2409. ASSERT_FALSE(svr.is_running());
  2410. });
  2411. svr.wait_until_ready();
  2412. Client cli(HOST, port);
  2413. cli.set_follow_location(true);
  2414. Headers headers = {{"Cookie", "session_id=SECRET"}};
  2415. auto res = cli.Get("/redir", headers);
  2416. ASSERT_TRUE(res);
  2417. EXPECT_EQ(StatusCode::OK_200, res->status);
  2418. EXPECT_EQ("session_id=SECRET", captured_cookie);
  2419. }
  2420. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  2421. Server svr;
  2422. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2423. // Port number that overflows int — should not crash
  2424. res.set_redirect("http://localhost:99999999999999999999/target");
  2425. });
  2426. auto port = svr.bind_to_any_port(HOST);
  2427. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2428. auto se = detail::scope_exit([&] {
  2429. svr.stop();
  2430. thread.join();
  2431. ASSERT_FALSE(svr.is_running());
  2432. });
  2433. svr.wait_until_ready();
  2434. Client cli(HOST, port);
  2435. cli.set_follow_location(true);
  2436. auto res = cli.Get("/redir");
  2437. // Should fail gracefully, not crash (no valid response due to bad port)
  2438. EXPECT_FALSE(res);
  2439. }
  2440. TEST(RedirectFromPageWithContent, Redirect) {
  2441. Server svr;
  2442. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2443. res.set_content("___", "text/plain");
  2444. res.set_redirect("/2");
  2445. });
  2446. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  2447. res.set_content("Hello World!", "text/plain");
  2448. });
  2449. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  2450. auto se = detail::scope_exit([&] {
  2451. svr.stop();
  2452. th.join();
  2453. ASSERT_FALSE(svr.is_running());
  2454. });
  2455. svr.wait_until_ready();
  2456. {
  2457. Client cli("localhost", PORT);
  2458. cli.set_follow_location(true);
  2459. std::string body;
  2460. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2461. body.append(data, data_length);
  2462. return true;
  2463. });
  2464. ASSERT_TRUE(res);
  2465. EXPECT_EQ(StatusCode::OK_200, res->status);
  2466. EXPECT_EQ("Hello World!", body);
  2467. }
  2468. {
  2469. Client cli("localhost", PORT);
  2470. std::string body;
  2471. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2472. body.append(data, data_length);
  2473. return true;
  2474. });
  2475. ASSERT_TRUE(res);
  2476. EXPECT_EQ(StatusCode::Found_302, res->status);
  2477. EXPECT_EQ("___", body);
  2478. }
  2479. }
  2480. TEST(RedirectFromPageWithContentIP6, Redirect) {
  2481. Server svr;
  2482. auto port_str = std::to_string(PORT);
  2483. auto redirect_url = "http://[::1]:" + port_str + "/2";
  2484. auto expected_host = "[::1]:" + port_str;
  2485. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2486. res.set_content("___", "text/plain");
  2487. // res.set_redirect("/2");
  2488. res.set_redirect(redirect_url);
  2489. });
  2490. svr.Get("/2", [&](const Request &req, Response &res) {
  2491. auto host_header = req.headers.find("Host");
  2492. ASSERT_TRUE(host_header != req.headers.end());
  2493. EXPECT_EQ(expected_host, host_header->second);
  2494. res.set_content("Hello World!", "text/plain");
  2495. });
  2496. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  2497. auto se = detail::scope_exit([&] {
  2498. svr.stop();
  2499. th.join();
  2500. ASSERT_FALSE(svr.is_running());
  2501. });
  2502. // When IPV6 support isn't available svr.listen("::1", PORT) never
  2503. // actually starts anything, so the condition !svr.is_running() will
  2504. // always remain true, and the loop never stops.
  2505. // This basically counts how many milliseconds have passed since the
  2506. // call to svr.listen(), and if after 5 seconds nothing started yet
  2507. // aborts the test.
  2508. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  2509. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2510. ASSERT_LT(milliseconds, 5000U);
  2511. }
  2512. {
  2513. Client cli("::1", PORT);
  2514. cli.set_follow_location(true);
  2515. std::string body;
  2516. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2517. body.append(data, data_length);
  2518. return true;
  2519. });
  2520. ASSERT_TRUE(res);
  2521. EXPECT_EQ(StatusCode::OK_200, res->status);
  2522. EXPECT_EQ("Hello World!", body);
  2523. }
  2524. {
  2525. Client cli("::1", PORT);
  2526. std::string body;
  2527. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2528. body.append(data, data_length);
  2529. return true;
  2530. });
  2531. ASSERT_TRUE(res);
  2532. EXPECT_EQ(StatusCode::Found_302, res->status);
  2533. EXPECT_EQ("___", body);
  2534. }
  2535. }
  2536. TEST(PathUrlEncodeTest, PathUrlEncode) {
  2537. Server svr;
  2538. svr.Get("/foo", [](const Request &req, Response &res) {
  2539. auto a = req.params.find("a");
  2540. if (a != req.params.end()) {
  2541. res.set_content((*a).second, "text/plain");
  2542. res.status = StatusCode::OK_200;
  2543. } else {
  2544. res.status = StatusCode::BadRequest_400;
  2545. }
  2546. });
  2547. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2548. auto se = detail::scope_exit([&] {
  2549. svr.stop();
  2550. thread.join();
  2551. ASSERT_FALSE(svr.is_running());
  2552. });
  2553. svr.wait_until_ready();
  2554. {
  2555. Client cli(HOST, PORT);
  2556. cli.set_path_encode(false);
  2557. auto res = cli.Get("/foo?a=explicitly+encoded");
  2558. ASSERT_TRUE(res);
  2559. EXPECT_EQ(StatusCode::OK_200, res->status);
  2560. // This expects it back with a space, as the `+` won't have been
  2561. // url-encoded, and server-side the params get decoded turning `+`
  2562. // into spaces.
  2563. EXPECT_EQ("explicitly encoded", res->body);
  2564. }
  2565. }
  2566. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  2567. // When path encoding is disabled the client must transmit the supplied
  2568. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  2569. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  2570. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  2571. // than a space (0x20). Assert on the raw wire target to catch this.
  2572. Server svr;
  2573. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  2574. svr.Get("/foo", [&](const Request &req, Response &res) {
  2575. EXPECT_EQ(expected_target, req.target);
  2576. res.status = StatusCode::OK_200;
  2577. });
  2578. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2579. auto se = detail::scope_exit([&] {
  2580. svr.stop();
  2581. thread.join();
  2582. ASSERT_FALSE(svr.is_running());
  2583. });
  2584. svr.wait_until_ready();
  2585. {
  2586. Client cli(HOST, PORT);
  2587. cli.set_path_encode(false);
  2588. auto res = cli.Get(expected_target.c_str());
  2589. ASSERT_TRUE(res);
  2590. EXPECT_EQ(StatusCode::OK_200, res->status);
  2591. }
  2592. }
  2593. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  2594. Server svr;
  2595. svr.Get("/", [](const Request &req, Response &) {
  2596. EXPECT_EQ("\x0A", req.get_param_value("something"));
  2597. });
  2598. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2599. auto se = detail::scope_exit([&] {
  2600. svr.stop();
  2601. thread.join();
  2602. ASSERT_FALSE(svr.is_running());
  2603. });
  2604. svr.wait_until_ready();
  2605. {
  2606. Client cli(HOST, PORT);
  2607. cli.set_path_encode(false);
  2608. auto res = cli.Get("/?something=%0A");
  2609. ASSERT_TRUE(res);
  2610. EXPECT_EQ(StatusCode::OK_200, res->status);
  2611. }
  2612. }
  2613. TEST(BindServerTest, BindDualStack) {
  2614. Server svr;
  2615. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2616. res.set_content("Hello World!", "text/plain");
  2617. });
  2618. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  2619. auto se = detail::scope_exit([&] {
  2620. svr.stop();
  2621. thread.join();
  2622. ASSERT_FALSE(svr.is_running());
  2623. });
  2624. svr.wait_until_ready();
  2625. {
  2626. Client cli("127.0.0.1", PORT);
  2627. auto res = cli.Get("/1");
  2628. ASSERT_TRUE(res);
  2629. EXPECT_EQ(StatusCode::OK_200, res->status);
  2630. EXPECT_EQ("Hello World!", res->body);
  2631. }
  2632. {
  2633. Client cli("::1", PORT);
  2634. auto res = cli.Get("/1");
  2635. ASSERT_TRUE(res);
  2636. EXPECT_EQ(StatusCode::OK_200, res->status);
  2637. EXPECT_EQ("Hello World!", res->body);
  2638. }
  2639. }
  2640. TEST(BindServerTest, BindAndListenSeparately) {
  2641. Server svr;
  2642. int port = svr.bind_to_any_port("0.0.0.0");
  2643. ASSERT_TRUE(svr.is_valid());
  2644. ASSERT_TRUE(port > 0);
  2645. svr.stop();
  2646. }
  2647. #ifdef CPPHTTPLIB_SSL_ENABLED
  2648. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  2649. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  2650. CLIENT_CA_CERT_DIR);
  2651. int port = svr.bind_to_any_port("0.0.0.0");
  2652. ASSERT_TRUE(svr.is_valid());
  2653. ASSERT_TRUE(port > 0);
  2654. svr.stop();
  2655. }
  2656. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  2657. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  2658. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  2659. int port = svr.bind_to_any_port("0.0.0.0");
  2660. ASSERT_TRUE(svr.is_valid());
  2661. ASSERT_TRUE(port > 0);
  2662. svr.stop();
  2663. }
  2664. TEST(BindServerTest, UpdateCertsPem) {
  2665. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2666. int port = svr.bind_to_any_port("0.0.0.0");
  2667. ASSERT_TRUE(svr.is_valid());
  2668. ASSERT_TRUE(port > 0);
  2669. // Read PEM files
  2670. std::string cert_pem, key_pem, ca_pem;
  2671. read_file(SERVER_CERT_FILE, cert_pem);
  2672. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2673. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2674. // Update server certificates using PEM API
  2675. ASSERT_TRUE(
  2676. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2677. ASSERT_TRUE(svr.is_valid());
  2678. svr.stop();
  2679. }
  2680. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  2681. // Start server with client CA (enables client auth)
  2682. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2683. ASSERT_TRUE(svr.is_valid());
  2684. bool handler_called = false;
  2685. svr.Get("/test", [&](const Request &req, Response &res) {
  2686. handler_called = true;
  2687. // Verify client certificate is present
  2688. auto cert = req.peer_cert();
  2689. EXPECT_TRUE(static_cast<bool>(cert));
  2690. res.set_content("ok", "text/plain");
  2691. });
  2692. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  2693. auto se = detail::scope_exit([&] {
  2694. svr.stop();
  2695. t.join();
  2696. ASSERT_FALSE(svr.is_running());
  2697. });
  2698. svr.wait_until_ready();
  2699. // Read PEM files
  2700. std::string cert_pem, key_pem, ca_pem;
  2701. read_file(SERVER_CERT_FILE, cert_pem);
  2702. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2703. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2704. // Update server certificates and client CA using PEM API while server running
  2705. ASSERT_TRUE(
  2706. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2707. // Connect with client certificate
  2708. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  2709. cli.enable_server_certificate_verification(false);
  2710. cli.set_connection_timeout(30);
  2711. auto res = cli.Get("/test");
  2712. ASSERT_TRUE(res);
  2713. ASSERT_EQ(StatusCode::OK_200, res->status);
  2714. ASSERT_TRUE(handler_called);
  2715. EXPECT_EQ("ok", res->body);
  2716. }
  2717. #endif
  2718. TEST(ErrorHandlerTest, ContentLength) {
  2719. Server svr;
  2720. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2721. res.status = StatusCode::OK_200;
  2722. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2723. "text/html"); // <= Content-Length still 13
  2724. });
  2725. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2726. res.set_content("Hello World!\n", "text/plain");
  2727. res.status = 524;
  2728. });
  2729. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2730. auto se = detail::scope_exit([&] {
  2731. svr.stop();
  2732. thread.join();
  2733. ASSERT_FALSE(svr.is_running());
  2734. });
  2735. svr.wait_until_ready();
  2736. {
  2737. Client cli(HOST, PORT);
  2738. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  2739. ASSERT_TRUE(res);
  2740. EXPECT_EQ(StatusCode::OK_200, res->status);
  2741. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2742. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2743. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2744. }
  2745. }
  2746. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2747. TEST(ExceptionTest, WithoutExceptionHandler) {
  2748. Server svr;
  2749. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  2750. throw std::runtime_error("exception...");
  2751. });
  2752. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  2753. throw std::runtime_error("exception\r\n...");
  2754. });
  2755. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2756. auto se = detail::scope_exit([&] {
  2757. svr.stop();
  2758. listen_thread.join();
  2759. ASSERT_FALSE(svr.is_running());
  2760. });
  2761. svr.wait_until_ready();
  2762. Client cli("localhost", PORT);
  2763. {
  2764. auto res = cli.Get("/exception");
  2765. ASSERT_TRUE(res);
  2766. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2767. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2768. }
  2769. {
  2770. auto res = cli.Get("/unknown");
  2771. ASSERT_TRUE(res);
  2772. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2773. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2774. }
  2775. }
  2776. TEST(ExceptionTest, WithExceptionHandler) {
  2777. Server svr;
  2778. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  2779. std::exception_ptr ep) {
  2780. EXPECT_FALSE(ep == nullptr);
  2781. try {
  2782. std::rethrow_exception(ep);
  2783. } catch (std::exception &e) {
  2784. EXPECT_EQ("abc", std::string(e.what()));
  2785. } catch (...) {}
  2786. res.status = StatusCode::InternalServerError_500;
  2787. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2788. "text/html"); // <= Content-Length still 13 at this point
  2789. });
  2790. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2791. res.set_content("Hello World!\n", "text/plain");
  2792. throw std::runtime_error("abc");
  2793. });
  2794. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2795. auto se = detail::scope_exit([&] {
  2796. svr.stop();
  2797. thread.join();
  2798. ASSERT_FALSE(svr.is_running());
  2799. });
  2800. svr.wait_until_ready();
  2801. for (size_t i = 0; i < 10; i++) {
  2802. Client cli(HOST, PORT);
  2803. for (size_t j = 0; j < 100; j++) {
  2804. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  2805. ASSERT_TRUE(res);
  2806. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2807. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2808. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2809. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2810. }
  2811. cli.set_keep_alive(true);
  2812. for (size_t j = 0; j < 100; j++) {
  2813. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  2814. ASSERT_TRUE(res);
  2815. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2816. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2817. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2818. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2819. }
  2820. }
  2821. }
  2822. TEST(ExceptionTest, AndErrorHandler) {
  2823. Server svr;
  2824. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2825. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  2826. });
  2827. svr.set_exception_handler(
  2828. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  2829. EXPECT_FALSE(ep == nullptr);
  2830. try {
  2831. std::rethrow_exception(ep);
  2832. } catch (std::exception &e) {
  2833. res.set_content(e.what(), "text/html");
  2834. } catch (...) {}
  2835. res.status = StatusCode::InternalServerError_500;
  2836. });
  2837. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  2838. throw std::runtime_error("EXCEPTION");
  2839. });
  2840. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  2841. res.set_content("ERROR", "text/html");
  2842. res.status = StatusCode::InternalServerError_500;
  2843. });
  2844. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2845. auto se = detail::scope_exit([&] {
  2846. svr.stop();
  2847. thread.join();
  2848. ASSERT_FALSE(svr.is_running());
  2849. });
  2850. svr.wait_until_ready();
  2851. Client cli(HOST, PORT);
  2852. {
  2853. auto res = cli.Get("/exception");
  2854. ASSERT_TRUE(res);
  2855. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2856. EXPECT_EQ("EXCEPTION", res->body);
  2857. }
  2858. {
  2859. auto res = cli.Get("/error");
  2860. ASSERT_TRUE(res);
  2861. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2862. EXPECT_EQ("ERROR", res->body);
  2863. }
  2864. {
  2865. auto res = cli.Get("/invalid");
  2866. ASSERT_TRUE(res);
  2867. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2868. EXPECT_EQ("NOT_FOUND", res->body);
  2869. }
  2870. }
  2871. #endif
  2872. TEST(NoContentTest, ContentLength) {
  2873. Server svr;
  2874. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2875. res.status = StatusCode::NoContent_204;
  2876. });
  2877. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2878. auto se = detail::scope_exit([&] {
  2879. svr.stop();
  2880. thread.join();
  2881. ASSERT_FALSE(svr.is_running());
  2882. });
  2883. svr.wait_until_ready();
  2884. {
  2885. Client cli(HOST, PORT);
  2886. auto res = cli.Get("/hi");
  2887. ASSERT_TRUE(res);
  2888. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2889. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2890. }
  2891. }
  2892. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2893. #ifdef CPPHTTPLIB_SSL_ENABLED
  2894. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2895. ASSERT_TRUE(svr.is_valid());
  2896. #else
  2897. Server svr;
  2898. #endif
  2899. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2900. if (req.path == "/routing_handler") {
  2901. res.set_header("PRE_ROUTING", "on");
  2902. res.set_content("Routing Handler", "text/plain");
  2903. return httplib::Server::HandlerResponse::Handled;
  2904. }
  2905. return httplib::Server::HandlerResponse::Unhandled;
  2906. });
  2907. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2908. res.set_content("Error", "text/html");
  2909. });
  2910. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2911. if (req.path == "/routing_handler") {
  2912. res.set_header("POST_ROUTING", "on");
  2913. }
  2914. });
  2915. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2916. res.set_content("Hello World!\n", "text/plain");
  2917. });
  2918. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2919. auto se = detail::scope_exit([&] {
  2920. svr.stop();
  2921. thread.join();
  2922. ASSERT_FALSE(svr.is_running());
  2923. });
  2924. svr.wait_until_ready();
  2925. {
  2926. #ifdef CPPHTTPLIB_SSL_ENABLED
  2927. SSLClient cli(HOST, PORT);
  2928. cli.enable_server_certificate_verification(false);
  2929. #else
  2930. Client cli(HOST, PORT);
  2931. #endif
  2932. auto res = cli.Get("/routing_handler");
  2933. ASSERT_TRUE(res);
  2934. EXPECT_EQ(StatusCode::OK_200, res->status);
  2935. EXPECT_EQ("Routing Handler", res->body);
  2936. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2937. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2938. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2939. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2940. }
  2941. {
  2942. #ifdef CPPHTTPLIB_SSL_ENABLED
  2943. SSLClient cli(HOST, PORT);
  2944. cli.enable_server_certificate_verification(false);
  2945. #else
  2946. Client cli(HOST, PORT);
  2947. #endif
  2948. auto res = cli.Get("/hi");
  2949. ASSERT_TRUE(res);
  2950. EXPECT_EQ(StatusCode::OK_200, res->status);
  2951. EXPECT_EQ("Hello World!\n", res->body);
  2952. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2953. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2954. }
  2955. {
  2956. #ifdef CPPHTTPLIB_SSL_ENABLED
  2957. SSLClient cli(HOST, PORT);
  2958. cli.enable_server_certificate_verification(false);
  2959. #else
  2960. Client cli(HOST, PORT);
  2961. #endif
  2962. auto res = cli.Get("/aaa");
  2963. ASSERT_TRUE(res);
  2964. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2965. EXPECT_EQ("Error", res->body);
  2966. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2967. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2968. }
  2969. }
  2970. TEST(RequestHandlerTest, PreRequestHandler) {
  2971. auto route_path = "/user/:user";
  2972. Server svr;
  2973. svr.Get("/hi", [](const Request &, Response &res) {
  2974. res.set_content("hi", "text/plain");
  2975. });
  2976. svr.Get(route_path, [](const Request &req, Response &res) {
  2977. res.set_content(req.path_params.at("user"), "text/plain");
  2978. });
  2979. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2980. if (req.matched_route == route_path) {
  2981. auto user = req.path_params.at("user");
  2982. if (user != "john") {
  2983. res.status = StatusCode::Forbidden_403;
  2984. res.set_content("error", "text/html");
  2985. return Server::HandlerResponse::Handled;
  2986. }
  2987. }
  2988. return Server::HandlerResponse::Unhandled;
  2989. });
  2990. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2991. auto se = detail::scope_exit([&] {
  2992. svr.stop();
  2993. thread.join();
  2994. ASSERT_FALSE(svr.is_running());
  2995. });
  2996. svr.wait_until_ready();
  2997. Client cli(HOST, PORT);
  2998. {
  2999. auto res = cli.Get("/hi");
  3000. ASSERT_TRUE(res);
  3001. EXPECT_EQ(StatusCode::OK_200, res->status);
  3002. EXPECT_EQ("hi", res->body);
  3003. }
  3004. {
  3005. auto res = cli.Get("/user/john");
  3006. ASSERT_TRUE(res);
  3007. EXPECT_EQ(StatusCode::OK_200, res->status);
  3008. EXPECT_EQ("john", res->body);
  3009. }
  3010. {
  3011. auto res = cli.Get("/user/invalid-user");
  3012. ASSERT_TRUE(res);
  3013. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  3014. EXPECT_EQ("error", res->body);
  3015. }
  3016. }
  3017. // The pre-request handler must run before the request body is read, so a
  3018. // rejected request never forces the server to buffer a (potentially large)
  3019. // body. Here the posted body is larger than the payload limit: if the body
  3020. // were read first the server would answer 413, but because the pre-request
  3021. // handler runs first it answers 403 and the body is never read.
  3022. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  3023. Server svr;
  3024. svr.set_payload_max_length(8);
  3025. auto handler_ran = false;
  3026. svr.Post("/reject", [&](const Request &req, Response &res) {
  3027. handler_ran = true;
  3028. res.set_content(req.body, "text/plain");
  3029. });
  3030. svr.Post("/accept", [](const Request &req, Response &res) {
  3031. res.set_content(req.body, "text/plain");
  3032. });
  3033. svr.set_pre_request_handler([](const Request &req, Response &res) {
  3034. if (req.matched_route == "/reject") {
  3035. res.status = StatusCode::Forbidden_403;
  3036. res.set_content("denied", "text/plain");
  3037. return Server::HandlerResponse::Handled;
  3038. }
  3039. return Server::HandlerResponse::Unhandled;
  3040. });
  3041. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3042. auto se = detail::scope_exit([&] {
  3043. svr.stop();
  3044. thread.join();
  3045. ASSERT_FALSE(svr.is_running());
  3046. });
  3047. svr.wait_until_ready();
  3048. Client cli(HOST, PORT);
  3049. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  3050. // rejects with 403 before the body is read, so 413 is never reached.
  3051. {
  3052. auto res = cli.Post("/reject", "0123456789", "text/plain");
  3053. ASSERT_TRUE(res);
  3054. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  3055. EXPECT_EQ("denied", res->body);
  3056. EXPECT_FALSE(handler_ran);
  3057. }
  3058. // An approved route still reads the body and enforces the payload limit.
  3059. {
  3060. auto res = cli.Post("/accept", "0123456789", "text/plain");
  3061. ASSERT_TRUE(res);
  3062. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  3063. }
  3064. }
  3065. TEST(UserDataTest, BasicOperations) {
  3066. httplib::UserData ud;
  3067. // Initially empty
  3068. EXPECT_FALSE(ud.has("key"));
  3069. EXPECT_EQ(nullptr, ud.get<int>("key"));
  3070. // set and get
  3071. ud.set("key", 42);
  3072. EXPECT_TRUE(ud.has("key"));
  3073. auto *p = ud.get<int>("key");
  3074. ASSERT_NE(nullptr, p);
  3075. EXPECT_EQ(42, *p);
  3076. // Type mismatch → nullptr
  3077. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  3078. // Overwrite with different type
  3079. ud.set("key", std::string("hello"));
  3080. EXPECT_EQ(nullptr, ud.get<int>("key"));
  3081. auto *s = ud.get<std::string>("key");
  3082. ASSERT_NE(nullptr, s);
  3083. EXPECT_EQ("hello", *s);
  3084. // erase
  3085. ud.erase("key");
  3086. EXPECT_FALSE(ud.has("key"));
  3087. // clear
  3088. ud.set("a", 1);
  3089. ud.set("b", 2);
  3090. ud.clear();
  3091. EXPECT_FALSE(ud.has("a"));
  3092. EXPECT_FALSE(ud.has("b"));
  3093. }
  3094. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  3095. struct AuthCtx {
  3096. std::string user_id;
  3097. };
  3098. Server svr;
  3099. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  3100. res.user_data.set("auth", AuthCtx{"alice"});
  3101. return Server::HandlerResponse::Unhandled;
  3102. });
  3103. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  3104. auto *ctx = res.user_data.get<AuthCtx>("auth");
  3105. ASSERT_NE(nullptr, ctx);
  3106. res.set_content("Hello " + ctx->user_id, "text/plain");
  3107. });
  3108. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3109. auto se = detail::scope_exit([&] {
  3110. svr.stop();
  3111. thread.join();
  3112. ASSERT_FALSE(svr.is_running());
  3113. });
  3114. svr.wait_until_ready();
  3115. Client cli(HOST, PORT);
  3116. auto res = cli.Get("/me");
  3117. ASSERT_TRUE(res);
  3118. EXPECT_EQ(StatusCode::OK_200, res->status);
  3119. EXPECT_EQ("Hello alice", res->body);
  3120. }
  3121. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  3122. struct RoleCtx {
  3123. std::string role;
  3124. };
  3125. Server svr;
  3126. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  3127. res.user_data.set("role", RoleCtx{"admin"});
  3128. return Server::HandlerResponse::Unhandled;
  3129. });
  3130. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  3131. auto *ctx = res.user_data.get<RoleCtx>("role");
  3132. ASSERT_NE(nullptr, ctx);
  3133. res.set_content(ctx->role, "text/plain");
  3134. });
  3135. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3136. auto se = detail::scope_exit([&] {
  3137. svr.stop();
  3138. thread.join();
  3139. ASSERT_FALSE(svr.is_running());
  3140. });
  3141. svr.wait_until_ready();
  3142. Client cli(HOST, PORT);
  3143. auto res = cli.Get("/role");
  3144. ASSERT_TRUE(res);
  3145. EXPECT_EQ(StatusCode::OK_200, res->status);
  3146. EXPECT_EQ("admin", res->body);
  3147. }
  3148. TEST(InvalidFormatTest, StatusCode) {
  3149. Server svr;
  3150. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3151. res.set_content("Hello World!\n", "text/plain");
  3152. res.status = 9999; // Status should be a three-digit code...
  3153. });
  3154. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3155. auto se = detail::scope_exit([&] {
  3156. svr.stop();
  3157. thread.join();
  3158. ASSERT_FALSE(svr.is_running());
  3159. });
  3160. svr.wait_until_ready();
  3161. {
  3162. Client cli(HOST, PORT);
  3163. auto res = cli.Get("/hi");
  3164. ASSERT_FALSE(res);
  3165. }
  3166. }
  3167. TEST(URLFragmentTest, WithFragment) {
  3168. Server svr;
  3169. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  3170. EXPECT_TRUE(req.target == "/hi");
  3171. });
  3172. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3173. auto se = detail::scope_exit([&] {
  3174. svr.stop();
  3175. thread.join();
  3176. ASSERT_FALSE(svr.is_running());
  3177. });
  3178. svr.wait_until_ready();
  3179. {
  3180. Client cli(HOST, PORT);
  3181. auto res = cli.Get("/hi#key1=val1=key2=val2");
  3182. EXPECT_TRUE(res);
  3183. EXPECT_EQ(StatusCode::OK_200, res->status);
  3184. res = cli.Get("/hi%23key1=val1=key2=val2");
  3185. EXPECT_TRUE(res);
  3186. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3187. }
  3188. }
  3189. TEST(HeaderWriter, SetHeaderWriter) {
  3190. Server svr;
  3191. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  3192. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  3193. return detail::write_headers(strm, hdrs);
  3194. });
  3195. svr.Get("/hi", [](const Request &req, Response &res) {
  3196. auto it = req.headers.find("CustomClientHeader");
  3197. EXPECT_TRUE(it != req.headers.end());
  3198. EXPECT_EQ(it->second, "CustomClientValue");
  3199. res.set_content("Hello World!\n", "text/plain");
  3200. });
  3201. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3202. auto se = detail::scope_exit([&] {
  3203. svr.stop();
  3204. thread.join();
  3205. ASSERT_FALSE(svr.is_running());
  3206. });
  3207. svr.wait_until_ready();
  3208. {
  3209. Client cli(HOST, PORT);
  3210. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  3211. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  3212. return detail::write_headers(strm, hdrs);
  3213. });
  3214. auto res = cli.Get("/hi");
  3215. EXPECT_TRUE(res);
  3216. EXPECT_EQ(StatusCode::OK_200, res->status);
  3217. auto it = res->headers.find("CustomServerHeader");
  3218. EXPECT_TRUE(it != res->headers.end());
  3219. EXPECT_EQ(it->second, "CustomServerValue");
  3220. }
  3221. }
  3222. class ServerTest : public ::testing::Test {
  3223. protected:
  3224. ServerTest()
  3225. : cli_(HOST, PORT)
  3226. #ifdef CPPHTTPLIB_SSL_ENABLED
  3227. ,
  3228. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  3229. #endif
  3230. {
  3231. #ifdef CPPHTTPLIB_SSL_ENABLED
  3232. cli_.enable_server_certificate_verification(false);
  3233. #endif
  3234. // Allow LARGE_DATA (100MB) responses
  3235. cli_.set_payload_max_length(200 * 1024 * 1024);
  3236. }
  3237. virtual void SetUp() {
  3238. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  3239. svr_.set_payload_max_length(200 * 1024 * 1024);
  3240. svr_.set_mount_point("/", "./www");
  3241. svr_.set_mount_point("/mount", "./www2");
  3242. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  3243. svr_.Get("/hi",
  3244. [&](const Request & /*req*/, Response &res) {
  3245. res.set_content("Hello World!", "text/plain");
  3246. })
  3247. .Get("/file_content",
  3248. [&](const Request & /*req*/, Response &res) {
  3249. res.set_file_content("./www/dir/test.html");
  3250. })
  3251. .Get("/file_content_with_content_type",
  3252. [&](const Request & /*req*/, Response &res) {
  3253. res.set_file_content("./www/file", "text/plain");
  3254. })
  3255. .Get("/invalid_file_content",
  3256. [&](const Request & /*req*/, Response &res) {
  3257. res.set_file_content("./www/dir/invalid_file_path");
  3258. })
  3259. .Get("/http_response_splitting",
  3260. [&](const Request & /*req*/, Response &res) {
  3261. res.set_header("a", "1\r\nSet-Cookie: a=1");
  3262. EXPECT_EQ(0U, res.headers.size());
  3263. EXPECT_FALSE(res.has_header("a"));
  3264. res.set_header("a", "1\nSet-Cookie: a=1");
  3265. EXPECT_EQ(0U, res.headers.size());
  3266. EXPECT_FALSE(res.has_header("a"));
  3267. res.set_header("a", "1\rSet-Cookie: a=1");
  3268. EXPECT_EQ(0U, res.headers.size());
  3269. EXPECT_FALSE(res.has_header("a"));
  3270. res.set_header("a\r\nb", "0");
  3271. EXPECT_EQ(0U, res.headers.size());
  3272. EXPECT_FALSE(res.has_header("a"));
  3273. res.set_header("a\rb", "0");
  3274. EXPECT_EQ(0U, res.headers.size());
  3275. EXPECT_FALSE(res.has_header("a"));
  3276. res.set_header("a\nb", "0");
  3277. EXPECT_EQ(0U, res.headers.size());
  3278. EXPECT_FALSE(res.has_header("a"));
  3279. res.set_redirect("1\r\nSet-Cookie: a=1");
  3280. EXPECT_EQ(0U, res.headers.size());
  3281. EXPECT_FALSE(res.has_header("Location"));
  3282. })
  3283. .Get("/slow",
  3284. [&](const Request & /*req*/, Response &res) {
  3285. std::this_thread::sleep_for(std::chrono::seconds(4));
  3286. res.set_content("slow", "text/plain");
  3287. })
  3288. #if 0
  3289. .Post("/slowpost",
  3290. [&](const Request & /*req*/, Response &res) {
  3291. std::this_thread::sleep_for(std::chrono::seconds(2));
  3292. res.set_content("slow", "text/plain");
  3293. })
  3294. #endif
  3295. .Get("/remote_addr",
  3296. [&](const Request &req, Response &res) {
  3297. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  3298. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  3299. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3300. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  3301. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  3302. #endif
  3303. res.set_content(req.remote_addr, "text/plain");
  3304. })
  3305. .Get("/local_addr",
  3306. [&](const Request &req, Response &res) {
  3307. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  3308. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  3309. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3310. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  3311. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  3312. #endif
  3313. auto local_addr = req.local_addr;
  3314. auto local_port = std::to_string(req.local_port);
  3315. res.set_content(local_addr.append(":").append(local_port),
  3316. "text/plain");
  3317. })
  3318. .Get("/endwith%",
  3319. [&](const Request & /*req*/, Response &res) {
  3320. res.set_content("Hello World!", "text/plain");
  3321. })
  3322. .Get("/a\\+\\+b",
  3323. [&](const Request &req, Response &res) {
  3324. ASSERT_TRUE(req.has_param("a +b"));
  3325. auto val = req.get_param_value("a +b");
  3326. res.set_content(val, "text/plain");
  3327. })
  3328. .Get("/", [&](const Request & /*req*/,
  3329. Response &res) { res.set_redirect("/hi"); })
  3330. .Post("/1",
  3331. [](const Request & /*req*/, Response &res) {
  3332. res.set_redirect("/2", StatusCode::SeeOther_303);
  3333. })
  3334. .Get("/2",
  3335. [](const Request & /*req*/, Response &res) {
  3336. res.set_content("redirected.", "text/plain");
  3337. res.status = StatusCode::OK_200;
  3338. })
  3339. .Post("/person",
  3340. [&](const Request &req, Response &res) {
  3341. if (req.has_param("name") && req.has_param("note")) {
  3342. persons_[req.get_param_value("name")] =
  3343. req.get_param_value("note");
  3344. } else {
  3345. res.status = StatusCode::BadRequest_400;
  3346. }
  3347. })
  3348. .Put("/person",
  3349. [&](const Request &req, Response &res) {
  3350. if (req.has_param("name") && req.has_param("note")) {
  3351. persons_[req.get_param_value("name")] =
  3352. req.get_param_value("note");
  3353. } else {
  3354. res.status = StatusCode::BadRequest_400;
  3355. }
  3356. })
  3357. .Get("/person/(.*)",
  3358. [&](const Request &req, Response &res) {
  3359. string name = req.matches[1];
  3360. if (persons_.find(name) != persons_.end()) {
  3361. auto note = persons_[name];
  3362. res.set_content(note, "text/plain");
  3363. } else {
  3364. res.status = StatusCode::NotFound_404;
  3365. }
  3366. })
  3367. .Delete("/person",
  3368. [&](const Request &req, Response &res) {
  3369. if (req.has_param("name")) {
  3370. string name = req.get_param_value("name");
  3371. if (persons_.find(name) != persons_.end()) {
  3372. persons_.erase(name);
  3373. res.set_content("DELETED", "text/plain");
  3374. } else {
  3375. res.status = StatusCode::NotFound_404;
  3376. }
  3377. } else {
  3378. res.status = StatusCode::BadRequest_400;
  3379. }
  3380. })
  3381. .Post("/x-www-form-urlencoded-json",
  3382. [&](const Request &req, Response &res) {
  3383. auto json = req.get_param_value("json");
  3384. ASSERT_EQ(JSON_DATA, json);
  3385. res.set_content(json, "appliation/json");
  3386. res.status = StatusCode::OK_200;
  3387. })
  3388. .Get("/streamed-chunked",
  3389. [&](const Request & /*req*/, Response &res) {
  3390. res.set_chunked_content_provider(
  3391. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  3392. sink.os << "123";
  3393. sink.os << "456";
  3394. sink.os << "789";
  3395. sink.done();
  3396. return true;
  3397. });
  3398. })
  3399. .Get("/streamed-chunked-with-prohibited-trailer",
  3400. [&](const Request & /*req*/, Response &res) {
  3401. auto i = new int(0);
  3402. // Declare both a prohibited trailer (Content-Length) and an
  3403. // allowed one
  3404. res.set_header("Trailer", "Content-Length, X-Allowed");
  3405. res.set_chunked_content_provider(
  3406. "text/plain",
  3407. [i](size_t /*offset*/, DataSink &sink) {
  3408. switch (*i) {
  3409. case 0: sink.os << "123"; break;
  3410. case 1: sink.os << "456"; break;
  3411. case 2: sink.os << "789"; break;
  3412. case 3: {
  3413. sink.done_with_trailer(
  3414. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  3415. } break;
  3416. }
  3417. (*i)++;
  3418. return true;
  3419. },
  3420. [i](bool success) {
  3421. EXPECT_TRUE(success);
  3422. delete i;
  3423. });
  3424. })
  3425. .Get("/streamed-chunked2",
  3426. [&](const Request & /*req*/, Response &res) {
  3427. auto i = new int(0);
  3428. res.set_chunked_content_provider(
  3429. "text/plain",
  3430. [i](size_t /*offset*/, DataSink &sink) {
  3431. switch (*i) {
  3432. case 0: sink.os << "123"; break;
  3433. case 1: sink.os << "456"; break;
  3434. case 2: sink.os << "789"; break;
  3435. case 3: sink.done(); break;
  3436. }
  3437. (*i)++;
  3438. return true;
  3439. },
  3440. [i](bool success) {
  3441. EXPECT_TRUE(success);
  3442. delete i;
  3443. });
  3444. })
  3445. .Get("/streamed-chunked-with-trailer",
  3446. [&](const Request & /*req*/, Response &res) {
  3447. auto i = new int(0);
  3448. res.set_header("Trailer", "Dummy1, Dummy2");
  3449. res.set_chunked_content_provider(
  3450. "text/plain",
  3451. [i](size_t /*offset*/, DataSink &sink) {
  3452. switch (*i) {
  3453. case 0: sink.os << "123"; break;
  3454. case 1: sink.os << "456"; break;
  3455. case 2: sink.os << "789"; break;
  3456. case 3: {
  3457. sink.done_with_trailer(
  3458. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  3459. } break;
  3460. }
  3461. (*i)++;
  3462. return true;
  3463. },
  3464. [i](bool success) {
  3465. EXPECT_TRUE(success);
  3466. delete i;
  3467. });
  3468. })
  3469. .Get("/streamed",
  3470. [&](const Request & /*req*/, Response &res) {
  3471. res.set_content_provider(
  3472. 6, "text/plain",
  3473. [](size_t offset, size_t /*length*/, DataSink &sink) {
  3474. sink.os << (offset < 3 ? "a" : "b");
  3475. return true;
  3476. });
  3477. })
  3478. .Get("/streamed-without-length",
  3479. [&](const Request & /*req*/, Response &res) {
  3480. auto data = new std::string("abcdefg");
  3481. res.set_content_provider(
  3482. "text/plain",
  3483. [data](size_t offset, DataSink &sink) {
  3484. if (offset < data->size()) {
  3485. sink.os << data->substr(offset);
  3486. }
  3487. sink.done();
  3488. return true;
  3489. },
  3490. [data](bool success) {
  3491. EXPECT_TRUE(success);
  3492. delete data;
  3493. });
  3494. })
  3495. .Get("/streamed-with-range",
  3496. [&](const Request &req, Response &res) {
  3497. auto data = new std::string("abcdefg");
  3498. res.set_content_provider(
  3499. data->size(), "text/plain",
  3500. [data](size_t offset, size_t length, DataSink &sink) {
  3501. size_t DATA_CHUNK_SIZE = 4;
  3502. const auto &d = *data;
  3503. auto out_len =
  3504. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  3505. auto ret =
  3506. sink.write(&d[static_cast<size_t>(offset)], out_len);
  3507. EXPECT_TRUE(ret);
  3508. return true;
  3509. },
  3510. [data, &req](bool success) {
  3511. EXPECT_EQ(success, !req.has_param("error"));
  3512. delete data;
  3513. });
  3514. })
  3515. .Get("/streamed-cancel",
  3516. [&](const Request & /*req*/, Response &res) {
  3517. res.set_content_provider(
  3518. size_t(-1), "text/plain",
  3519. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  3520. sink.os << "data_chunk";
  3521. return true;
  3522. });
  3523. })
  3524. .Get("/regex-with-delimiter",
  3525. [&](const Request &req, Response & /*res*/) {
  3526. ASSERT_TRUE(req.has_param("key"));
  3527. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  3528. })
  3529. .Get("/with-range",
  3530. [&](const Request & /*req*/, Response &res) {
  3531. res.set_content("abcdefg", "text/plain");
  3532. })
  3533. .Get("/test-start-time",
  3534. [&](const Request &req, Response & /*res*/) {
  3535. EXPECT_NE(req.start_time_,
  3536. std::chrono::steady_clock::time_point::min());
  3537. })
  3538. .Get("/with-range-customized-response",
  3539. [&](const Request & /*req*/, Response &res) {
  3540. res.status = StatusCode::BadRequest_400;
  3541. res.set_content(JSON_DATA, "application/json");
  3542. })
  3543. .Post("/chunked",
  3544. [&](const Request &req, Response & /*res*/) {
  3545. EXPECT_EQ(req.body, "dechunked post body");
  3546. })
  3547. .Post("/large-chunked",
  3548. [&](const Request &req, Response & /*res*/) {
  3549. std::string expected(6 * 30 * 1024u, 'a');
  3550. EXPECT_EQ(req.body, expected);
  3551. })
  3552. .Post("/multipart",
  3553. [&](const Request &req, Response & /*res*/) {
  3554. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  3555. req.form.get_field_count("text2") +
  3556. req.form.get_field_count("file3") +
  3557. req.form.get_field_count("file4"));
  3558. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  3559. req.form.get_file_count("file2"));
  3560. ASSERT_TRUE(!req.form.has_file("???"));
  3561. ASSERT_TRUE(!req.form.has_field("???"));
  3562. ASSERT_TRUE(req.body.empty());
  3563. {
  3564. const auto &text = req.form.get_field("text1");
  3565. EXPECT_EQ("text default", text);
  3566. }
  3567. {
  3568. const auto &text = req.form.get_field("text2");
  3569. EXPECT_EQ("aωb", text);
  3570. }
  3571. {
  3572. const auto &file = req.form.get_file("file1");
  3573. EXPECT_EQ("hello.txt", file.filename);
  3574. EXPECT_EQ("text/plain", file.content_type);
  3575. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3576. }
  3577. {
  3578. const auto &file = req.form.get_file("file2");
  3579. EXPECT_EQ("world.json", file.filename);
  3580. EXPECT_EQ("application/json", file.content_type);
  3581. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  3582. }
  3583. {
  3584. const auto &text = req.form.get_field("file3");
  3585. EXPECT_EQ(0u, text.size());
  3586. }
  3587. {
  3588. const auto &text = req.form.get_field("file4");
  3589. EXPECT_EQ(0u, text.size());
  3590. }
  3591. })
  3592. .Post("/multipart/multi_file_values",
  3593. [&](const Request &req, Response & /*res*/) {
  3594. EXPECT_EQ(3u, req.form.get_field_count("text") +
  3595. req.form.get_field_count("multi_text1"));
  3596. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  3597. ASSERT_TRUE(!req.form.has_file("???"));
  3598. ASSERT_TRUE(!req.form.has_field("???"));
  3599. ASSERT_TRUE(req.body.empty());
  3600. {
  3601. const auto &text = req.form.get_field("text");
  3602. EXPECT_EQ("default text", text);
  3603. }
  3604. {
  3605. const auto &text1_values = req.form.get_fields("multi_text1");
  3606. EXPECT_EQ(2u, text1_values.size());
  3607. EXPECT_EQ("aaaaa", text1_values[0]);
  3608. EXPECT_EQ("bbbbb", text1_values[1]);
  3609. }
  3610. {
  3611. const auto &file1_values = req.form.get_files("multi_file1");
  3612. EXPECT_EQ(2u, file1_values.size());
  3613. auto file1 = file1_values[0];
  3614. EXPECT_EQ(file1.filename, "hello.txt");
  3615. EXPECT_EQ(file1.content_type, "text/plain");
  3616. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  3617. auto file2 = file1_values[1];
  3618. EXPECT_EQ(file2.filename, "world.json");
  3619. EXPECT_EQ(file2.content_type, "application/json");
  3620. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  3621. }
  3622. })
  3623. .Post("/empty",
  3624. [&](const Request &req, Response &res) {
  3625. EXPECT_EQ(req.body, "");
  3626. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  3627. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3628. res.set_content("empty", "text/plain");
  3629. })
  3630. .Post("/empty-no-content-type",
  3631. [&](const Request &req, Response &res) {
  3632. EXPECT_EQ(req.body, "");
  3633. EXPECT_FALSE(req.has_header("Content-Type"));
  3634. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3635. res.set_content("empty-no-content-type", "text/plain");
  3636. })
  3637. .Post("/path-only",
  3638. [&](const Request &req, Response &res) {
  3639. EXPECT_EQ(req.body, "");
  3640. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3641. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3642. res.set_content("path-only", "text/plain");
  3643. })
  3644. .Post("/path-headers-only",
  3645. [&](const Request &req, Response &res) {
  3646. EXPECT_EQ(req.body, "");
  3647. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3648. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3649. EXPECT_EQ("world", req.get_header_value("hello"));
  3650. EXPECT_EQ("world2", req.get_header_value("hello2"));
  3651. res.set_content("path-headers-only", "text/plain");
  3652. })
  3653. .Post("/post-large",
  3654. [&](const Request &req, Response &res) {
  3655. EXPECT_EQ(req.body, LARGE_DATA);
  3656. res.set_content(req.body, "text/plain");
  3657. })
  3658. .Post("/post-loopback",
  3659. [&](const Request &, Response &res,
  3660. ContentReader const &content_reader) {
  3661. std::string body;
  3662. content_reader([&](const char *data, size_t data_length) {
  3663. body.append(data, data_length);
  3664. return true;
  3665. });
  3666. res.set_content(body, "text/plain");
  3667. })
  3668. .Put("/put-loopback",
  3669. [&](const Request &, Response &res,
  3670. ContentReader const &content_reader) {
  3671. std::string body;
  3672. content_reader([&](const char *data, size_t data_length) {
  3673. body.append(data, data_length);
  3674. return true;
  3675. });
  3676. res.set_content(body, "text/plain");
  3677. })
  3678. .Patch("/patch-loopback",
  3679. [&](const Request &, Response &res,
  3680. ContentReader const &content_reader) {
  3681. std::string body;
  3682. content_reader([&](const char *data, size_t data_length) {
  3683. body.append(data, data_length);
  3684. return true;
  3685. });
  3686. res.set_content(body, "text/plain");
  3687. })
  3688. .Put("/empty-no-content-type",
  3689. [&](const Request &req, Response &res) {
  3690. EXPECT_EQ(req.body, "");
  3691. EXPECT_FALSE(req.has_header("Content-Type"));
  3692. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3693. res.set_content("empty-no-content-type", "text/plain");
  3694. })
  3695. .Put("/put",
  3696. [&](const Request &req, Response &res) {
  3697. EXPECT_EQ(req.body, "PUT");
  3698. res.set_content(req.body, "text/plain");
  3699. })
  3700. .Put("/put-large",
  3701. [&](const Request &req, Response &res) {
  3702. EXPECT_EQ(req.body, LARGE_DATA);
  3703. res.set_content(req.body, "text/plain");
  3704. })
  3705. .Patch("/patch",
  3706. [&](const Request &req, Response &res) {
  3707. EXPECT_EQ(req.body, "PATCH");
  3708. res.set_content(req.body, "text/plain");
  3709. })
  3710. .Delete("/delete",
  3711. [&](const Request & /*req*/, Response &res) {
  3712. res.set_content("DELETE", "text/plain");
  3713. })
  3714. .Delete("/delete-body",
  3715. [&](const Request &req, Response &res) {
  3716. EXPECT_EQ(req.body, "content");
  3717. res.set_content(req.body, "text/plain");
  3718. })
  3719. .Options(R"(\*)",
  3720. [&](const Request & /*req*/, Response &res) {
  3721. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  3722. })
  3723. .Get("/request-target",
  3724. [&](const Request &req, Response & /*res*/) {
  3725. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  3726. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  3727. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  3728. })
  3729. .Get("/long-query-value",
  3730. [&](const Request &req, Response & /*res*/) {
  3731. EXPECT_EQ(LONG_QUERY_URL, req.target);
  3732. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  3733. })
  3734. .Get("/too-long-query-value",
  3735. [&](const Request &req, Response & /*res*/) {
  3736. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  3737. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  3738. })
  3739. .Get("/array-param",
  3740. [&](const Request &req, Response & /*res*/) {
  3741. EXPECT_EQ(3u, req.get_param_value_count("array"));
  3742. EXPECT_EQ("value1", req.get_param_value("array", 0));
  3743. EXPECT_EQ("value2", req.get_param_value("array", 1));
  3744. EXPECT_EQ("value3", req.get_param_value("array", 2));
  3745. })
  3746. .Get("/array-param-values",
  3747. [&](const Request &req, Response & /*res*/) {
  3748. auto values = req.get_param_values("array");
  3749. EXPECT_EQ(3u, values.size());
  3750. EXPECT_EQ("value1", values[0]);
  3751. EXPECT_EQ("value2", values[1]);
  3752. EXPECT_EQ("value3", values[2]);
  3753. auto empty = req.get_param_values("nonexistent");
  3754. EXPECT_TRUE(empty.empty());
  3755. })
  3756. .Post("/validate-no-multiple-headers",
  3757. [&](const Request &req, Response & /*res*/) {
  3758. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  3759. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  3760. })
  3761. .Post("/content_receiver",
  3762. [&](const Request &req, Response &res,
  3763. const ContentReader &content_reader) {
  3764. if (req.is_multipart_form_data()) {
  3765. std::vector<FormData> items;
  3766. content_reader(
  3767. [&](const FormData &file) {
  3768. items.push_back(file);
  3769. return true;
  3770. },
  3771. [&](const char *data, size_t data_length) {
  3772. items.back().content.append(data, data_length);
  3773. return true;
  3774. });
  3775. EXPECT_EQ(5u, items.size());
  3776. {
  3777. const auto &file = get_file_value(items, "text1");
  3778. EXPECT_TRUE(file.filename.empty());
  3779. EXPECT_EQ("text default", file.content);
  3780. }
  3781. {
  3782. const auto &file = get_file_value(items, "text2");
  3783. EXPECT_TRUE(file.filename.empty());
  3784. EXPECT_EQ("aωb", file.content);
  3785. }
  3786. {
  3787. const auto &file = get_file_value(items, "file1");
  3788. EXPECT_EQ("hello.txt", file.filename);
  3789. EXPECT_EQ("text/plain", file.content_type);
  3790. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3791. }
  3792. {
  3793. const auto &file = get_file_value(items, "file2");
  3794. EXPECT_EQ("world.json", file.filename);
  3795. EXPECT_EQ("application/json", file.content_type);
  3796. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  3797. }
  3798. {
  3799. const auto &file = get_file_value(items, "file3");
  3800. EXPECT_TRUE(file.filename.empty());
  3801. EXPECT_EQ("application/octet-stream", file.content_type);
  3802. EXPECT_EQ(0u, file.content.size());
  3803. }
  3804. } else {
  3805. std::string body;
  3806. content_reader([&](const char *data, size_t data_length) {
  3807. EXPECT_EQ(7U, data_length);
  3808. body.append(data, data_length);
  3809. return true;
  3810. });
  3811. EXPECT_EQ(body, "content");
  3812. res.set_content(body, "text/plain");
  3813. }
  3814. })
  3815. .Put("/content_receiver",
  3816. [&](const Request & /*req*/, Response &res,
  3817. const ContentReader &content_reader) {
  3818. std::string body;
  3819. content_reader([&](const char *data, size_t data_length) {
  3820. body.append(data, data_length);
  3821. return true;
  3822. });
  3823. EXPECT_EQ(body, "content");
  3824. res.set_content(body, "text/plain");
  3825. })
  3826. .Patch("/content_receiver",
  3827. [&](const Request & /*req*/, Response &res,
  3828. const ContentReader &content_reader) {
  3829. std::string body;
  3830. content_reader([&](const char *data, size_t data_length) {
  3831. body.append(data, data_length);
  3832. return true;
  3833. });
  3834. EXPECT_EQ(body, "content");
  3835. res.set_content(body, "text/plain");
  3836. })
  3837. .Post("/query-string-and-body",
  3838. [&](const Request &req, Response & /*res*/) {
  3839. ASSERT_TRUE(req.has_param("key"));
  3840. EXPECT_EQ(req.get_param_value("key"), "value");
  3841. EXPECT_EQ(req.body, "content");
  3842. })
  3843. .Get("/last-request",
  3844. [&](const Request &req, Response & /*res*/) {
  3845. EXPECT_EQ("close", req.get_header_value("Connection"));
  3846. })
  3847. .Get(R"(/redirect/(\d+))",
  3848. [&](const Request &req, Response &res) {
  3849. auto num = std::stoi(req.matches[1]) + 1;
  3850. std::string url = "/redirect/" + std::to_string(num);
  3851. res.set_redirect(url);
  3852. })
  3853. .Post("/binary",
  3854. [&](const Request &req, Response &res) {
  3855. EXPECT_EQ(4U, req.body.size());
  3856. EXPECT_EQ("application/octet-stream",
  3857. req.get_header_value("Content-Type"));
  3858. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3859. res.set_content(req.body, "application/octet-stream");
  3860. })
  3861. .Put("/binary",
  3862. [&](const Request &req, Response &res) {
  3863. EXPECT_EQ(4U, req.body.size());
  3864. EXPECT_EQ("application/octet-stream",
  3865. req.get_header_value("Content-Type"));
  3866. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3867. res.set_content(req.body, "application/octet-stream");
  3868. })
  3869. .Patch("/binary",
  3870. [&](const Request &req, Response &res) {
  3871. EXPECT_EQ(4U, req.body.size());
  3872. EXPECT_EQ("application/octet-stream",
  3873. req.get_header_value("Content-Type"));
  3874. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3875. res.set_content(req.body, "application/octet-stream");
  3876. })
  3877. .Delete("/binary",
  3878. [&](const Request &req, Response &res) {
  3879. EXPECT_EQ(4U, req.body.size());
  3880. EXPECT_EQ("application/octet-stream",
  3881. req.get_header_value("Content-Type"));
  3882. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3883. res.set_content(req.body, "application/octet-stream");
  3884. })
  3885. .Get("/issue1772",
  3886. [&](const Request & /*req*/, Response &res) {
  3887. res.status = 401;
  3888. res.set_header("WWW-Authenticate", "Basic realm=123456");
  3889. })
  3890. .Delete("/issue609",
  3891. [](const httplib::Request &, httplib::Response &res,
  3892. const httplib::ContentReader &) {
  3893. res.set_content("ok", "text/plain");
  3894. })
  3895. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  3896. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  3897. .Get("/compress",
  3898. [&](const Request & /*req*/, Response &res) {
  3899. res.set_content(
  3900. "12345678901234567890123456789012345678901234567890123456789"
  3901. "01234567890123456789012345678901234567890",
  3902. "text/plain");
  3903. })
  3904. .Get("/compress-with-charset",
  3905. [&](const Request & /*req*/, Response &res) {
  3906. res.set_content(
  3907. "12345678901234567890123456789012345678901234567890123456789"
  3908. "01234567890123456789012345678901234567890",
  3909. "application/json; charset=utf-8");
  3910. })
  3911. .Get("/nocompress",
  3912. [&](const Request & /*req*/, Response &res) {
  3913. res.set_content(
  3914. "12345678901234567890123456789012345678901234567890123456789"
  3915. "01234567890123456789012345678901234567890",
  3916. "application/octet-stream");
  3917. })
  3918. .Post("/compress-multipart",
  3919. [&](const Request &req, Response & /*res*/) {
  3920. EXPECT_EQ(2u, req.form.fields.size());
  3921. ASSERT_TRUE(!req.form.has_field("???"));
  3922. {
  3923. const auto &text = req.form.get_field("key1");
  3924. EXPECT_EQ("test", text);
  3925. }
  3926. {
  3927. const auto &text = req.form.get_field("key2");
  3928. EXPECT_EQ("--abcdefg123", text);
  3929. }
  3930. })
  3931. #endif
  3932. ;
  3933. persons_["john"] = "programmer";
  3934. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3935. svr_.wait_until_ready();
  3936. }
  3937. virtual void TearDown() {
  3938. svr_.stop();
  3939. if (!request_threads_.empty()) {
  3940. std::this_thread::sleep_for(std::chrono::seconds(1));
  3941. for (auto &t : request_threads_) {
  3942. t.join();
  3943. }
  3944. }
  3945. t_.join();
  3946. }
  3947. map<string, string> persons_;
  3948. #ifdef CPPHTTPLIB_SSL_ENABLED
  3949. SSLClient cli_;
  3950. SSLServer svr_;
  3951. #else
  3952. Client cli_;
  3953. Server svr_;
  3954. #endif
  3955. thread t_;
  3956. std::vector<thread> request_threads_;
  3957. };
  3958. TEST_F(ServerTest, GetMethod200) {
  3959. auto res = cli_.Get("/hi");
  3960. ASSERT_TRUE(res);
  3961. EXPECT_EQ("HTTP/1.1", res->version);
  3962. EXPECT_EQ(StatusCode::OK_200, res->status);
  3963. EXPECT_EQ("OK", res->reason);
  3964. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3965. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3966. EXPECT_EQ("Hello World!", res->body);
  3967. }
  3968. TEST_F(ServerTest, GetEmptyFile) {
  3969. auto res = cli_.Get("/empty_file");
  3970. ASSERT_TRUE(res);
  3971. EXPECT_EQ(StatusCode::OK_200, res->status);
  3972. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3973. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  3974. EXPECT_EQ("", res->body);
  3975. }
  3976. TEST_F(ServerTest, GetFileContent) {
  3977. auto res = cli_.Get("/file_content");
  3978. ASSERT_TRUE(res);
  3979. EXPECT_EQ(StatusCode::OK_200, res->status);
  3980. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3981. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  3982. EXPECT_EQ("test.html", res->body);
  3983. }
  3984. TEST_F(ServerTest, GetFileContentWithRange) {
  3985. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  3986. ASSERT_TRUE(res);
  3987. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3988. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3989. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  3990. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  3991. EXPECT_EQ("est", res->body);
  3992. }
  3993. TEST_F(ServerTest, GetFileContentWithContentType) {
  3994. auto res = cli_.Get("/file_content_with_content_type");
  3995. ASSERT_TRUE(res);
  3996. EXPECT_EQ(StatusCode::OK_200, res->status);
  3997. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3998. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  3999. EXPECT_EQ("file\n", res->body);
  4000. }
  4001. TEST_F(ServerTest, GetInvalidFileContent) {
  4002. auto res = cli_.Get("/invalid_file_content");
  4003. ASSERT_TRUE(res);
  4004. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4005. }
  4006. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  4007. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  4008. ASSERT_TRUE(res);
  4009. EXPECT_EQ("HTTP/1.1", res->version);
  4010. EXPECT_EQ(StatusCode::OK_200, res->status);
  4011. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4012. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  4013. EXPECT_EQ("Hello World!", res->body);
  4014. }
  4015. TEST_F(ServerTest, GetMethod302) {
  4016. auto res = cli_.Get("/");
  4017. ASSERT_TRUE(res);
  4018. EXPECT_EQ(StatusCode::Found_302, res->status);
  4019. EXPECT_EQ("/hi", res->get_header_value("Location"));
  4020. }
  4021. TEST_F(ServerTest, GetMethod302Redirect) {
  4022. cli_.set_follow_location(true);
  4023. auto res = cli_.Get("/");
  4024. ASSERT_TRUE(res);
  4025. EXPECT_EQ(StatusCode::OK_200, res->status);
  4026. EXPECT_EQ("Hello World!", res->body);
  4027. EXPECT_EQ("/hi", res->location);
  4028. }
  4029. TEST_F(ServerTest, GetMethod404) {
  4030. auto res = cli_.Get("/invalid");
  4031. ASSERT_TRUE(res);
  4032. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4033. }
  4034. TEST_F(ServerTest, HeadMethod200) {
  4035. auto res = cli_.Head("/hi");
  4036. ASSERT_TRUE(res);
  4037. EXPECT_EQ(StatusCode::OK_200, res->status);
  4038. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4039. EXPECT_TRUE(res->body.empty());
  4040. }
  4041. TEST_F(ServerTest, HeadMethod200Static) {
  4042. auto res = cli_.Head("/mount/dir/index.html");
  4043. ASSERT_TRUE(res);
  4044. EXPECT_EQ(StatusCode::OK_200, res->status);
  4045. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4046. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  4047. EXPECT_TRUE(res->body.empty());
  4048. }
  4049. TEST_F(ServerTest, HeadMethod404) {
  4050. auto res = cli_.Head("/invalid");
  4051. ASSERT_TRUE(res);
  4052. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4053. EXPECT_TRUE(res->body.empty());
  4054. }
  4055. TEST_F(ServerTest, GetMethodPersonJohn) {
  4056. auto res = cli_.Get("/person/john");
  4057. ASSERT_TRUE(res);
  4058. EXPECT_EQ(StatusCode::OK_200, res->status);
  4059. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4060. EXPECT_EQ("programmer", res->body);
  4061. }
  4062. TEST_F(ServerTest, PostMethod1) {
  4063. auto res = cli_.Get("/person/john1");
  4064. ASSERT_TRUE(res);
  4065. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4066. res = cli_.Post("/person", "name=john1&note=coder",
  4067. "application/x-www-form-urlencoded");
  4068. ASSERT_TRUE(res);
  4069. ASSERT_EQ(StatusCode::OK_200, res->status);
  4070. res = cli_.Get("/person/john1");
  4071. ASSERT_TRUE(res);
  4072. ASSERT_EQ(StatusCode::OK_200, res->status);
  4073. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4074. ASSERT_EQ("coder", res->body);
  4075. }
  4076. TEST_F(ServerTest, PostMethod2) {
  4077. auto res = cli_.Get("/person/john2");
  4078. ASSERT_TRUE(res);
  4079. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4080. Params params;
  4081. params.emplace("name", "john2");
  4082. params.emplace("note", "coder");
  4083. res = cli_.Post("/person", params);
  4084. ASSERT_TRUE(res);
  4085. ASSERT_EQ(StatusCode::OK_200, res->status);
  4086. res = cli_.Get("/person/john2");
  4087. ASSERT_TRUE(res);
  4088. ASSERT_EQ(StatusCode::OK_200, res->status);
  4089. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4090. ASSERT_EQ("coder", res->body);
  4091. }
  4092. TEST_F(ServerTest, PutMethod3) {
  4093. auto res = cli_.Get("/person/john3");
  4094. ASSERT_TRUE(res);
  4095. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4096. Params params;
  4097. params.emplace("name", "john3");
  4098. params.emplace("note", "coder");
  4099. res = cli_.Put("/person", params);
  4100. ASSERT_TRUE(res);
  4101. ASSERT_EQ(StatusCode::OK_200, res->status);
  4102. res = cli_.Get("/person/john3");
  4103. ASSERT_TRUE(res);
  4104. ASSERT_EQ(StatusCode::OK_200, res->status);
  4105. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4106. ASSERT_EQ("coder", res->body);
  4107. }
  4108. TEST_F(ServerTest, DeleteMethod1) {
  4109. auto res = cli_.Get("/person/john4");
  4110. ASSERT_TRUE(res);
  4111. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4112. Params params;
  4113. params.emplace("name", "john4");
  4114. params.emplace("note", "coder");
  4115. res = cli_.Post("/person", params);
  4116. ASSERT_TRUE(res);
  4117. ASSERT_EQ(StatusCode::OK_200, res->status);
  4118. res = cli_.Get("/person/john4");
  4119. ASSERT_TRUE(res);
  4120. ASSERT_EQ(StatusCode::OK_200, res->status);
  4121. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4122. ASSERT_EQ("coder", res->body);
  4123. Params delete_params;
  4124. delete_params.emplace("name", "john4");
  4125. res = cli_.Delete("/person", delete_params);
  4126. ASSERT_TRUE(res);
  4127. ASSERT_EQ(StatusCode::OK_200, res->status);
  4128. ASSERT_EQ("DELETED", res->body);
  4129. res = cli_.Get("/person/john4");
  4130. ASSERT_TRUE(res);
  4131. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4132. }
  4133. TEST_F(ServerTest, DeleteMethod2) {
  4134. auto res = cli_.Get("/person/john5");
  4135. ASSERT_TRUE(res);
  4136. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4137. Params params;
  4138. params.emplace("name", "john5");
  4139. params.emplace("note", "developer");
  4140. res = cli_.Post("/person", params);
  4141. ASSERT_TRUE(res);
  4142. ASSERT_EQ(StatusCode::OK_200, res->status);
  4143. res = cli_.Get("/person/john5");
  4144. ASSERT_TRUE(res);
  4145. ASSERT_EQ(StatusCode::OK_200, res->status);
  4146. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4147. ASSERT_EQ("developer", res->body);
  4148. Params delete_params;
  4149. delete_params.emplace("name", "john5");
  4150. Headers headers;
  4151. headers.emplace("Custom-Header", "test-value");
  4152. res = cli_.Delete("/person", headers, delete_params);
  4153. ASSERT_TRUE(res);
  4154. ASSERT_EQ(StatusCode::OK_200, res->status);
  4155. ASSERT_EQ("DELETED", res->body);
  4156. res = cli_.Get("/person/john5");
  4157. ASSERT_TRUE(res);
  4158. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4159. }
  4160. TEST_F(ServerTest, DeleteMethod3) {
  4161. auto res = cli_.Get("/person/john6");
  4162. ASSERT_TRUE(res);
  4163. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4164. Params params;
  4165. params.emplace("name", "john6");
  4166. params.emplace("note", "tester");
  4167. res = cli_.Post("/person", params);
  4168. ASSERT_TRUE(res);
  4169. ASSERT_EQ(StatusCode::OK_200, res->status);
  4170. res = cli_.Get("/person/john6");
  4171. ASSERT_TRUE(res);
  4172. ASSERT_EQ(StatusCode::OK_200, res->status);
  4173. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4174. ASSERT_EQ("tester", res->body);
  4175. Params delete_params;
  4176. delete_params.emplace("name", "john6");
  4177. Headers headers;
  4178. headers.emplace("Custom-Header", "test-value");
  4179. res = cli_.Delete("/person", headers, delete_params, nullptr);
  4180. ASSERT_TRUE(res);
  4181. ASSERT_EQ(StatusCode::OK_200, res->status);
  4182. ASSERT_EQ("DELETED", res->body);
  4183. res = cli_.Get("/person/john6");
  4184. ASSERT_TRUE(res);
  4185. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4186. }
  4187. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  4188. Params params;
  4189. params.emplace("json", JSON_DATA);
  4190. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  4191. ASSERT_TRUE(res);
  4192. ASSERT_EQ(StatusCode::OK_200, res->status);
  4193. ASSERT_EQ(JSON_DATA, res->body);
  4194. }
  4195. TEST_F(ServerTest, PostEmptyContent) {
  4196. auto res = cli_.Post("/empty", "", "text/plain");
  4197. ASSERT_TRUE(res);
  4198. ASSERT_EQ(StatusCode::OK_200, res->status);
  4199. ASSERT_EQ("empty", res->body);
  4200. }
  4201. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  4202. auto res = cli_.Post("/empty-no-content-type");
  4203. ASSERT_TRUE(res);
  4204. ASSERT_EQ(StatusCode::OK_200, res->status);
  4205. ASSERT_EQ("empty-no-content-type", res->body);
  4206. }
  4207. TEST_F(ServerTest, PostPathOnly) {
  4208. auto res = cli_.Post("/path-only");
  4209. ASSERT_TRUE(res);
  4210. ASSERT_EQ(StatusCode::OK_200, res->status);
  4211. ASSERT_EQ("path-only", res->body);
  4212. }
  4213. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  4214. auto res = cli_.Post("/path-headers-only",
  4215. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  4216. ASSERT_TRUE(res);
  4217. ASSERT_EQ(StatusCode::OK_200, res->status);
  4218. ASSERT_EQ("path-headers-only", res->body);
  4219. }
  4220. TEST_F(ServerTest, PostLarge) {
  4221. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  4222. ASSERT_TRUE(res);
  4223. ASSERT_EQ(StatusCode::OK_200, res->status);
  4224. EXPECT_EQ(LARGE_DATA, res->body);
  4225. }
  4226. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  4227. auto res = cli_.Put("/empty-no-content-type");
  4228. ASSERT_TRUE(res);
  4229. ASSERT_EQ(StatusCode::OK_200, res->status);
  4230. ASSERT_EQ("empty-no-content-type", res->body);
  4231. }
  4232. TEST_F(ServerTest, GetMethodDir) {
  4233. auto res = cli_.Get("/dir/");
  4234. ASSERT_TRUE(res);
  4235. EXPECT_EQ(StatusCode::OK_200, res->status);
  4236. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4237. auto body = R"(<html>
  4238. <head>
  4239. </head>
  4240. <body>
  4241. <a href="/dir/test.html">Test</a>
  4242. <a href="/hi">hi</a>
  4243. </body>
  4244. </html>
  4245. )";
  4246. EXPECT_EQ(body, res->body);
  4247. }
  4248. TEST_F(ServerTest, GetMethodDirTest) {
  4249. auto res = cli_.Get("/dir/test.html");
  4250. ASSERT_TRUE(res);
  4251. EXPECT_EQ(StatusCode::OK_200, res->status);
  4252. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4253. EXPECT_EQ("test.html", res->body);
  4254. }
  4255. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  4256. auto res = cli_.Get("/dir/../dir/test.html");
  4257. ASSERT_TRUE(res);
  4258. EXPECT_EQ(StatusCode::OK_200, res->status);
  4259. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4260. EXPECT_EQ("test.html", res->body);
  4261. }
  4262. TEST_F(ServerTest, GetMethodInvalidPath) {
  4263. auto res = cli_.Get("/dir/../test.html");
  4264. ASSERT_TRUE(res);
  4265. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4266. }
  4267. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  4268. auto res = cli_.Get("/../www/dir/test.html");
  4269. ASSERT_TRUE(res);
  4270. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4271. }
  4272. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  4273. auto res = cli_.Get("/dir/../../www/dir/test.html");
  4274. ASSERT_TRUE(res);
  4275. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4276. }
  4277. TEST_F(ServerTest, GetMethodDirMountTest) {
  4278. auto res = cli_.Get("/mount/dir/test.html");
  4279. ASSERT_TRUE(res);
  4280. EXPECT_EQ(StatusCode::OK_200, res->status);
  4281. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4282. EXPECT_EQ("test.html", res->body);
  4283. }
  4284. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  4285. auto res = cli_.Get("/mount/dir/../dir/test.html");
  4286. ASSERT_TRUE(res);
  4287. EXPECT_EQ(StatusCode::OK_200, res->status);
  4288. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4289. EXPECT_EQ("test.html", res->body);
  4290. }
  4291. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  4292. auto res = cli_.Get("/mount/dir/../test.html");
  4293. ASSERT_TRUE(res);
  4294. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4295. }
  4296. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  4297. auto res = cli_.Get("/mount/dir/test.html%00.js");
  4298. ASSERT_TRUE(res);
  4299. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4300. }
  4301. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  4302. auto res = cli_.Get("/mount/../www2/dir/test.html");
  4303. ASSERT_TRUE(res);
  4304. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4305. }
  4306. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  4307. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  4308. ASSERT_TRUE(res);
  4309. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4310. }
  4311. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  4312. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  4313. ASSERT_TRUE(res);
  4314. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4315. }
  4316. TEST_F(ServerTest, PostMethod303) {
  4317. auto res = cli_.Post("/1", "body", "text/plain");
  4318. ASSERT_TRUE(res);
  4319. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  4320. EXPECT_EQ("/2", res->get_header_value("Location"));
  4321. }
  4322. TEST_F(ServerTest, PostMethod303Redirect) {
  4323. cli_.set_follow_location(true);
  4324. auto res = cli_.Post("/1", "body", "text/plain");
  4325. ASSERT_TRUE(res);
  4326. EXPECT_EQ(StatusCode::OK_200, res->status);
  4327. EXPECT_EQ("redirected.", res->body);
  4328. EXPECT_EQ("/2", res->location);
  4329. }
  4330. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  4331. auto res = cli_.Get("/dir/test.abcde");
  4332. ASSERT_TRUE(res);
  4333. EXPECT_EQ(StatusCode::OK_200, res->status);
  4334. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4335. EXPECT_EQ("abcde", res->body);
  4336. }
  4337. TEST_F(ServerTest, StaticFileRange) {
  4338. auto res =
  4339. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  4340. ASSERT_TRUE(res);
  4341. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4342. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4343. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4344. EXPECT_EQ(true, res->has_header("Content-Range"));
  4345. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  4346. EXPECT_EQ(std::string("cd"), res->body);
  4347. }
  4348. TEST_F(ServerTest, StaticFileRanges) {
  4349. auto res = cli_.Get("/dir/test.abcde",
  4350. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  4351. ASSERT_TRUE(res);
  4352. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4353. EXPECT_TRUE(
  4354. res->get_header_value("Content-Type")
  4355. .find(
  4356. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  4357. 0);
  4358. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  4359. }
  4360. TEST_F(ServerTest, StaticFileRangeHead) {
  4361. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  4362. ASSERT_TRUE(res);
  4363. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4364. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4365. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4366. EXPECT_EQ(true, res->has_header("Content-Range"));
  4367. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  4368. }
  4369. TEST_F(ServerTest, StaticFileRangeBigFile) {
  4370. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  4371. ASSERT_TRUE(res);
  4372. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4373. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4374. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  4375. EXPECT_EQ(true, res->has_header("Content-Range"));
  4376. EXPECT_EQ("bytes 1048571-1048575/1048576",
  4377. res->get_header_value("Content-Range"));
  4378. EXPECT_EQ("LAST\n", res->body);
  4379. }
  4380. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  4381. auto res =
  4382. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  4383. ASSERT_TRUE(res);
  4384. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4385. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4386. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  4387. EXPECT_EQ(true, res->has_header("Content-Range"));
  4388. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  4389. }
  4390. TEST_F(ServerTest, StaticFileBigFile) {
  4391. auto res = cli_.Get("/dir/1MB.txt");
  4392. ASSERT_TRUE(res);
  4393. EXPECT_EQ(StatusCode::OK_200, res->status);
  4394. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4395. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  4396. }
  4397. TEST_F(ServerTest, InvalidBaseDirMount) {
  4398. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  4399. }
  4400. TEST_F(ServerTest, Binary) {
  4401. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  4402. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  4403. "application/octet-stream");
  4404. ASSERT_TRUE(res);
  4405. ASSERT_EQ(StatusCode::OK_200, res->status);
  4406. ASSERT_EQ(4U, res->body.size());
  4407. res = cli_.Put("/binary", binary.data(), binary.size(),
  4408. "application/octet-stream");
  4409. ASSERT_TRUE(res);
  4410. ASSERT_EQ(StatusCode::OK_200, res->status);
  4411. ASSERT_EQ(4U, res->body.size());
  4412. res = cli_.Patch("/binary", binary.data(), binary.size(),
  4413. "application/octet-stream");
  4414. ASSERT_TRUE(res);
  4415. ASSERT_EQ(StatusCode::OK_200, res->status);
  4416. ASSERT_EQ(4U, res->body.size());
  4417. res = cli_.Delete("/binary", binary.data(), binary.size(),
  4418. "application/octet-stream");
  4419. ASSERT_TRUE(res);
  4420. ASSERT_EQ(StatusCode::OK_200, res->status);
  4421. ASSERT_EQ(4U, res->body.size());
  4422. }
  4423. TEST_F(ServerTest, BinaryString) {
  4424. auto binary = std::string("\x00\x01\x02\x03", 4);
  4425. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  4426. ASSERT_TRUE(res);
  4427. ASSERT_EQ(StatusCode::OK_200, res->status);
  4428. ASSERT_EQ(4U, res->body.size());
  4429. res = cli_.Put("/binary", binary, "application/octet-stream");
  4430. ASSERT_TRUE(res);
  4431. ASSERT_EQ(StatusCode::OK_200, res->status);
  4432. ASSERT_EQ(4U, res->body.size());
  4433. res = cli_.Patch("/binary", binary, "application/octet-stream");
  4434. ASSERT_TRUE(res);
  4435. ASSERT_EQ(StatusCode::OK_200, res->status);
  4436. ASSERT_EQ(4U, res->body.size());
  4437. res = cli_.Delete("/binary", binary, "application/octet-stream");
  4438. ASSERT_TRUE(res);
  4439. ASSERT_EQ(StatusCode::OK_200, res->status);
  4440. ASSERT_EQ(4U, res->body.size());
  4441. }
  4442. TEST_F(ServerTest, EmptyRequest) {
  4443. auto res = cli_.Get("");
  4444. ASSERT_TRUE(!res);
  4445. EXPECT_EQ(Error::Connection, res.error());
  4446. }
  4447. TEST_F(ServerTest, LongRequest) {
  4448. std::string request;
  4449. for (size_t i = 0; i < 545; i++) {
  4450. request += "/TooLongRequest";
  4451. }
  4452. request += "OK";
  4453. auto res = cli_.Get(request.c_str());
  4454. ASSERT_TRUE(res);
  4455. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4456. }
  4457. TEST_F(ServerTest, TooLongRequest) {
  4458. std::string request;
  4459. for (size_t i = 0; i < 546; i++) {
  4460. request += "/TooLongRequest";
  4461. }
  4462. request += "_NG";
  4463. auto start = std::chrono::high_resolution_clock::now();
  4464. cli_.set_keep_alive(true);
  4465. auto res = cli_.Get(request.c_str());
  4466. auto end = std::chrono::high_resolution_clock::now();
  4467. auto elapsed =
  4468. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  4469. .count();
  4470. ASSERT_TRUE(res);
  4471. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  4472. EXPECT_LE(elapsed, 1000);
  4473. EXPECT_EQ("close", res->get_header_value("Connection"));
  4474. EXPECT_FALSE(cli_.is_socket_open());
  4475. }
  4476. TEST_F(ServerTest, AlmostTooLongRequest) {
  4477. // test for #2046 - URI length check shouldn't include other content on req
  4478. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  4479. // leading /, space, HTTP/1.1)
  4480. std::string request =
  4481. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  4482. auto res = cli_.Get(request.c_str());
  4483. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4484. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4485. }
  4486. TEST_F(ServerTest, LongHeader) {
  4487. Request req;
  4488. req.method = "GET";
  4489. req.path = "/hi";
  4490. std::string host_and_port;
  4491. host_and_port += HOST;
  4492. host_and_port += ":";
  4493. host_and_port += std::to_string(PORT);
  4494. req.headers.emplace("Host", host_and_port.c_str());
  4495. req.headers.emplace("Accept", "*/*");
  4496. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4497. req.headers.emplace(
  4498. "Header-Name",
  4499. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4500. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4501. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4502. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4503. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4504. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4505. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4506. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4507. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4508. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4509. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4510. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4511. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4512. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4513. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4514. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4515. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4516. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4517. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4518. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4519. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4520. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4521. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4522. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4523. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4524. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4525. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4526. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4527. "@@@@@@@@@@@@@@@@");
  4528. auto res = std::make_shared<Response>();
  4529. auto error = Error::Success;
  4530. auto ret = cli_.send(req, *res, error);
  4531. ASSERT_TRUE(ret);
  4532. EXPECT_EQ(StatusCode::OK_200, res->status);
  4533. }
  4534. TEST_F(ServerTest, LongQueryValue) {
  4535. auto start = std::chrono::high_resolution_clock::now();
  4536. cli_.set_keep_alive(true);
  4537. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  4538. auto end = std::chrono::high_resolution_clock::now();
  4539. auto elapsed =
  4540. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  4541. .count();
  4542. ASSERT_TRUE(res);
  4543. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  4544. EXPECT_LE(elapsed, 1000);
  4545. EXPECT_EQ("close", res->get_header_value("Connection"));
  4546. EXPECT_FALSE(cli_.is_socket_open());
  4547. }
  4548. TEST_F(ServerTest, TooLongQueryValue) {
  4549. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  4550. ASSERT_FALSE(res);
  4551. EXPECT_EQ(Error::Read, res.error());
  4552. }
  4553. TEST_F(ServerTest, TooLongHeader) {
  4554. Request req;
  4555. req.method = "GET";
  4556. req.path = "/hi";
  4557. std::string host_and_port;
  4558. host_and_port += HOST;
  4559. host_and_port += ":";
  4560. host_and_port += std::to_string(PORT);
  4561. req.headers.emplace("Host", host_and_port.c_str());
  4562. req.headers.emplace("Accept", "*/*");
  4563. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4564. req.headers.emplace(
  4565. "Header-Name",
  4566. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4567. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4568. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4569. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4570. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4571. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4572. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4573. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4574. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4575. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4576. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4577. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4578. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4579. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4580. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4581. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4582. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4583. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4584. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4585. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4586. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4587. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4588. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4589. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4590. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4591. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4592. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4593. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4594. "@@@@@@@@@@@@@@@@@");
  4595. auto res = std::make_shared<Response>();
  4596. auto error = Error::Success;
  4597. auto ret = cli_.send(req, *res, error);
  4598. ASSERT_TRUE(ret);
  4599. EXPECT_EQ(StatusCode::OK_200, res->status);
  4600. }
  4601. TEST_F(ServerTest, HeaderCountAtLimit) {
  4602. // Test with headers just under the 100 limit
  4603. httplib::Headers headers;
  4604. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  4605. // This should keep us just under the 100 header limit
  4606. for (int i = 0; i < 95; i++) {
  4607. std::string name = "X-Test-Header-" + std::to_string(i);
  4608. std::string value = "value" + std::to_string(i);
  4609. headers.emplace(name, value);
  4610. }
  4611. // This should work fine as we're under the limit
  4612. auto res = cli_.Get("/hi", headers);
  4613. EXPECT_TRUE(res);
  4614. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  4615. }
  4616. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  4617. // Test with many headers to exceed the 100 limit
  4618. httplib::Headers headers;
  4619. // Add 150 headers to definitely exceed the 100 limit
  4620. for (int i = 0; i < 150; i++) {
  4621. std::string name = "X-Test-Header-" + std::to_string(i);
  4622. std::string value = "value" + std::to_string(i);
  4623. headers.emplace(name, value);
  4624. }
  4625. // This should fail due to exceeding header count limit
  4626. cli_.set_keep_alive(true);
  4627. auto res = cli_.Get("/hi", headers);
  4628. // The server should respond with 400 Bad Request
  4629. ASSERT_TRUE(res);
  4630. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4631. EXPECT_EQ("close", res->get_header_value("Connection"));
  4632. EXPECT_FALSE(cli_.is_socket_open());
  4633. }
  4634. TEST_F(ServerTest, PercentEncoding) {
  4635. auto res = cli_.Get("/e%6edwith%");
  4636. ASSERT_TRUE(res);
  4637. EXPECT_EQ(StatusCode::OK_200, res->status);
  4638. }
  4639. TEST_F(ServerTest, PercentEncodingUnicode) {
  4640. auto res = cli_.Get("/e%u006edwith%");
  4641. ASSERT_TRUE(res);
  4642. EXPECT_EQ(StatusCode::OK_200, res->status);
  4643. }
  4644. TEST_F(ServerTest, InvalidPercentEncoding) {
  4645. auto res = cli_.Get("/%endwith%");
  4646. ASSERT_TRUE(res);
  4647. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4648. }
  4649. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  4650. auto res = cli_.Get("/%uendwith%");
  4651. ASSERT_TRUE(res);
  4652. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4653. }
  4654. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  4655. auto res = cli_.Get("/hello?aaa=bbb%");
  4656. ASSERT_TRUE(res);
  4657. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4658. }
  4659. TEST_F(ServerTest, PlusSignEncoding) {
  4660. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  4661. ASSERT_TRUE(res);
  4662. EXPECT_EQ(StatusCode::OK_200, res->status);
  4663. EXPECT_EQ("a +b", res->body);
  4664. }
  4665. TEST_F(ServerTest, HeaderCountSecurityTest) {
  4666. // This test simulates a potential DoS attack using many headers
  4667. // to verify our security fix prevents memory exhaustion
  4668. httplib::Headers attack_headers;
  4669. // Attempt to add many headers like an attacker would (200 headers to far
  4670. // exceed limit)
  4671. for (int i = 0; i < 200; i++) {
  4672. std::string name = "X-Attack-Header-" + std::to_string(i);
  4673. std::string value = "attack_payload_" + std::to_string(i);
  4674. attack_headers.emplace(name, value);
  4675. }
  4676. // Try to POST with excessive headers
  4677. cli_.set_keep_alive(true);
  4678. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  4679. // Should either fail or return 400 Bad Request due to security limit
  4680. if (res) {
  4681. // If we get a response, it should be 400 Bad Request
  4682. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4683. EXPECT_EQ("close", res->get_header_value("Connection"));
  4684. }
  4685. EXPECT_FALSE(cli_.is_socket_open());
  4686. }
  4687. TEST_F(ServerTest, MultipartFormData) {
  4688. UploadFormDataItems items = {
  4689. {"text1", "text default", "", ""},
  4690. {"text2", "aωb", "", ""},
  4691. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4692. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  4693. {"file3", "", "", "application/octet-stream"},
  4694. {"file4", "", "", " application/json tmp-string "}};
  4695. auto res = cli_.Post("/multipart", items);
  4696. ASSERT_TRUE(res);
  4697. EXPECT_EQ(StatusCode::OK_200, res->status);
  4698. }
  4699. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  4700. UploadFormDataItems items = {
  4701. {"text", "default text", "", ""},
  4702. {"multi_text1", "aaaaa", "", ""},
  4703. {"multi_text1", "bbbbb", "", ""},
  4704. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4705. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  4706. "application/json"},
  4707. };
  4708. auto res = cli_.Post("/multipart/multi_file_values", items);
  4709. ASSERT_TRUE(res);
  4710. EXPECT_EQ(StatusCode::OK_200, res->status);
  4711. }
  4712. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  4713. auto res = cli_.Get("/hi");
  4714. ASSERT_TRUE(res);
  4715. EXPECT_EQ(StatusCode::OK_200, res->status);
  4716. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  4717. EXPECT_EQ("Hello World!", res->body);
  4718. }
  4719. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  4720. Request req;
  4721. req.method = "POST";
  4722. req.path = "/chunked";
  4723. std::string host_and_port;
  4724. host_and_port += HOST;
  4725. host_and_port += ":";
  4726. host_and_port += std::to_string(PORT);
  4727. req.headers.emplace("Host", host_and_port.c_str());
  4728. req.headers.emplace("Accept", "*/*");
  4729. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4730. req.headers.emplace("Content-Type", "text/plain");
  4731. req.headers.emplace("Content-Length", "0");
  4732. req.headers.emplace(
  4733. "Transfer-Encoding",
  4734. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  4735. // Client does not chunk, so make a chunked body manually.
  4736. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  4737. auto res = std::make_shared<Response>();
  4738. auto error = Error::Success;
  4739. auto ret = cli_.send(req, *res, error);
  4740. ASSERT_TRUE(ret);
  4741. EXPECT_EQ(StatusCode::OK_200, res->status);
  4742. }
  4743. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  4744. // rather than treat them as valid lengths.
  4745. template <typename ClientT>
  4746. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  4747. Request req;
  4748. req.method = "POST";
  4749. req.path = "/chunked";
  4750. std::string host_and_port;
  4751. host_and_port += HOST;
  4752. host_and_port += ":";
  4753. host_and_port += std::to_string(PORT);
  4754. req.headers.emplace("Host", host_and_port.c_str());
  4755. req.headers.emplace("Content-Length", "0");
  4756. req.headers.emplace("Transfer-Encoding", "chunked");
  4757. req.body = body;
  4758. auto res = std::make_shared<Response>();
  4759. auto error = Error::Success;
  4760. ASSERT_TRUE(cli.send(req, *res, error));
  4761. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4762. }
  4763. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  4764. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  4765. }
  4766. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  4767. expect_chunked_body_rejected(
  4768. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  4769. }
  4770. TEST_F(ServerTest, GetStreamed2) {
  4771. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  4772. ASSERT_TRUE(res);
  4773. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4774. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4775. EXPECT_EQ(true, res->has_header("Content-Range"));
  4776. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  4777. EXPECT_EQ(std::string("ab"), res->body);
  4778. }
  4779. TEST_F(ServerTest, GetStreamed) {
  4780. auto res = cli_.Get("/streamed");
  4781. ASSERT_TRUE(res);
  4782. EXPECT_EQ(StatusCode::OK_200, res->status);
  4783. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4784. EXPECT_EQ(std::string("aaabbb"), res->body);
  4785. }
  4786. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  4787. auto res = cli_.Get("/streamed-without-length",
  4788. Headers{make_range_header({{0, -1}})});
  4789. ASSERT_TRUE(res);
  4790. EXPECT_EQ(StatusCode::OK_200, res->status);
  4791. EXPECT_EQ(false, res->has_header("Content-Length"));
  4792. EXPECT_EQ(false, res->has_header("Content-Range"));
  4793. EXPECT_EQ(std::string("abcdefg"), res->body);
  4794. }
  4795. TEST_F(ServerTest, GetStreamedWithRange1) {
  4796. auto res =
  4797. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  4798. ASSERT_TRUE(res);
  4799. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4800. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4801. EXPECT_EQ(true, res->has_header("Content-Range"));
  4802. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4803. EXPECT_EQ(std::string("def"), res->body);
  4804. }
  4805. TEST_F(ServerTest, GetStreamedWithRange2) {
  4806. auto res =
  4807. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  4808. ASSERT_TRUE(res);
  4809. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4810. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4811. EXPECT_EQ(true, res->has_header("Content-Range"));
  4812. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4813. EXPECT_EQ(std::string("bcdefg"), res->body);
  4814. }
  4815. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  4816. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  4817. ASSERT_TRUE(res);
  4818. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4819. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4820. EXPECT_EQ(true, res->has_header("Content-Range"));
  4821. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  4822. EXPECT_EQ(std::string("efg"), res->body);
  4823. }
  4824. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  4825. auto res =
  4826. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-9999"}});
  4827. ASSERT_TRUE(res);
  4828. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4829. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4830. EXPECT_EQ(false, res->has_header("Content-Range"));
  4831. EXPECT_EQ(0U, res->body.size());
  4832. }
  4833. TEST_F(ServerTest, GetStreamedWithRangeError) {
  4834. auto res =
  4835. cli_.Get("/streamed-with-range",
  4836. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  4837. "92233720368547758079223372036854775807"}});
  4838. ASSERT_TRUE(res);
  4839. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4840. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4841. EXPECT_EQ(false, res->has_header("Content-Range"));
  4842. EXPECT_EQ(0U, res->body.size());
  4843. }
  4844. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  4845. auto res = cli_.Get(
  4846. "/with-range",
  4847. Headers{{"Range",
  4848. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  4849. {"Accept-Encoding", ""}});
  4850. ASSERT_TRUE(res);
  4851. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4852. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4853. EXPECT_EQ(true, res->has_header("Content-Range"));
  4854. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4855. EXPECT_EQ(std::string("abcdefg"), res->body);
  4856. }
  4857. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  4858. auto res = cli_.Get("/with-range", Headers{
  4859. {"Range", "bytes=0-"},
  4860. {"Accept-Encoding", ""},
  4861. });
  4862. ASSERT_TRUE(res);
  4863. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4864. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4865. EXPECT_EQ(true, res->has_header("Content-Range"));
  4866. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4867. EXPECT_EQ(std::string("abcdefg"), res->body);
  4868. }
  4869. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  4870. auto res = cli_.Get("/streamed-with-range",
  4871. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  4872. ASSERT_TRUE(res);
  4873. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4874. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4875. EXPECT_EQ(false, res->has_header("Content-Range"));
  4876. EXPECT_EQ(267U, res->body.size());
  4877. // Check that both range contents are present
  4878. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  4879. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4880. // Check that Content-Range headers are present for both ranges
  4881. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  4882. std::string::npos);
  4883. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4884. std::string::npos);
  4885. }
  4886. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  4887. Ranges ranges;
  4888. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  4889. ranges.emplace_back(0, -1);
  4890. }
  4891. auto res = cli_.Get("/streamed-with-range?error",
  4892. Headers{{make_range_header(ranges)}});
  4893. ASSERT_TRUE(res);
  4894. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4895. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4896. EXPECT_EQ(false, res->has_header("Content-Range"));
  4897. EXPECT_EQ(0U, res->body.size());
  4898. }
  4899. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  4900. auto res = cli_.Get("/streamed-with-range",
  4901. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  4902. ASSERT_TRUE(res);
  4903. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4904. EXPECT_EQ(5U, res->body.size());
  4905. // Check that overlapping ranges are coalesced into a single range
  4906. EXPECT_EQ("bcdef", res->body);
  4907. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  4908. // Should be single range, not multipart
  4909. EXPECT_TRUE(res->has_header("Content-Range"));
  4910. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4911. }
  4912. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  4913. auto res = cli_.Get("/streamed-with-range",
  4914. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  4915. ASSERT_TRUE(res);
  4916. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4917. EXPECT_EQ(268U, res->body.size());
  4918. // Check that both range contents are present
  4919. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4920. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  4921. // Check that Content-Range headers are present for both ranges
  4922. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4923. std::string::npos);
  4924. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  4925. std::string::npos);
  4926. }
  4927. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  4928. auto res = cli_.Get("/streamed-with-range",
  4929. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  4930. ASSERT_TRUE(res);
  4931. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4932. EXPECT_EQ(269U, res->body.size());
  4933. // Check that both duplicate range contents are present
  4934. size_t first_abc = res->body.find("abc\r\n");
  4935. EXPECT_TRUE(first_abc != std::string::npos);
  4936. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  4937. EXPECT_TRUE(second_abc != std::string::npos);
  4938. // Check that Content-Range headers are present for both ranges
  4939. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  4940. EXPECT_TRUE(first_range != std::string::npos);
  4941. size_t second_range =
  4942. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  4943. EXPECT_TRUE(second_range != std::string::npos);
  4944. }
  4945. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  4946. auto res =
  4947. cli_.Get("/streamed-with-range?error",
  4948. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  4949. ASSERT_TRUE(res);
  4950. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4951. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4952. EXPECT_EQ(false, res->has_header("Content-Range"));
  4953. EXPECT_EQ(0U, res->body.size());
  4954. }
  4955. TEST_F(ServerTest, GetStreamedEndless) {
  4956. uint64_t offset = 0;
  4957. auto res = cli_.Get("/streamed-cancel",
  4958. [&](const char * /*data*/, uint64_t data_length) {
  4959. if (offset < 100) {
  4960. offset += data_length;
  4961. return true;
  4962. }
  4963. return false;
  4964. });
  4965. ASSERT_TRUE(!res);
  4966. EXPECT_EQ(Error::Canceled, res.error());
  4967. }
  4968. TEST_F(ServerTest, ClientStop) {
  4969. std::atomic_size_t count{4};
  4970. std::vector<std::thread> threads;
  4971. for (auto i = count.load(); i != 0; --i) {
  4972. threads.emplace_back([&]() {
  4973. auto res = cli_.Get("/streamed-cancel",
  4974. [&](const char *, uint64_t) { return true; });
  4975. --count;
  4976. ASSERT_TRUE(!res);
  4977. EXPECT_TRUE(res.error() == Error::Canceled ||
  4978. res.error() == Error::Read || res.error() == Error::Write);
  4979. });
  4980. }
  4981. std::this_thread::sleep_for(std::chrono::seconds(2));
  4982. while (count != 0) {
  4983. cli_.stop();
  4984. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4985. }
  4986. for (auto &t : threads) {
  4987. t.join();
  4988. }
  4989. }
  4990. TEST_F(ServerTest, GetWithRange1) {
  4991. auto res = cli_.Get("/with-range", Headers{
  4992. make_range_header({{3, 5}}),
  4993. {"Accept-Encoding", ""},
  4994. });
  4995. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4996. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4997. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4998. EXPECT_EQ(true, res->has_header("Content-Range"));
  4999. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  5000. EXPECT_EQ(std::string("def"), res->body);
  5001. }
  5002. TEST_F(ServerTest, GetWithRange2) {
  5003. auto res = cli_.Get("/with-range", Headers{
  5004. make_range_header({{1, -1}}),
  5005. {"Accept-Encoding", ""},
  5006. });
  5007. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5008. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5009. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5010. EXPECT_EQ(true, res->has_header("Content-Range"));
  5011. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  5012. EXPECT_EQ(std::string("bcdefg"), res->body);
  5013. }
  5014. TEST_F(ServerTest, GetWithRange3) {
  5015. auto res = cli_.Get("/with-range", Headers{
  5016. make_range_header({{0, 0}}),
  5017. {"Accept-Encoding", ""},
  5018. });
  5019. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5020. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5021. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  5022. EXPECT_EQ(true, res->has_header("Content-Range"));
  5023. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  5024. EXPECT_EQ(std::string("a"), res->body);
  5025. }
  5026. TEST_F(ServerTest, GetWithRange4) {
  5027. auto res = cli_.Get("/with-range", Headers{
  5028. make_range_header({{-1, 2}}),
  5029. {"Accept-Encoding", ""},
  5030. });
  5031. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5032. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5033. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5034. EXPECT_EQ(true, res->has_header("Content-Range"));
  5035. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  5036. EXPECT_EQ(std::string("fg"), res->body);
  5037. }
  5038. TEST_F(ServerTest, GetWithRange5) {
  5039. auto res = cli_.Get("/with-range", Headers{
  5040. make_range_header({{0, 5}}),
  5041. {"Accept-Encoding", ""},
  5042. });
  5043. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5044. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5045. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5046. EXPECT_EQ(true, res->has_header("Content-Range"));
  5047. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  5048. EXPECT_EQ(std::string("abcdef"), res->body);
  5049. }
  5050. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  5051. auto res =
  5052. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  5053. ASSERT_TRUE(res);
  5054. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5055. }
  5056. TEST_F(ServerTest, GetWithRangeMultipart) {
  5057. auto res =
  5058. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5059. ASSERT_TRUE(res);
  5060. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5061. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  5062. EXPECT_EQ(false, res->has_header("Content-Range"));
  5063. EXPECT_EQ(267U, res->body.size());
  5064. }
  5065. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  5066. auto res = cli_.Get("/with-range",
  5067. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  5068. ASSERT_TRUE(res);
  5069. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5070. }
  5071. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  5072. auto res = cli_.Get("/with-range-customized-response",
  5073. Headers{{make_range_header({{1, 2}})}});
  5074. ASSERT_TRUE(res);
  5075. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5076. EXPECT_EQ(true, res->has_header("Content-Length"));
  5077. EXPECT_EQ(false, res->has_header("Content-Range"));
  5078. EXPECT_EQ(JSON_DATA, res->body);
  5079. }
  5080. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  5081. auto res = cli_.Get("/with-range-customized-response",
  5082. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5083. ASSERT_TRUE(res);
  5084. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5085. EXPECT_EQ(true, res->has_header("Content-Length"));
  5086. EXPECT_EQ(false, res->has_header("Content-Range"));
  5087. EXPECT_EQ(JSON_DATA, res->body);
  5088. }
  5089. TEST_F(ServerTest, Issue1772) {
  5090. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  5091. ASSERT_TRUE(res);
  5092. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  5093. }
  5094. TEST_F(ServerTest, Issue609) {
  5095. auto res = cli_.Delete("/issue609");
  5096. ASSERT_TRUE(res);
  5097. EXPECT_EQ(StatusCode::OK_200, res->status);
  5098. EXPECT_EQ(std::string("ok"), res->body);
  5099. }
  5100. TEST_F(ServerTest, GetStreamedChunked) {
  5101. auto res = cli_.Get("/streamed-chunked");
  5102. ASSERT_TRUE(res);
  5103. EXPECT_EQ(StatusCode::OK_200, res->status);
  5104. EXPECT_EQ(std::string("123456789"), res->body);
  5105. }
  5106. TEST_F(ServerTest, GetStreamedChunked2) {
  5107. auto res = cli_.Get("/streamed-chunked2");
  5108. ASSERT_TRUE(res);
  5109. EXPECT_EQ(StatusCode::OK_200, res->status);
  5110. EXPECT_EQ(std::string("123456789"), res->body);
  5111. }
  5112. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  5113. auto res = cli_.Get("/streamed-chunked-with-trailer");
  5114. ASSERT_TRUE(res);
  5115. EXPECT_EQ(StatusCode::OK_200, res->status);
  5116. EXPECT_EQ(std::string("123456789"), res->body);
  5117. EXPECT_TRUE(res->has_header("Trailer"));
  5118. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  5119. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  5120. // Trailers are now stored separately from headers (security fix)
  5121. EXPECT_EQ(2U, res->trailers.size());
  5122. EXPECT_TRUE(res->has_trailer("Dummy1"));
  5123. EXPECT_TRUE(res->has_trailer("Dummy2"));
  5124. EXPECT_FALSE(res->has_trailer("Dummy3"));
  5125. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  5126. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  5127. // Verify trailers are NOT in headers (security verification)
  5128. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  5129. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  5130. }
  5131. TEST_F(ServerTest, LargeChunkedPost) {
  5132. Request req;
  5133. req.method = "POST";
  5134. req.path = "/large-chunked";
  5135. std::string host_and_port;
  5136. host_and_port += HOST;
  5137. host_and_port += ":";
  5138. host_and_port += std::to_string(PORT);
  5139. req.headers.emplace("Host", host_and_port.c_str());
  5140. req.headers.emplace("Accept", "*/*");
  5141. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5142. req.headers.emplace("Content-Type", "text/plain");
  5143. req.headers.emplace("Content-Length", "0");
  5144. req.headers.emplace("Transfer-Encoding", "chunked");
  5145. std::string long_string(30 * 1024u, 'a');
  5146. std::string chunk = "7800\r\n" + long_string + "\r\n";
  5147. // Attempt to make a large enough post to exceed OS buffers, to test that
  5148. // the server handles short reads if the full chunk data isn't available.
  5149. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  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, GetMethodRemoteAddr) {
  5157. auto res = cli_.Get("/remote_addr");
  5158. ASSERT_TRUE(res);
  5159. EXPECT_EQ(StatusCode::OK_200, res->status);
  5160. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5161. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  5162. }
  5163. TEST_F(ServerTest, GetMethodLocalAddr) {
  5164. auto res = cli_.Get("/local_addr");
  5165. ASSERT_TRUE(res);
  5166. EXPECT_EQ(StatusCode::OK_200, res->status);
  5167. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5168. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  5169. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  5170. }
  5171. TEST_F(ServerTest, HTTPResponseSplitting) {
  5172. auto res = cli_.Get("/http_response_splitting");
  5173. ASSERT_TRUE(res);
  5174. EXPECT_EQ(StatusCode::OK_200, res->status);
  5175. }
  5176. TEST_F(ServerTest, SlowRequest) {
  5177. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5178. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5179. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5180. }
  5181. #if 0
  5182. TEST_F(ServerTest, SlowPost) {
  5183. char buffer[64 * 1024];
  5184. memset(buffer, 0x42, sizeof(buffer));
  5185. auto res = cli_.Post(
  5186. "/slowpost", 64 * 1024 * 1024,
  5187. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5188. auto ret = sink.write(buffer, sizeof(buffer));
  5189. EXPECT_TRUE(ret);
  5190. return true;
  5191. },
  5192. "text/plain");
  5193. ASSERT_TRUE(res);
  5194. EXPECT_EQ(StatusCode::OK_200, res->status);
  5195. }
  5196. TEST_F(ServerTest, SlowPostFail) {
  5197. char buffer[64 * 1024];
  5198. memset(buffer, 0x42, sizeof(buffer));
  5199. cli_.set_write_timeout(std::chrono::seconds(0));
  5200. auto res = cli_.Post(
  5201. "/slowpost", 64 * 1024 * 1024,
  5202. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5203. sink.write(buffer, sizeof(buffer));
  5204. return true;
  5205. },
  5206. "text/plain");
  5207. ASSERT_TRUE(!res);
  5208. EXPECT_EQ(Error::Write, res.error());
  5209. }
  5210. #endif
  5211. TEST_F(ServerTest, Put) {
  5212. auto res = cli_.Put("/put", "PUT", "text/plain");
  5213. ASSERT_TRUE(res);
  5214. EXPECT_EQ(StatusCode::OK_200, res->status);
  5215. EXPECT_EQ("PUT", res->body);
  5216. }
  5217. TEST_F(ServerTest, PutWithContentProvider) {
  5218. auto res = cli_.Put(
  5219. "/put", 3,
  5220. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5221. sink.os << "PUT";
  5222. return true;
  5223. },
  5224. "text/plain");
  5225. ASSERT_TRUE(res);
  5226. EXPECT_EQ(StatusCode::OK_200, res->status);
  5227. EXPECT_EQ("PUT", res->body);
  5228. }
  5229. TEST_F(ServerTest, PostWithContentProviderAbort) {
  5230. auto res = cli_.Post(
  5231. "/post", 42,
  5232. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  5233. return false;
  5234. },
  5235. "text/plain");
  5236. ASSERT_TRUE(!res);
  5237. EXPECT_EQ(Error::Canceled, res.error());
  5238. }
  5239. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  5240. auto res = cli_.Put(
  5241. "/put",
  5242. [](size_t /*offset*/, DataSink &sink) {
  5243. sink.os << "PUT";
  5244. sink.done();
  5245. return true;
  5246. },
  5247. "text/plain");
  5248. ASSERT_TRUE(res);
  5249. EXPECT_EQ(StatusCode::OK_200, res->status);
  5250. EXPECT_EQ("PUT", res->body);
  5251. }
  5252. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  5253. auto res = cli_.Post(
  5254. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  5255. "text/plain");
  5256. ASSERT_TRUE(!res);
  5257. EXPECT_EQ(Error::Canceled, res.error());
  5258. }
  5259. TEST_F(ServerTest, PostLoopBack) {
  5260. std::string body;
  5261. auto res = cli_.Post(
  5262. "/post-loopback", 9,
  5263. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5264. EXPECT_EQ(9u, length);
  5265. sink.write("123", 3);
  5266. sink.write("456", 3);
  5267. sink.write("789", 3);
  5268. return true;
  5269. },
  5270. "text/plain",
  5271. [&body](const char *data, size_t data_length) {
  5272. body.append(data, data_length);
  5273. return true;
  5274. });
  5275. ASSERT_TRUE(res);
  5276. EXPECT_EQ(StatusCode::OK_200, res->status);
  5277. EXPECT_EQ("123456789", body);
  5278. }
  5279. TEST_F(ServerTest, PutLoopBack) {
  5280. std::string body;
  5281. auto res = cli_.Put(
  5282. "/put-loopback", 9,
  5283. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5284. EXPECT_EQ(9u, length);
  5285. sink.write("123", 3);
  5286. sink.write("456", 3);
  5287. sink.write("789", 3);
  5288. return true;
  5289. },
  5290. "text/plain",
  5291. [&body](const char *data, size_t data_length) {
  5292. body.append(data, data_length);
  5293. return true;
  5294. });
  5295. ASSERT_TRUE(res);
  5296. EXPECT_EQ(StatusCode::OK_200, res->status);
  5297. EXPECT_EQ("123456789", body);
  5298. }
  5299. TEST_F(ServerTest, PatchLoopBack) {
  5300. std::string body;
  5301. auto res = cli_.Patch(
  5302. "/patch-loopback", 9,
  5303. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5304. EXPECT_EQ(9u, length);
  5305. sink.write("123", 3);
  5306. sink.write("456", 3);
  5307. sink.write("789", 3);
  5308. return true;
  5309. },
  5310. "text/plain",
  5311. [&body](const char *data, size_t data_length) {
  5312. body.append(data, data_length);
  5313. return true;
  5314. });
  5315. ASSERT_TRUE(res);
  5316. EXPECT_EQ(StatusCode::OK_200, res->status);
  5317. EXPECT_EQ("123456789", body);
  5318. }
  5319. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  5320. std::string body;
  5321. auto res = cli_.Post(
  5322. "/post-loopback",
  5323. [](size_t /*offset*/, DataSink &sink) {
  5324. sink.write("123", 3);
  5325. sink.write("456", 3);
  5326. sink.write("789", 3);
  5327. sink.done();
  5328. return true;
  5329. },
  5330. "text/plain",
  5331. [&body](const char *data, size_t data_length) {
  5332. body.append(data, data_length);
  5333. return true;
  5334. });
  5335. ASSERT_TRUE(res);
  5336. EXPECT_EQ(StatusCode::OK_200, res->status);
  5337. EXPECT_EQ("123456789", body);
  5338. }
  5339. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5340. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  5341. cli_.set_compress(true);
  5342. auto res = cli_.Put(
  5343. "/put", 3,
  5344. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5345. sink.os << "PUT";
  5346. return true;
  5347. },
  5348. "text/plain");
  5349. ASSERT_TRUE(res);
  5350. EXPECT_EQ(StatusCode::OK_200, res->status);
  5351. EXPECT_EQ("PUT", res->body);
  5352. }
  5353. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  5354. cli_.set_compress(true);
  5355. auto res = cli_.Post(
  5356. "/post", 42,
  5357. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  5358. return false;
  5359. },
  5360. "text/plain");
  5361. ASSERT_TRUE(!res);
  5362. EXPECT_EQ(Error::Canceled, res.error());
  5363. }
  5364. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  5365. cli_.set_compress(true);
  5366. auto res = cli_.Put(
  5367. "/put",
  5368. [](size_t /*offset*/, DataSink &sink) {
  5369. sink.os << "PUT";
  5370. sink.done();
  5371. return true;
  5372. },
  5373. "text/plain");
  5374. ASSERT_TRUE(res);
  5375. EXPECT_EQ(StatusCode::OK_200, res->status);
  5376. EXPECT_EQ("PUT", res->body);
  5377. }
  5378. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  5379. cli_.set_compress(true);
  5380. auto res = cli_.Post(
  5381. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  5382. "text/plain");
  5383. ASSERT_TRUE(!res);
  5384. EXPECT_EQ(Error::Canceled, res.error());
  5385. }
  5386. TEST_F(ServerTest, PutLargeFileWithGzip) {
  5387. cli_.set_compress(true);
  5388. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  5389. ASSERT_TRUE(res);
  5390. EXPECT_EQ(StatusCode::OK_200, res->status);
  5391. EXPECT_EQ(LARGE_DATA, res->body);
  5392. }
  5393. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  5394. #ifdef CPPHTTPLIB_SSL_ENABLED
  5395. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  5396. Client cli(s.c_str());
  5397. cli.enable_server_certificate_verification(false);
  5398. #else
  5399. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  5400. Client cli(s.c_str());
  5401. #endif
  5402. cli.set_compress(true);
  5403. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  5404. ASSERT_TRUE(res);
  5405. EXPECT_EQ(StatusCode::OK_200, res->status);
  5406. EXPECT_EQ(LARGE_DATA, res->body);
  5407. // The compressed size should be less than a 10th of the original. May vary
  5408. // depending on the zlib library.
  5409. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  5410. static_cast<uint64_t>(10 * 1024 * 1024));
  5411. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5412. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  5413. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  5414. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  5415. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5416. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  5417. #endif
  5418. }
  5419. TEST_F(ServerTest, PutContentWithDeflate) {
  5420. cli_.set_compress(false);
  5421. Headers headers;
  5422. headers.emplace("Content-Encoding", "deflate");
  5423. // PUT in deflate format:
  5424. auto res = cli_.Put("/put", headers,
  5425. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  5426. ASSERT_TRUE(res);
  5427. EXPECT_EQ(StatusCode::OK_200, res->status);
  5428. EXPECT_EQ("PUT", res->body);
  5429. }
  5430. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  5431. Headers headers;
  5432. headers.emplace("Accept-Encoding", "gzip, deflate");
  5433. auto res = cli_.Get("/streamed-chunked", headers);
  5434. ASSERT_TRUE(res);
  5435. EXPECT_EQ(StatusCode::OK_200, res->status);
  5436. EXPECT_EQ(std::string("123456789"), res->body);
  5437. }
  5438. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  5439. Headers headers;
  5440. headers.emplace("Accept-Encoding", "gzip, deflate");
  5441. auto res = cli_.Get("/streamed-chunked2", headers);
  5442. ASSERT_TRUE(res);
  5443. EXPECT_EQ(StatusCode::OK_200, res->status);
  5444. EXPECT_EQ(std::string("123456789"), res->body);
  5445. }
  5446. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  5447. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  5448. ASSERT_TRUE(res);
  5449. EXPECT_EQ(StatusCode::OK_200, res->status);
  5450. }
  5451. TEST(GzipDecompressor, ChunkedDecompression) {
  5452. std::string data;
  5453. for (size_t i = 0; i < 32 * 1024; ++i) {
  5454. data.push_back(static_cast<char>('a' + i % 26));
  5455. }
  5456. std::string compressed_data;
  5457. {
  5458. httplib::detail::gzip_compressor compressor;
  5459. bool result = compressor.compress(
  5460. data.data(), data.size(),
  5461. /*last=*/true,
  5462. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5463. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5464. compressed_data_size);
  5465. return true;
  5466. });
  5467. ASSERT_TRUE(result);
  5468. }
  5469. std::string decompressed_data;
  5470. {
  5471. httplib::detail::gzip_decompressor decompressor;
  5472. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5473. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5474. size_t chunk_size = 130;
  5475. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5476. chunk_begin += chunk_size) {
  5477. size_t current_chunk_size =
  5478. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5479. bool result = decompressor.decompress(
  5480. compressed_data.data() + chunk_begin, current_chunk_size,
  5481. [&](const char *decompressed_data_chunk,
  5482. size_t decompressed_data_chunk_size) {
  5483. decompressed_data.insert(decompressed_data.size(),
  5484. decompressed_data_chunk,
  5485. decompressed_data_chunk_size);
  5486. return true;
  5487. });
  5488. ASSERT_TRUE(result);
  5489. }
  5490. }
  5491. ASSERT_EQ(data, decompressed_data);
  5492. }
  5493. TEST(GzipDecompressor, DeflateDecompression) {
  5494. std::string original_text = "Raw deflate without gzip";
  5495. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  5496. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  5497. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  5498. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  5499. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5500. std::string decompressed_data;
  5501. {
  5502. httplib::detail::gzip_decompressor decompressor;
  5503. bool result = decompressor.decompress(
  5504. compressed_data.data(), compressed_data.size(),
  5505. [&](const char *decompressed_data_chunk,
  5506. size_t decompressed_data_chunk_size) {
  5507. decompressed_data.insert(decompressed_data.size(),
  5508. decompressed_data_chunk,
  5509. decompressed_data_chunk_size);
  5510. return true;
  5511. });
  5512. ASSERT_TRUE(result);
  5513. }
  5514. ASSERT_EQ(original_text, decompressed_data);
  5515. }
  5516. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  5517. std::string original_text = "Raw deflate without gzip";
  5518. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  5519. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  5520. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  5521. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  5522. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  5523. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5524. std::string decompressed_data;
  5525. {
  5526. httplib::detail::gzip_decompressor decompressor;
  5527. bool result = decompressor.decompress(
  5528. compressed_data.data(), compressed_data.size(),
  5529. [&](const char *decompressed_data_chunk,
  5530. size_t decompressed_data_chunk_size) {
  5531. decompressed_data.insert(decompressed_data.size(),
  5532. decompressed_data_chunk,
  5533. decompressed_data_chunk_size);
  5534. return true;
  5535. });
  5536. ASSERT_TRUE(result);
  5537. }
  5538. ASSERT_EQ(original_text, decompressed_data);
  5539. }
  5540. #endif
  5541. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5542. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  5543. Headers headers;
  5544. headers.emplace("Accept-Encoding", "br");
  5545. auto res = cli_.Get("/streamed-chunked", headers);
  5546. ASSERT_TRUE(res);
  5547. EXPECT_EQ(StatusCode::OK_200, res->status);
  5548. EXPECT_EQ(std::string("123456789"), res->body);
  5549. }
  5550. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  5551. Headers headers;
  5552. headers.emplace("Accept-Encoding", "br");
  5553. auto res = cli_.Get("/streamed-chunked2", headers);
  5554. ASSERT_TRUE(res);
  5555. EXPECT_EQ(StatusCode::OK_200, res->status);
  5556. EXPECT_EQ(std::string("123456789"), res->body);
  5557. }
  5558. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  5559. cli_.set_compress(true);
  5560. auto res = cli_.Put(
  5561. "/put", 3,
  5562. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5563. sink.os << "PUT";
  5564. return true;
  5565. },
  5566. "text/plain");
  5567. ASSERT_TRUE(res);
  5568. EXPECT_EQ(StatusCode::OK_200, res->status);
  5569. EXPECT_EQ("PUT", res->body);
  5570. }
  5571. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  5572. cli_.set_compress(true);
  5573. auto res = cli_.Put(
  5574. "/put",
  5575. [](size_t /*offset*/, DataSink &sink) {
  5576. sink.os << "PUT";
  5577. sink.done();
  5578. return true;
  5579. },
  5580. "text/plain");
  5581. ASSERT_TRUE(res);
  5582. EXPECT_EQ(StatusCode::OK_200, res->status);
  5583. EXPECT_EQ("PUT", res->body);
  5584. }
  5585. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  5586. cli_.set_compress(true);
  5587. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  5588. ASSERT_TRUE(res);
  5589. EXPECT_EQ(StatusCode::OK_200, res->status);
  5590. EXPECT_EQ(LARGE_DATA, res->body);
  5591. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  5592. }
  5593. #endif
  5594. TEST_F(ServerTest, Patch) {
  5595. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  5596. ASSERT_TRUE(res);
  5597. EXPECT_EQ(StatusCode::OK_200, res->status);
  5598. EXPECT_EQ("PATCH", res->body);
  5599. }
  5600. TEST_F(ServerTest, Delete) {
  5601. auto res = cli_.Delete("/delete");
  5602. ASSERT_TRUE(res);
  5603. EXPECT_EQ(StatusCode::OK_200, res->status);
  5604. EXPECT_EQ("DELETE", res->body);
  5605. }
  5606. TEST_F(ServerTest, DeleteContentReceiver) {
  5607. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  5608. ASSERT_TRUE(res);
  5609. EXPECT_EQ(StatusCode::OK_200, res->status);
  5610. EXPECT_EQ("content", res->body);
  5611. }
  5612. TEST_F(ServerTest, Options) {
  5613. auto res = cli_.Options("*");
  5614. ASSERT_TRUE(res);
  5615. EXPECT_EQ(StatusCode::OK_200, res->status);
  5616. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  5617. EXPECT_TRUE(res->body.empty());
  5618. }
  5619. TEST_F(ServerTest, URL) {
  5620. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  5621. ASSERT_TRUE(res);
  5622. EXPECT_EQ(StatusCode::OK_200, res->status);
  5623. }
  5624. TEST_F(ServerTest, ArrayParam) {
  5625. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  5626. ASSERT_TRUE(res);
  5627. EXPECT_EQ(StatusCode::OK_200, res->status);
  5628. }
  5629. TEST_F(ServerTest, ArrayParamValues) {
  5630. auto res =
  5631. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  5632. ASSERT_TRUE(res);
  5633. EXPECT_EQ(StatusCode::OK_200, res->status);
  5634. }
  5635. TEST_F(ServerTest, NoMultipleHeaders) {
  5636. Headers headers = {{"Content-Length", "5"}};
  5637. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  5638. "text/plain");
  5639. ASSERT_TRUE(res);
  5640. EXPECT_EQ(StatusCode::OK_200, res->status);
  5641. }
  5642. TEST_F(ServerTest, PostContentReceiver) {
  5643. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5644. ASSERT_TRUE(res);
  5645. ASSERT_EQ(StatusCode::OK_200, res->status);
  5646. ASSERT_EQ("content", res->body);
  5647. }
  5648. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  5649. UploadFormDataItems items = {
  5650. {"text1", "text default", "", ""},
  5651. {"text2", "aωb", "", ""},
  5652. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5653. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5654. {"file3", "", "", "application/octet-stream"},
  5655. };
  5656. auto res = cli_.Post("/content_receiver", items);
  5657. ASSERT_TRUE(res);
  5658. EXPECT_EQ(StatusCode::OK_200, res->status);
  5659. }
  5660. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  5661. UploadFormDataItems items = {
  5662. {"text1", "text default", "", ""},
  5663. {"text2", "aωb", "", ""},
  5664. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5665. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5666. {"file3", "", "", "application/octet-stream"},
  5667. };
  5668. auto boundary = std::string("+++++");
  5669. std::string body;
  5670. for (const auto &item : items) {
  5671. body += "--" + boundary + "\r\n";
  5672. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  5673. if (!item.filename.empty()) {
  5674. body += "; filename=\"" + item.filename + "\"";
  5675. }
  5676. body += "\r\n";
  5677. if (!item.content_type.empty()) {
  5678. body += "Content-Type: " + item.content_type + "\r\n";
  5679. }
  5680. body += "\r\n";
  5681. body += item.content + "\r\n";
  5682. }
  5683. body += "--" + boundary + "--\r\n";
  5684. std::string content_type = "multipart/form-data; boundary=" + boundary;
  5685. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  5686. ASSERT_TRUE(res);
  5687. EXPECT_EQ(StatusCode::OK_200, res->status);
  5688. }
  5689. TEST(MultipartFormDataTest, FieldEscaping) {
  5690. Server svr;
  5691. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  5692. const ContentReader &content_reader) {
  5693. ASSERT_TRUE(req.is_multipart_form_data());
  5694. std::vector<FormData> received;
  5695. content_reader(
  5696. [&](const FormData &file) {
  5697. received.push_back(file);
  5698. return true;
  5699. },
  5700. [&](const char *data, size_t data_length) {
  5701. received.back().content.append(data, data_length);
  5702. return true;
  5703. });
  5704. // '"', CR and LF in names and filenames are escaped following the
  5705. // WHATWG HTML standard, so each part still parses as a single part
  5706. // with no injected headers. Content types get CR/LF escaped too,
  5707. // while '"' (legal there, e.g. quoted charset) is preserved.
  5708. ASSERT_EQ(4U, received.size());
  5709. EXPECT_EQ("na%22me", received[0].name);
  5710. EXPECT_EQ("quoted name", received[0].content);
  5711. EXPECT_EQ("file", received[1].name);
  5712. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  5713. received[1].filename);
  5714. EXPECT_EQ("application/octet-stream", received[1].content_type);
  5715. EXPECT_EQ("injected", received[1].content);
  5716. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  5717. EXPECT_EQ("my%22file.txt", received[2].filename);
  5718. EXPECT_EQ("cr lf name", received[2].content);
  5719. EXPECT_EQ("typed", received[3].name);
  5720. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  5721. received[3].content_type);
  5722. EXPECT_EQ("typed content", received[3].content);
  5723. });
  5724. auto port = svr.bind_to_any_port("localhost");
  5725. auto t = std::thread([&]() { svr.listen_after_bind(); });
  5726. auto se = detail::scope_exit([&] {
  5727. svr.stop();
  5728. t.join();
  5729. ASSERT_FALSE(svr.is_running());
  5730. });
  5731. svr.wait_until_ready();
  5732. Client cli("localhost", port);
  5733. UploadFormDataItems items = {
  5734. {"na\"me", "quoted name", "", ""},
  5735. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  5736. "application/octet-stream"},
  5737. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  5738. {"typed", "typed content", "",
  5739. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  5740. };
  5741. auto res = cli.Post("/post", items);
  5742. ASSERT_TRUE(res);
  5743. EXPECT_EQ(StatusCode::OK_200, res->status);
  5744. }
  5745. TEST(MultipartFormDataTest, PublicWriterAPI) {
  5746. const UploadFormDataItems items = {
  5747. {"name1", "Content 1", "", ""},
  5748. {"name2", "Content 2", "file2.txt", "text/plain"},
  5749. };
  5750. Server svr;
  5751. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  5752. const ContentReader &content_reader) {
  5753. ASSERT_TRUE(req.is_multipart_form_data());
  5754. std::vector<FormData> received;
  5755. content_reader(
  5756. [&](const FormData &file) {
  5757. received.push_back(file);
  5758. return true;
  5759. },
  5760. [&](const char *data, size_t data_length) {
  5761. received.back().content.append(data, data_length);
  5762. return true;
  5763. });
  5764. ASSERT_EQ(2U, received.size());
  5765. EXPECT_EQ("name1", received[0].name);
  5766. EXPECT_EQ("Content 1", received[0].content);
  5767. EXPECT_EQ("name2", received[1].name);
  5768. EXPECT_EQ("Content 2", received[1].content);
  5769. EXPECT_EQ("file2.txt", received[1].filename);
  5770. EXPECT_EQ("text/plain", received[1].content_type);
  5771. });
  5772. auto port = svr.bind_to_any_port("localhost");
  5773. auto t = std::thread([&]() { svr.listen_after_bind(); });
  5774. auto se = detail::scope_exit([&] {
  5775. svr.stop();
  5776. t.join();
  5777. ASSERT_FALSE(svr.is_running());
  5778. });
  5779. svr.wait_until_ready();
  5780. Client cli("localhost", port);
  5781. // Whole-body serialization with a generated boundary
  5782. {
  5783. MultipartFormDataWriter writer;
  5784. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  5785. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  5786. writer.content_type());
  5787. auto body = writer.serialize(items);
  5788. EXPECT_EQ(body.size(), writer.content_length(items));
  5789. auto res = cli.Post("/post", body, writer.content_type());
  5790. ASSERT_TRUE(res);
  5791. EXPECT_EQ(StatusCode::OK_200, res->status);
  5792. }
  5793. // Per-part framing with a custom boundary via a content provider
  5794. {
  5795. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  5796. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  5797. MultipartFormDataWriter writer("custom-boundary_123");
  5798. EXPECT_EQ("custom-boundary_123", writer.boundary());
  5799. std::string body;
  5800. for (const auto &item : items) {
  5801. body += writer.item_begin(item);
  5802. body += item.content;
  5803. body += MultipartFormDataWriter::item_end();
  5804. }
  5805. body += writer.finish();
  5806. EXPECT_EQ(body.size(), writer.content_length(items));
  5807. auto res = cli.Post(
  5808. "/post", body.size(),
  5809. [&](size_t offset, size_t length, DataSink &sink) {
  5810. sink.write(body.data() + offset, length);
  5811. return true;
  5812. },
  5813. writer.content_type());
  5814. ASSERT_TRUE(res);
  5815. EXPECT_EQ(StatusCode::OK_200, res->status);
  5816. }
  5817. }
  5818. TEST_F(ServerTest, PostContentReceiverGzip) {
  5819. cli_.set_compress(true);
  5820. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5821. ASSERT_TRUE(res);
  5822. ASSERT_EQ(StatusCode::OK_200, res->status);
  5823. ASSERT_EQ("content", res->body);
  5824. }
  5825. TEST_F(ServerTest, PutContentReceiver) {
  5826. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  5827. ASSERT_TRUE(res);
  5828. ASSERT_EQ(StatusCode::OK_200, res->status);
  5829. ASSERT_EQ("content", res->body);
  5830. }
  5831. TEST_F(ServerTest, PatchContentReceiver) {
  5832. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  5833. ASSERT_TRUE(res);
  5834. ASSERT_EQ(StatusCode::OK_200, res->status);
  5835. ASSERT_EQ("content", res->body);
  5836. }
  5837. template <typename ClientType>
  5838. void TestWithHeadersAndContentReceiver(
  5839. ClientType &cli,
  5840. std::function<Result(ClientType &, const std::string &, const Headers &,
  5841. const std::string &, const std::string &,
  5842. ContentReceiver, DownloadProgress)>
  5843. request_func) {
  5844. Headers headers;
  5845. headers.emplace("X-Custom-Header", "test-value");
  5846. std::string received_body;
  5847. auto res = request_func(
  5848. cli, "/content_receiver", headers, "content", "application/json",
  5849. [&](const char *data, size_t data_length) {
  5850. received_body.append(data, data_length);
  5851. return true;
  5852. },
  5853. nullptr);
  5854. ASSERT_TRUE(res);
  5855. EXPECT_EQ(StatusCode::OK_200, res->status);
  5856. EXPECT_EQ("content", received_body);
  5857. }
  5858. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  5859. #ifdef CPPHTTPLIB_SSL_ENABLED
  5860. using ClientT = SSLClient;
  5861. #else
  5862. using ClientT = Client;
  5863. #endif
  5864. TestWithHeadersAndContentReceiver<ClientT>(
  5865. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5866. const std::string &body, const std::string &content_type,
  5867. ContentReceiver receiver, DownloadProgress progress) {
  5868. return cli.Post(path, headers, body, content_type, receiver, progress);
  5869. });
  5870. }
  5871. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  5872. #ifdef CPPHTTPLIB_SSL_ENABLED
  5873. using ClientT = SSLClient;
  5874. #else
  5875. using ClientT = Client;
  5876. #endif
  5877. TestWithHeadersAndContentReceiver<ClientT>(
  5878. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5879. const std::string &body, const std::string &content_type,
  5880. ContentReceiver receiver, DownloadProgress progress) {
  5881. return cli.Put(path, headers, body, content_type, receiver, progress);
  5882. });
  5883. }
  5884. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  5885. #ifdef CPPHTTPLIB_SSL_ENABLED
  5886. using ClientT = SSLClient;
  5887. #else
  5888. using ClientT = Client;
  5889. #endif
  5890. TestWithHeadersAndContentReceiver<ClientT>(
  5891. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5892. const std::string &body, const std::string &content_type,
  5893. ContentReceiver receiver, DownloadProgress progress) {
  5894. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5895. });
  5896. }
  5897. template <typename ClientType>
  5898. void TestWithHeadersAndContentReceiverWithProgress(
  5899. ClientType &cli,
  5900. std::function<Result(ClientType &, const std::string &, const Headers &,
  5901. const std::string &, const std::string &,
  5902. ContentReceiver, DownloadProgress)>
  5903. request_func) {
  5904. Headers headers;
  5905. headers.emplace("X-Test-Header", "progress-test");
  5906. std::string received_body;
  5907. auto progress_called = false;
  5908. auto res = request_func(
  5909. cli, "/content_receiver", headers, "content", "text/plain",
  5910. [&](const char *data, size_t data_length) {
  5911. received_body.append(data, data_length);
  5912. return true;
  5913. },
  5914. [&](uint64_t /*current*/, uint64_t /*total*/) {
  5915. progress_called = true;
  5916. return true;
  5917. });
  5918. ASSERT_TRUE(res);
  5919. EXPECT_EQ(StatusCode::OK_200, res->status);
  5920. EXPECT_EQ("content", received_body);
  5921. EXPECT_TRUE(progress_called);
  5922. }
  5923. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  5924. #ifdef CPPHTTPLIB_SSL_ENABLED
  5925. using ClientT = SSLClient;
  5926. #else
  5927. using ClientT = Client;
  5928. #endif
  5929. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5930. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5931. const std::string &body, const std::string &content_type,
  5932. ContentReceiver receiver, DownloadProgress progress) {
  5933. return cli.Post(path, headers, body, content_type, receiver, progress);
  5934. });
  5935. }
  5936. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  5937. #ifdef CPPHTTPLIB_SSL_ENABLED
  5938. using ClientT = SSLClient;
  5939. #else
  5940. using ClientT = Client;
  5941. #endif
  5942. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5943. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5944. const std::string &body, const std::string &content_type,
  5945. ContentReceiver receiver, DownloadProgress progress) {
  5946. return cli.Put(path, headers, body, content_type, receiver, progress);
  5947. });
  5948. }
  5949. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  5950. #ifdef CPPHTTPLIB_SSL_ENABLED
  5951. using ClientT = SSLClient;
  5952. #else
  5953. using ClientT = Client;
  5954. #endif
  5955. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5956. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5957. const std::string &body, const std::string &content_type,
  5958. ContentReceiver receiver, DownloadProgress progress) {
  5959. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5960. });
  5961. }
  5962. template <typename ClientType>
  5963. void TestWithHeadersAndContentReceiverError(
  5964. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  5965. const Headers &, const std::string &,
  5966. const std::string &, ContentReceiver)>
  5967. request_func) {
  5968. Headers headers;
  5969. headers.emplace("X-Error-Test", "true");
  5970. std::string received_body;
  5971. auto receiver_failed = false;
  5972. auto res =
  5973. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  5974. [&](const char *data, size_t data_length) {
  5975. received_body.append(data, data_length);
  5976. receiver_failed = true;
  5977. return false;
  5978. });
  5979. ASSERT_FALSE(res);
  5980. EXPECT_TRUE(receiver_failed);
  5981. }
  5982. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  5983. #ifdef CPPHTTPLIB_SSL_ENABLED
  5984. using ClientT = SSLClient;
  5985. #else
  5986. using ClientT = Client;
  5987. #endif
  5988. TestWithHeadersAndContentReceiverError<ClientT>(
  5989. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5990. const std::string &body, const std::string &content_type,
  5991. ContentReceiver receiver) {
  5992. return cli.Post(path, headers, body, content_type, receiver);
  5993. });
  5994. }
  5995. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  5996. #ifdef CPPHTTPLIB_SSL_ENABLED
  5997. using ClientT = SSLClient;
  5998. #else
  5999. using ClientT = Client;
  6000. #endif
  6001. TestWithHeadersAndContentReceiverError<ClientT>(
  6002. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6003. const std::string &body, const std::string &content_type,
  6004. ContentReceiver receiver) {
  6005. return cli.Put(path, headers, body, content_type, receiver);
  6006. });
  6007. }
  6008. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  6009. #ifdef CPPHTTPLIB_SSL_ENABLED
  6010. using ClientT = SSLClient;
  6011. #else
  6012. using ClientT = Client;
  6013. #endif
  6014. TestWithHeadersAndContentReceiverError<ClientT>(
  6015. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6016. const std::string &body, const std::string &content_type,
  6017. ContentReceiver receiver) {
  6018. return cli.Patch(path, headers, body, content_type, receiver);
  6019. });
  6020. }
  6021. TEST_F(ServerTest, PostQueryStringAndBody) {
  6022. auto res =
  6023. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  6024. ASSERT_TRUE(res);
  6025. ASSERT_EQ(StatusCode::OK_200, res->status);
  6026. }
  6027. TEST_F(ServerTest, HTTP2Magic) {
  6028. Request req;
  6029. req.method = "PRI";
  6030. req.path = "*";
  6031. req.body = "SM";
  6032. auto res = std::make_shared<Response>();
  6033. auto error = Error::Success;
  6034. auto ret = cli_.send(req, *res, error);
  6035. ASSERT_TRUE(ret);
  6036. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6037. }
  6038. TEST_F(ServerTest, KeepAlive) {
  6039. auto res = cli_.Get("/hi");
  6040. ASSERT_TRUE(res);
  6041. EXPECT_EQ(StatusCode::OK_200, res->status);
  6042. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6043. EXPECT_EQ("Hello World!", res->body);
  6044. res = cli_.Get("/hi");
  6045. ASSERT_TRUE(res);
  6046. EXPECT_EQ(StatusCode::OK_200, res->status);
  6047. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6048. EXPECT_EQ("Hello World!", res->body);
  6049. res = cli_.Get("/hi");
  6050. ASSERT_TRUE(res);
  6051. EXPECT_EQ(StatusCode::OK_200, res->status);
  6052. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6053. EXPECT_EQ("Hello World!", res->body);
  6054. res = cli_.Get("/not-exist");
  6055. ASSERT_TRUE(res);
  6056. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6057. res = cli_.Post("/empty", "", "text/plain");
  6058. ASSERT_TRUE(res);
  6059. EXPECT_EQ(StatusCode::OK_200, res->status);
  6060. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6061. EXPECT_EQ("empty", res->body);
  6062. EXPECT_EQ("close", res->get_header_value("Connection"));
  6063. res = cli_.Post(
  6064. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  6065. "text/plain");
  6066. ASSERT_TRUE(res);
  6067. EXPECT_EQ(StatusCode::OK_200, res->status);
  6068. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6069. EXPECT_EQ("empty", res->body);
  6070. cli_.set_keep_alive(false);
  6071. res = cli_.Get("/last-request");
  6072. ASSERT_TRUE(res);
  6073. EXPECT_EQ(StatusCode::OK_200, res->status);
  6074. EXPECT_EQ("close", res->get_header_value("Connection"));
  6075. }
  6076. TEST_F(ServerTest, TooManyRedirect) {
  6077. cli_.set_follow_location(true);
  6078. auto res = cli_.Get("/redirect/0");
  6079. ASSERT_TRUE(!res);
  6080. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  6081. }
  6082. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  6083. Request req;
  6084. req.method = "FOOBAR";
  6085. req.path = "/hi";
  6086. cli_.set_keep_alive(true);
  6087. auto res = cli_.send(req);
  6088. ASSERT_TRUE(res);
  6089. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6090. EXPECT_EQ("close", res->get_header_value("Connection"));
  6091. EXPECT_FALSE(cli_.is_socket_open());
  6092. }
  6093. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  6094. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6095. TEST_F(ServerTest, Gzip) {
  6096. Headers headers;
  6097. headers.emplace("Accept-Encoding", "gzip, deflate");
  6098. auto res = cli_.Get("/compress", headers);
  6099. ASSERT_TRUE(res);
  6100. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6101. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6102. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6103. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6104. "7890123456789012345678901234567890",
  6105. res->body);
  6106. EXPECT_EQ(StatusCode::OK_200, res->status);
  6107. }
  6108. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  6109. Headers headers;
  6110. headers.emplace("Accept-Encoding", "gzip, deflate");
  6111. auto res = cli_.Get("/compress-with-charset", headers);
  6112. ASSERT_TRUE(res);
  6113. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6114. EXPECT_EQ("application/json; charset=utf-8",
  6115. res->get_header_value("Content-Type"));
  6116. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6117. "7890123456789012345678901234567890",
  6118. res->body);
  6119. EXPECT_EQ(StatusCode::OK_200, res->status);
  6120. }
  6121. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  6122. Headers headers;
  6123. headers.emplace("Accept-Encoding", "");
  6124. auto res = cli_.Get("/compress", headers);
  6125. ASSERT_TRUE(res);
  6126. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6127. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6128. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6129. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6130. "7890123456789012345678901234567890",
  6131. res->body);
  6132. EXPECT_EQ(StatusCode::OK_200, res->status);
  6133. }
  6134. TEST_F(ServerTest, GzipWithContentReceiver) {
  6135. Headers headers;
  6136. headers.emplace("Accept-Encoding", "gzip, deflate");
  6137. std::string body;
  6138. auto res = cli_.Get("/compress", headers,
  6139. [&](const char *data, uint64_t data_length) {
  6140. EXPECT_EQ(100U, data_length);
  6141. body.append(data, data_length);
  6142. return true;
  6143. });
  6144. ASSERT_TRUE(res);
  6145. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6146. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6147. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6148. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6149. "7890123456789012345678901234567890",
  6150. body);
  6151. EXPECT_EQ(StatusCode::OK_200, res->status);
  6152. }
  6153. TEST_F(ServerTest, GzipWithoutDecompressing) {
  6154. Headers headers;
  6155. headers.emplace("Accept-Encoding", "gzip, deflate");
  6156. cli_.set_decompress(false);
  6157. auto res = cli_.Get("/compress", headers);
  6158. ASSERT_TRUE(res);
  6159. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6160. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6161. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6162. EXPECT_EQ(33U, res->body.size());
  6163. EXPECT_EQ(StatusCode::OK_200, res->status);
  6164. }
  6165. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  6166. Headers headers;
  6167. headers.emplace("Accept-Encoding", "");
  6168. std::string body;
  6169. auto res = cli_.Get("/compress", headers,
  6170. [&](const char *data, uint64_t data_length) {
  6171. EXPECT_EQ(100U, data_length);
  6172. body.append(data, data_length);
  6173. return true;
  6174. });
  6175. ASSERT_TRUE(res);
  6176. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6177. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6178. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6179. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6180. "7890123456789012345678901234567890",
  6181. body);
  6182. EXPECT_EQ(StatusCode::OK_200, res->status);
  6183. }
  6184. TEST_F(ServerTest, NoGzip) {
  6185. Headers headers;
  6186. headers.emplace("Accept-Encoding", "gzip, deflate");
  6187. auto res = cli_.Get("/nocompress", headers);
  6188. ASSERT_TRUE(res);
  6189. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6190. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6191. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6192. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6193. "7890123456789012345678901234567890",
  6194. res->body);
  6195. EXPECT_EQ(StatusCode::OK_200, res->status);
  6196. }
  6197. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  6198. Headers headers;
  6199. headers.emplace("Accept-Encoding", "gzip, deflate");
  6200. std::string body;
  6201. auto res = cli_.Get("/nocompress", headers,
  6202. [&](const char *data, uint64_t data_length) {
  6203. EXPECT_EQ(100U, data_length);
  6204. body.append(data, data_length);
  6205. return true;
  6206. });
  6207. ASSERT_TRUE(res);
  6208. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6209. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6210. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6211. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6212. "7890123456789012345678901234567890",
  6213. body);
  6214. EXPECT_EQ(StatusCode::OK_200, res->status);
  6215. }
  6216. TEST_F(ServerTest, MultipartFormDataGzip) {
  6217. UploadFormDataItems items = {
  6218. {"key1", "test", "", ""},
  6219. {"key2", "--abcdefg123", "", ""},
  6220. };
  6221. cli_.set_compress(true);
  6222. auto res = cli_.Post("/compress-multipart", items);
  6223. ASSERT_TRUE(res);
  6224. EXPECT_EQ(StatusCode::OK_200, res->status);
  6225. }
  6226. #endif
  6227. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6228. TEST_F(ServerTest, Brotli) {
  6229. Headers headers;
  6230. headers.emplace("Accept-Encoding", "br");
  6231. auto res = cli_.Get("/compress", headers);
  6232. ASSERT_TRUE(res);
  6233. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  6234. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6235. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  6236. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6237. "7890123456789012345678901234567890",
  6238. res->body);
  6239. EXPECT_EQ(StatusCode::OK_200, res->status);
  6240. }
  6241. #endif
  6242. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  6243. TEST_F(ServerTest, Zstd) {
  6244. Headers headers;
  6245. headers.emplace("Accept-Encoding", "zstd");
  6246. auto res = cli_.Get("/compress", headers);
  6247. ASSERT_TRUE(res);
  6248. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6249. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6250. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6251. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6252. "7890123456789012345678901234567890",
  6253. res->body);
  6254. EXPECT_EQ(StatusCode::OK_200, res->status);
  6255. }
  6256. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  6257. Headers headers;
  6258. headers.emplace("Accept-Encoding", "");
  6259. auto res = cli_.Get("/compress", headers);
  6260. ASSERT_TRUE(res);
  6261. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6262. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6263. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6264. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6265. "7890123456789012345678901234567890",
  6266. res->body);
  6267. EXPECT_EQ(StatusCode::OK_200, res->status);
  6268. }
  6269. TEST_F(ServerTest, ZstdWithContentReceiver) {
  6270. Headers headers;
  6271. headers.emplace("Accept-Encoding", "zstd");
  6272. std::string body;
  6273. auto res = cli_.Get("/compress", headers,
  6274. [&](const char *data, uint64_t data_length) {
  6275. EXPECT_EQ(100U, data_length);
  6276. body.append(data, data_length);
  6277. return true;
  6278. });
  6279. ASSERT_TRUE(res);
  6280. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6281. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6282. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6283. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6284. "7890123456789012345678901234567890",
  6285. body);
  6286. EXPECT_EQ(StatusCode::OK_200, res->status);
  6287. }
  6288. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  6289. Headers headers;
  6290. headers.emplace("Accept-Encoding", "zstd");
  6291. cli_.set_decompress(false);
  6292. auto res = cli_.Get("/compress", headers);
  6293. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  6294. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  6295. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  6296. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  6297. ASSERT_TRUE(res);
  6298. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6299. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6300. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6301. EXPECT_EQ(StatusCode::OK_200, res->status);
  6302. ASSERT_EQ(26U, res->body.size());
  6303. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  6304. 0);
  6305. }
  6306. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  6307. Headers headers;
  6308. headers.emplace("Accept-Encoding", "");
  6309. std::string body;
  6310. auto res = cli_.Get("/compress", headers,
  6311. [&](const char *data, uint64_t data_length) {
  6312. EXPECT_EQ(100U, data_length);
  6313. body.append(data, data_length);
  6314. return true;
  6315. });
  6316. ASSERT_TRUE(res);
  6317. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6318. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6319. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6320. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6321. "7890123456789012345678901234567890",
  6322. body);
  6323. EXPECT_EQ(StatusCode::OK_200, res->status);
  6324. }
  6325. TEST_F(ServerTest, NoZstd) {
  6326. Headers headers;
  6327. headers.emplace("Accept-Encoding", "zstd");
  6328. auto res = cli_.Get("/nocompress", headers);
  6329. ASSERT_TRUE(res);
  6330. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6331. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6332. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6333. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6334. "7890123456789012345678901234567890",
  6335. res->body);
  6336. EXPECT_EQ(StatusCode::OK_200, res->status);
  6337. }
  6338. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  6339. Headers headers;
  6340. headers.emplace("Accept-Encoding", "zstd");
  6341. std::string body;
  6342. auto res = cli_.Get("/nocompress", headers,
  6343. [&](const char *data, uint64_t data_length) {
  6344. EXPECT_EQ(100U, data_length);
  6345. body.append(data, data_length);
  6346. return true;
  6347. });
  6348. ASSERT_TRUE(res);
  6349. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6350. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6351. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6352. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6353. "7890123456789012345678901234567890",
  6354. body);
  6355. EXPECT_EQ(StatusCode::OK_200, res->status);
  6356. }
  6357. // TODO: How to enable zstd ??
  6358. TEST_F(ServerTest, MultipartFormDataZstd) {
  6359. UploadFormDataItems items = {
  6360. {"key1", "test", "", ""},
  6361. {"key2", "--abcdefg123", "", ""},
  6362. };
  6363. Headers headers;
  6364. headers.emplace("Accept-Encoding", "zstd");
  6365. cli_.set_compress(true);
  6366. auto res = cli_.Post("/compress-multipart", headers, items);
  6367. ASSERT_TRUE(res);
  6368. EXPECT_EQ(StatusCode::OK_200, res->status);
  6369. }
  6370. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  6371. Headers headers;
  6372. headers.emplace("Accept-Encoding", "zstd");
  6373. cli_.set_compress(true);
  6374. auto res = cli_.Put(
  6375. "/put", headers, 3,
  6376. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6377. sink.os << "PUT";
  6378. return true;
  6379. },
  6380. "text/plain");
  6381. ASSERT_TRUE(res);
  6382. EXPECT_EQ(StatusCode::OK_200, res->status);
  6383. EXPECT_EQ("PUT", res->body);
  6384. }
  6385. // Pre-compression logging tests
  6386. TEST_F(ServerTest, PreCompressionLogging) {
  6387. // Test data for compression (matches the actual /compress endpoint content)
  6388. const std::string test_content =
  6389. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6390. "3456789012345678901234567890";
  6391. // Variables to capture logging data
  6392. std::string pre_compression_body;
  6393. std::string pre_compression_content_type;
  6394. std::string pre_compression_content_encoding;
  6395. std::string post_compression_body;
  6396. std::string post_compression_content_type;
  6397. std::string post_compression_content_encoding;
  6398. // Set up pre-compression logger
  6399. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  6400. const Response &res) {
  6401. pre_compression_body = res.body;
  6402. pre_compression_content_type = res.get_header_value("Content-Type");
  6403. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  6404. });
  6405. // Set up post-compression logger
  6406. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6407. post_compression_body = res.body;
  6408. post_compression_content_type = res.get_header_value("Content-Type");
  6409. post_compression_content_encoding =
  6410. res.get_header_value("Content-Encoding");
  6411. });
  6412. // Test with gzip compression
  6413. Headers headers;
  6414. headers.emplace("Accept-Encoding", "gzip");
  6415. auto res = cli_.Get("/compress", headers);
  6416. // Verify response was compressed
  6417. ASSERT_TRUE(res);
  6418. EXPECT_EQ(StatusCode::OK_200, res->status);
  6419. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6420. // Verify pre-compression logger captured uncompressed content
  6421. EXPECT_EQ(test_content, pre_compression_body);
  6422. EXPECT_EQ("text/plain", pre_compression_content_type);
  6423. EXPECT_TRUE(pre_compression_content_encoding
  6424. .empty()); // No encoding header before compression
  6425. // Verify post-compression logger captured compressed content
  6426. EXPECT_NE(test_content,
  6427. post_compression_body); // Should be different after compression
  6428. EXPECT_EQ("text/plain", post_compression_content_type);
  6429. EXPECT_EQ("gzip", post_compression_content_encoding);
  6430. // Verify compressed content is smaller
  6431. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  6432. }
  6433. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  6434. const std::string test_content =
  6435. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6436. "3456789012345678901234567890";
  6437. std::string pre_compression_body;
  6438. std::string post_compression_body;
  6439. svr_.set_pre_compression_logger(
  6440. [&](const Request & /*req*/, const Response &res) {
  6441. pre_compression_body = res.body;
  6442. });
  6443. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6444. post_compression_body = res.body;
  6445. });
  6446. Headers headers;
  6447. headers.emplace("Accept-Encoding", "br");
  6448. auto res = cli_.Get("/compress", headers);
  6449. ASSERT_TRUE(res);
  6450. EXPECT_EQ(StatusCode::OK_200, res->status);
  6451. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  6452. // Verify pre-compression content is uncompressed
  6453. EXPECT_EQ(test_content, pre_compression_body);
  6454. // Verify post-compression content is compressed
  6455. EXPECT_NE(test_content, post_compression_body);
  6456. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  6457. }
  6458. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  6459. const std::string test_content =
  6460. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6461. "3456789012345678901234567890";
  6462. std::string pre_compression_body;
  6463. std::string post_compression_body;
  6464. svr_.set_pre_compression_logger(
  6465. [&](const Request & /*req*/, const Response &res) {
  6466. pre_compression_body = res.body;
  6467. });
  6468. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6469. post_compression_body = res.body;
  6470. });
  6471. // Request without compression (use /nocompress endpoint)
  6472. Headers headers;
  6473. auto res = cli_.Get("/nocompress", headers);
  6474. ASSERT_TRUE(res);
  6475. EXPECT_EQ(StatusCode::OK_200, res->status);
  6476. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6477. // Pre-compression logger should not be called when no compression is applied
  6478. EXPECT_TRUE(
  6479. pre_compression_body.empty()); // Pre-compression logger not called
  6480. EXPECT_EQ(
  6481. test_content,
  6482. post_compression_body); // Post-compression logger captures final content
  6483. }
  6484. TEST_F(ServerTest, LoggerSeesContentLength) {
  6485. size_t logged_content_length = 0;
  6486. std::string logged_content_length_header;
  6487. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6488. logged_content_length = res.content_length_;
  6489. logged_content_length_header = res.get_header_value("Content-Length");
  6490. });
  6491. auto res = cli_.Get("/nocompress");
  6492. ASSERT_TRUE(res);
  6493. EXPECT_EQ(StatusCode::OK_200, res->status);
  6494. EXPECT_EQ(res->body.size(), logged_content_length);
  6495. EXPECT_EQ(std::to_string(logged_content_length),
  6496. logged_content_length_header);
  6497. }
  6498. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  6499. const std::string test_content =
  6500. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6501. "3456789012345678901234567890";
  6502. std::string pre_compression_body;
  6503. bool pre_logger_called = false;
  6504. // Set only pre-compression logger
  6505. svr_.set_pre_compression_logger(
  6506. [&](const Request & /*req*/, const Response &res) {
  6507. pre_compression_body = res.body;
  6508. pre_logger_called = true;
  6509. });
  6510. Headers headers;
  6511. headers.emplace("Accept-Encoding", "gzip");
  6512. auto res = cli_.Get("/compress", headers);
  6513. ASSERT_TRUE(res);
  6514. EXPECT_EQ(StatusCode::OK_200, res->status);
  6515. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6516. // Verify pre-compression logger was called
  6517. EXPECT_TRUE(pre_logger_called);
  6518. EXPECT_EQ(test_content, pre_compression_body);
  6519. }
  6520. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  6521. {
  6522. // Test with Expect: 100-continue header - success case
  6523. // Server returns 100 Continue, client sends body, server returns 200 OK
  6524. Request req;
  6525. req.method = "POST";
  6526. req.path = "/post-large";
  6527. req.set_header("Expect", "100-continue");
  6528. req.body = LARGE_DATA;
  6529. Response res;
  6530. auto error = Error::Success;
  6531. cli_.set_keep_alive(true);
  6532. auto ret = cli_.send(req, res, error);
  6533. EXPECT_TRUE(ret);
  6534. EXPECT_EQ(StatusCode::OK_200, res.status);
  6535. EXPECT_EQ(LARGE_DATA, res.body);
  6536. }
  6537. {
  6538. // Test with Expect: 100-continue header - error case
  6539. // Client should not send the body when server returns an error
  6540. Request req;
  6541. req.method = "POST";
  6542. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  6543. req.set_header("Expect", "100-continue");
  6544. req.body = LARGE_DATA;
  6545. Response res;
  6546. auto error = Error::Success;
  6547. auto start = std::chrono::high_resolution_clock::now();
  6548. cli_.set_keep_alive(true);
  6549. auto ret = cli_.send(req, res, error);
  6550. auto end = std::chrono::high_resolution_clock::now();
  6551. auto elapsed =
  6552. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6553. .count();
  6554. // With Expect: 100-continue, request completes successfully but with error
  6555. EXPECT_TRUE(ret);
  6556. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  6557. EXPECT_EQ("close", res.get_header_value("Connection"));
  6558. EXPECT_FALSE(cli_.is_socket_open());
  6559. EXPECT_LE(elapsed, 2000);
  6560. }
  6561. {
  6562. // Send an extra GET request to ensure error recovery without hanging
  6563. Request req;
  6564. req.method = "GET";
  6565. req.path = "/hi";
  6566. auto start = std::chrono::high_resolution_clock::now();
  6567. auto res = cli_.send(req);
  6568. auto end = std::chrono::high_resolution_clock::now();
  6569. auto elapsed =
  6570. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6571. .count();
  6572. ASSERT_TRUE(res);
  6573. EXPECT_EQ(StatusCode::OK_200, res->status);
  6574. EXPECT_EQ("Hello World!", res->body);
  6575. EXPECT_LE(elapsed, 500);
  6576. }
  6577. }
  6578. TEST(ZstdDecompressor, ChunkedDecompression) {
  6579. std::string data;
  6580. for (size_t i = 0; i < 32 * 1024; ++i) {
  6581. data.push_back(static_cast<char>('a' + i % 26));
  6582. }
  6583. std::string compressed_data;
  6584. {
  6585. httplib::detail::zstd_compressor compressor;
  6586. bool result = compressor.compress(
  6587. data.data(), data.size(),
  6588. /*last=*/true,
  6589. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  6590. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  6591. compressed_data_size);
  6592. return true;
  6593. });
  6594. ASSERT_TRUE(result);
  6595. }
  6596. std::string decompressed_data;
  6597. {
  6598. httplib::detail::zstd_decompressor decompressor;
  6599. // Chunk size is chosen specifically to have a decompressed chunk size equal
  6600. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  6601. size_t chunk_size = 130;
  6602. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  6603. chunk_begin += chunk_size) {
  6604. size_t current_chunk_size =
  6605. std::min(compressed_data.size() - chunk_begin, chunk_size);
  6606. bool result = decompressor.decompress(
  6607. compressed_data.data() + chunk_begin, current_chunk_size,
  6608. [&](const char *decompressed_data_chunk,
  6609. size_t decompressed_data_chunk_size) {
  6610. decompressed_data.insert(decompressed_data.size(),
  6611. decompressed_data_chunk,
  6612. decompressed_data_chunk_size);
  6613. return true;
  6614. });
  6615. ASSERT_TRUE(result);
  6616. }
  6617. }
  6618. ASSERT_EQ(data, decompressed_data);
  6619. }
  6620. TEST(ZstdDecompressor, Decompress) {
  6621. std::string original_text = "Compressed with ZSTD";
  6622. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  6623. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  6624. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  6625. 0x20, 0x5a, 0x53, 0x54, 0x44};
  6626. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6627. std::string decompressed_data;
  6628. {
  6629. httplib::detail::zstd_decompressor decompressor;
  6630. bool result = decompressor.decompress(
  6631. compressed_data.data(), compressed_data.size(),
  6632. [&](const char *decompressed_data_chunk,
  6633. size_t decompressed_data_chunk_size) {
  6634. decompressed_data.insert(decompressed_data.size(),
  6635. decompressed_data_chunk,
  6636. decompressed_data_chunk_size);
  6637. return true;
  6638. });
  6639. ASSERT_TRUE(result);
  6640. }
  6641. ASSERT_EQ(original_text, decompressed_data);
  6642. }
  6643. #endif
  6644. // Sends a raw request to a server listening at HOST:PORT.
  6645. static bool send_request(time_t read_timeout_sec, const std::string &req,
  6646. std::string *resp = nullptr) {
  6647. auto error = Error::Success;
  6648. auto client_sock = detail::create_client_socket(
  6649. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  6650. /*connection_timeout_sec=*/5, 0,
  6651. /*read_timeout_sec=*/5, 0,
  6652. /*write_timeout_sec=*/5, 0, std::string(), error);
  6653. if (client_sock == INVALID_SOCKET) { return false; }
  6654. auto ret = detail::process_client_socket(
  6655. client_sock, read_timeout_sec, 0, 0, 0, 0,
  6656. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  6657. if (req.size() !=
  6658. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  6659. return false;
  6660. }
  6661. char buf[512];
  6662. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  6663. while (line_reader.getline()) {
  6664. if (resp) { *resp += line_reader.ptr(); }
  6665. }
  6666. return true;
  6667. });
  6668. detail::close_socket(client_sock);
  6669. return ret;
  6670. }
  6671. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  6672. Server svr;
  6673. std::string header_value;
  6674. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  6675. header_value = req.get_header_value("foo");
  6676. res.set_content("ok", "text/plain");
  6677. });
  6678. thread t = thread([&] { svr.listen(HOST, PORT); });
  6679. auto se = detail::scope_exit([&] {
  6680. svr.stop();
  6681. t.join();
  6682. ASSERT_FALSE(svr.is_running());
  6683. });
  6684. svr.wait_until_ready();
  6685. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  6686. // like characters are not treated the same - use vertical tab and escape.
  6687. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  6688. "foo: \t \v bar \x1B\t \r\n"
  6689. "Connection: close\r\n"
  6690. "\r\n";
  6691. std::string res;
  6692. ASSERT_TRUE(send_request(5, req, &res));
  6693. EXPECT_EQ(header_value, "");
  6694. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  6695. }
  6696. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  6697. Server svr;
  6698. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  6699. auto i = new int(0);
  6700. res.set_header("Trailer", "X-Safe, X-Reflected");
  6701. res.set_chunked_content_provider(
  6702. "text/plain",
  6703. [i](size_t /*offset*/, DataSink &sink) {
  6704. if (*i == 0) {
  6705. sink.os << "body";
  6706. } else {
  6707. Headers trailer;
  6708. // A valid trailer that must survive.
  6709. trailer.emplace("X-Safe", "safe");
  6710. // Attacker-controlled value carrying CR/LF (response splitting).
  6711. trailer.emplace("X-Reflected",
  6712. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  6713. // Attacker-controlled name carrying CR/LF.
  6714. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  6715. sink.done_with_trailer(trailer);
  6716. }
  6717. (*i)++;
  6718. return true;
  6719. },
  6720. [i](bool /*success*/) { delete i; });
  6721. });
  6722. thread t = thread([&] { svr.listen(HOST, PORT); });
  6723. auto se = detail::scope_exit([&] {
  6724. svr.stop();
  6725. t.join();
  6726. ASSERT_FALSE(svr.is_running());
  6727. });
  6728. svr.wait_until_ready();
  6729. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  6730. "Host: " + HOST +
  6731. "\r\n"
  6732. "Connection: close\r\n"
  6733. "\r\n";
  6734. std::string res;
  6735. ASSERT_TRUE(send_request(5, req, &res));
  6736. // The injected fields must not appear anywhere in the raw response.
  6737. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  6738. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  6739. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  6740. // Invalid trailers are dropped entirely, matching set_header().
  6741. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  6742. // The valid trailer still passes through.
  6743. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  6744. }
  6745. // Forward declaration: in split builds split.py strips `inline` and moves the
  6746. // definition into httplib.cc, so detail::write_request_line is not visible from
  6747. // the public httplib.h. Re-declaring it here lets the tests link against the
  6748. // symbol in both header-only and split builds.
  6749. namespace httplib {
  6750. namespace detail {
  6751. ssize_t write_request_line(Stream &strm, const std::string &method,
  6752. const std::string &path);
  6753. } // namespace detail
  6754. } // namespace httplib
  6755. TEST(RequestLineInjectionTest, RejectsCRLFInTarget) {
  6756. // A well-formed target is written verbatim.
  6757. {
  6758. detail::BufferStream strm;
  6759. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  6760. EXPECT_GT(n, 0);
  6761. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  6762. }
  6763. // A target carrying CR/LF must be rejected before anything reaches the wire,
  6764. // otherwise it splits the request line and injects a header or a whole
  6765. // request. This is what a decoded redirect Location ("%0D%0A") turns into
  6766. // when path encoding is disabled.
  6767. const std::string evil_targets[] = {
  6768. "/a\r\nInjected: pwned",
  6769. "/a\rInjected",
  6770. "/a\nInjected",
  6771. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  6772. };
  6773. for (const auto &evil : evil_targets) {
  6774. detail::BufferStream strm;
  6775. auto n = detail::write_request_line(strm, "GET", evil);
  6776. EXPECT_LT(n, 0);
  6777. EXPECT_TRUE(strm.get_buffer().empty());
  6778. }
  6779. }
  6780. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  6781. // End-to-end counterpart to RejectsCRLFInTarget. With path encoding disabled
  6782. // the client transmits the target verbatim, so a CR/LF-bearing target -- what
  6783. // a redirect Location "%0D%0A" decodes to -- reaches write_request. The
  6784. // client must fail cleanly with Error::Write instead of putting a
  6785. // request-line-less, header-injecting request on the wire.
  6786. Server svr;
  6787. svr.Get("/a", [](const Request &, Response &res) {
  6788. res.set_content("ok", "text/plain");
  6789. });
  6790. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6791. auto se = detail::scope_exit([&] {
  6792. svr.stop();
  6793. thread.join();
  6794. ASSERT_FALSE(svr.is_running());
  6795. });
  6796. svr.wait_until_ready();
  6797. {
  6798. Client cli(HOST, PORT);
  6799. cli.set_path_encode(false);
  6800. // The request is rejected before anything is written, so the connection
  6801. // stays silent and the subsequent response read would otherwise block for
  6802. // the full default read timeout. Shorten it -- the assertion is on the
  6803. // error, not the timeout.
  6804. cli.set_read_timeout(1, 0);
  6805. auto res = cli.Get("/a\r\nInjected: pwned");
  6806. EXPECT_FALSE(res);
  6807. EXPECT_EQ(Error::Write, res.error());
  6808. }
  6809. }
  6810. // Sends a raw request and verifies that there isn't a crash or exception.
  6811. static void test_raw_request(const std::string &req,
  6812. std::string *out = nullptr) {
  6813. Server svr;
  6814. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6815. res.set_content("ok", "text/plain");
  6816. });
  6817. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  6818. res.set_content("ok", "text/plain");
  6819. });
  6820. svr.Get("/header_field_value_check",
  6821. [&](const Request & /*req*/, Response &res) {
  6822. res.set_content("ok", "text/plain");
  6823. });
  6824. // Server read timeout must be longer than the client read timeout for the
  6825. // bug to reproduce, probably to force the server to process a request
  6826. // without a trailing blank line.
  6827. const time_t client_read_timeout_sec = 1;
  6828. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  6829. bool listen_thread_ok = false;
  6830. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  6831. auto se = detail::scope_exit([&] {
  6832. svr.stop();
  6833. t.join();
  6834. ASSERT_FALSE(svr.is_running());
  6835. EXPECT_TRUE(listen_thread_ok);
  6836. });
  6837. svr.wait_until_ready();
  6838. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  6839. }
  6840. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  6841. // A certain header line causes an exception if the header property is parsed
  6842. // naively with a single regex. This occurs with libc++ but not libstdc++.
  6843. test_raw_request(
  6844. "GET /hi HTTP/1.1\r\n"
  6845. " : "
  6846. " "
  6847. " ");
  6848. }
  6849. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  6850. // A certain header line causes an exception if the header property *name* is
  6851. // parsed with a regular expression starting with "(.+?):" - this is a non-
  6852. // greedy matcher and requires backtracking when there are a lot of ":"
  6853. // characters.
  6854. // This occurs with libc++ but not libstdc++.
  6855. test_raw_request(
  6856. "GET /hi HTTP/1.1\r\n"
  6857. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  6858. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  6859. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  6860. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  6861. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  6862. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  6863. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  6864. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  6865. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  6866. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  6867. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  6868. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  6869. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  6870. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  6871. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  6872. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  6873. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  6874. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  6875. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  6876. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  6877. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  6878. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  6879. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  6880. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  6881. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  6882. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  6883. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  6884. "&&&%%%");
  6885. }
  6886. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  6887. // Make sure this doesn't crash the server.
  6888. // In a previous version of the header line regex, the "\r" rendered the line
  6889. // unparsable and the regex engine repeatedly backtracked, trying to look for
  6890. // a new position where the leading white space ended and the field value
  6891. // began.
  6892. // The crash occurs with libc++ but not libstdc++.
  6893. test_raw_request("GET /hi HTTP/1.1\r\n"
  6894. "a:" +
  6895. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  6896. "\r\n"
  6897. "\r\n");
  6898. }
  6899. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  6900. std::string out;
  6901. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6902. "Content-Type: text/plain\r\n"
  6903. "Transfer-Encoding: chunked\r\n"
  6904. "\r\n"
  6905. "nothex\r\n",
  6906. &out);
  6907. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6908. }
  6909. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  6910. std::string out;
  6911. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6912. "Content-Type: text/plain\r\n"
  6913. "Transfer-Encoding: chunked\r\n"
  6914. "\r\n"
  6915. "3\r\n"
  6916. "xyz\r\n"
  6917. "NaN\r\n",
  6918. &out);
  6919. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6920. }
  6921. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  6922. std::string out;
  6923. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6924. "Content-Type: text/plain\r\n"
  6925. "Transfer-Encoding: chunked\r\n"
  6926. "\r\n"
  6927. // Length is too large for 64 bits.
  6928. "1ffffffffffffffff\r\n"
  6929. "xyz\r\n",
  6930. &out);
  6931. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6932. }
  6933. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  6934. test_raw_request("GET /hi HTTP/1.1\r\n"
  6935. "Content-Type: text/plain\r\n\r");
  6936. }
  6937. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  6938. std::string out;
  6939. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  6940. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6941. }
  6942. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  6943. Server svr;
  6944. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  6945. EXPECT_TRUE(!req.remote_addr.empty());
  6946. });
  6947. thread t = thread([&] { svr.listen(HOST, PORT); });
  6948. auto se = detail::scope_exit([&] {
  6949. svr.stop();
  6950. t.join();
  6951. ASSERT_FALSE(svr.is_running());
  6952. });
  6953. svr.wait_until_ready();
  6954. // Send an invalid request line to trigger Bad Request
  6955. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  6956. std::string out;
  6957. ASSERT_TRUE(send_request(5, bad_req, &out));
  6958. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6959. }
  6960. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  6961. std::string out;
  6962. std::string request(
  6963. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  6964. test_raw_request(request, &out);
  6965. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6966. }
  6967. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  6968. std::string out;
  6969. std::string request(
  6970. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  6971. test_raw_request(request, &out);
  6972. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6973. }
  6974. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  6975. std::string out;
  6976. std::string request(
  6977. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  6978. test_raw_request(request, &out);
  6979. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6980. }
  6981. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  6982. std::string out;
  6983. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  6984. "Test: \r\n\r\n",
  6985. &out);
  6986. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  6987. }
  6988. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  6989. Server svr;
  6990. std::string x_custom;
  6991. std::string cookie;
  6992. std::string xff;
  6993. std::string x_unicode;
  6994. std::string x_iis;
  6995. svr.Get("/check", [&](const Request &req, Response &res) {
  6996. x_custom = req.get_header_value("X-Custom");
  6997. cookie = req.get_header_value("Cookie");
  6998. xff = req.get_header_value("X-Forwarded-For");
  6999. x_unicode = req.get_header_value("X-Unicode");
  7000. x_iis = req.get_header_value("X-IIS");
  7001. res.set_content("ok", "text/plain");
  7002. });
  7003. thread t = thread([&] { svr.listen(HOST, PORT); });
  7004. auto se = detail::scope_exit([&] {
  7005. svr.stop();
  7006. t.join();
  7007. ASSERT_FALSE(svr.is_running());
  7008. });
  7009. svr.wait_until_ready();
  7010. const std::string req = "GET /check HTTP/1.1\r\n"
  7011. "Host: localhost\r\n"
  7012. "X-Custom: a%0D%0AInjected: b\r\n"
  7013. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  7014. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  7015. "X-Unicode: %E3%81%82\r\n"
  7016. "X-IIS: %u00E9\r\n"
  7017. "Connection: close\r\n"
  7018. "\r\n";
  7019. std::string res;
  7020. ASSERT_TRUE(send_request(5, req, &res));
  7021. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7022. // Every value must be returned verbatim (wire form), with no decoding.
  7023. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  7024. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  7025. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  7026. EXPECT_EQ("%E3%81%82", x_unicode);
  7027. EXPECT_EQ("%u00E9", x_iis);
  7028. }
  7029. // Applications that previously relied on automatic percent-decoding can
  7030. // reproduce the old behavior by explicitly calling decode_path_component()
  7031. // or, for RFC 3986 conformance, decode_uri_component().
  7032. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  7033. Server svr;
  7034. std::string decoded;
  7035. svr.Get("/check", [&](const Request &req, Response &res) {
  7036. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  7037. res.set_content("ok", "text/plain");
  7038. });
  7039. thread t = thread([&] { svr.listen(HOST, PORT); });
  7040. auto se = detail::scope_exit([&] {
  7041. svr.stop();
  7042. t.join();
  7043. ASSERT_FALSE(svr.is_running());
  7044. });
  7045. svr.wait_until_ready();
  7046. const std::string req = "GET /check HTTP/1.1\r\n"
  7047. "Host: localhost\r\n"
  7048. "X-Custom: hello%20world\r\n"
  7049. "Connection: close\r\n"
  7050. "\r\n";
  7051. std::string res;
  7052. ASSERT_TRUE(send_request(5, req, &res));
  7053. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7054. EXPECT_EQ("hello world", decoded);
  7055. }
  7056. // Regression test for #2033. Browsers send Referer values that include
  7057. // percent-encoded characters such as %0A inside the URL. Decoding the
  7058. // header value would either trip the post-decode CR/LF/NUL guard (the
  7059. // original bug, returning 400) or, after that guard was relaxed, silently
  7060. // store a literal LF — both unacceptable. The wire form must round-trip.
  7061. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  7062. Server svr;
  7063. std::string referer;
  7064. svr.Get("/check", [&](const Request &req, Response &res) {
  7065. referer = req.get_header_value("Referer");
  7066. res.set_content("ok", "text/plain");
  7067. });
  7068. thread t = thread([&] { svr.listen(HOST, PORT); });
  7069. auto se = detail::scope_exit([&] {
  7070. svr.stop();
  7071. t.join();
  7072. ASSERT_FALSE(svr.is_running());
  7073. });
  7074. svr.wait_until_ready();
  7075. const std::string req = "GET /check HTTP/1.1\r\n"
  7076. "Host: localhost\r\n"
  7077. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  7078. "Connection: close\r\n"
  7079. "\r\n";
  7080. std::string res;
  7081. ASSERT_TRUE(send_request(5, req, &res));
  7082. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7083. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  7084. }
  7085. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  7086. Server svr;
  7087. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  7088. res.set_header("Cache-Control", "no-cache");
  7089. res.set_chunked_content_provider(
  7090. "text/event-stream", [](size_t offset, DataSink &sink) {
  7091. std::string s = "data:";
  7092. s += std::to_string(offset);
  7093. s += "\n\n";
  7094. auto ret = sink.write(s.data(), s.size());
  7095. EXPECT_TRUE(ret);
  7096. std::this_thread::sleep_for(std::chrono::seconds(1));
  7097. return true;
  7098. });
  7099. });
  7100. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7101. svr.wait_until_ready();
  7102. Client client(HOST, PORT);
  7103. const Headers headers = {{"Accept", "text/event-stream"}};
  7104. auto get_thread = std::thread([&client, &headers]() {
  7105. auto res = client.Get(
  7106. "/events", headers,
  7107. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  7108. });
  7109. auto se = detail::scope_exit([&] {
  7110. svr.stop();
  7111. get_thread.join();
  7112. listen_thread.join();
  7113. ASSERT_FALSE(svr.is_running());
  7114. });
  7115. // Give GET time to get a few messages.
  7116. std::this_thread::sleep_for(std::chrono::seconds(2));
  7117. }
  7118. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  7119. httplib::Server svr;
  7120. svr.Post("/hi",
  7121. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  7122. res.status = StatusCode::OK_200;
  7123. });
  7124. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7125. svr.wait_until_ready();
  7126. Client cli(HOST, PORT);
  7127. auto res = cli.Post("/hi", "data", "text/plain");
  7128. ASSERT_TRUE(res);
  7129. EXPECT_EQ(StatusCode::OK_200, res->status);
  7130. svr.stop();
  7131. thread.join();
  7132. ASSERT_FALSE(svr.is_running());
  7133. res = cli.Post("/hi", "data", "text/plain");
  7134. ASSERT_FALSE(res);
  7135. }
  7136. TEST(ServerStopTest, ListenFailure) {
  7137. Server svr;
  7138. auto t = thread([&]() {
  7139. auto ret = svr.listen("????", PORT);
  7140. EXPECT_FALSE(ret);
  7141. });
  7142. svr.wait_until_ready();
  7143. svr.stop();
  7144. t.join();
  7145. }
  7146. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  7147. TEST(ServerStopTest, Decommision) {
  7148. Server svr;
  7149. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  7150. for (int i = 0; i < 4; i++) {
  7151. auto is_even = !(i % 2);
  7152. std::thread t{[&] {
  7153. try {
  7154. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  7155. if (is_even) {
  7156. throw std::runtime_error("Some thing that happens to go wrong.");
  7157. }
  7158. svr.listen(HOST, PORT);
  7159. } catch (...) { svr.decommission(); }
  7160. }};
  7161. svr.wait_until_ready();
  7162. // Server is up
  7163. {
  7164. Client cli(HOST, PORT);
  7165. auto res = cli.Get("/hi");
  7166. if (is_even) {
  7167. EXPECT_FALSE(res);
  7168. } else {
  7169. EXPECT_TRUE(res);
  7170. EXPECT_EQ("hi...", res->body);
  7171. }
  7172. }
  7173. svr.stop();
  7174. t.join();
  7175. // Server is down...
  7176. {
  7177. Client cli(HOST, PORT);
  7178. auto res = cli.Get("/hi");
  7179. EXPECT_FALSE(res);
  7180. }
  7181. }
  7182. }
  7183. #endif
  7184. // Helper function for string body upload progress tests
  7185. template <typename SetupHandler, typename ClientCall>
  7186. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  7187. ClientCall &&client_call,
  7188. const string &body) {
  7189. Server svr;
  7190. setup_handler(svr);
  7191. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7192. auto se = detail::scope_exit([&] {
  7193. svr.stop();
  7194. t.join();
  7195. });
  7196. svr.wait_until_ready();
  7197. Client cli(HOST, PORT);
  7198. vector<uint64_t> progress_values;
  7199. bool progress_called = false;
  7200. auto res =
  7201. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  7202. progress_values.push_back(current);
  7203. progress_called = true;
  7204. return true;
  7205. });
  7206. ASSERT_TRUE(res);
  7207. EXPECT_EQ(200, res->status);
  7208. EXPECT_TRUE(progress_called);
  7209. }
  7210. TEST(UploadProgressTest, PostStringBodyBasic) {
  7211. TestStringBodyUploadProgress(
  7212. [](Server &svr) {
  7213. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  7214. res.set_content("received", "text/plain");
  7215. });
  7216. },
  7217. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7218. return cli.Post("/test", body, "text/plain", progress_callback);
  7219. },
  7220. "test data for upload progress");
  7221. }
  7222. TEST(UploadProgressTest, PutStringBodyBasic) {
  7223. TestStringBodyUploadProgress(
  7224. [](Server &svr) {
  7225. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  7226. res.set_content("put received", "text/plain");
  7227. });
  7228. },
  7229. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7230. return cli.Put("/test", body, "text/plain", progress_callback);
  7231. },
  7232. "put test data for upload progress");
  7233. }
  7234. TEST(UploadProgressTest, PatchStringBodyBasic) {
  7235. TestStringBodyUploadProgress(
  7236. [](Server &svr) {
  7237. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  7238. res.set_content("patch received", "text/plain");
  7239. });
  7240. },
  7241. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7242. return cli.Patch("/test", body, "text/plain", progress_callback);
  7243. },
  7244. "patch test data for upload progress");
  7245. }
  7246. // Helper function for content provider upload progress tests
  7247. template <typename SetupHandler, typename ClientCall>
  7248. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  7249. ClientCall &&client_call) {
  7250. Server svr;
  7251. setup_handler(svr);
  7252. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7253. auto se = detail::scope_exit([&] {
  7254. svr.stop();
  7255. t.join();
  7256. });
  7257. svr.wait_until_ready();
  7258. Client cli(HOST, PORT);
  7259. vector<uint64_t> progress_values;
  7260. auto res =
  7261. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  7262. progress_values.push_back(current);
  7263. return true;
  7264. });
  7265. ASSERT_TRUE(res);
  7266. EXPECT_EQ(200, res->status);
  7267. EXPECT_FALSE(progress_values.empty());
  7268. }
  7269. TEST(UploadProgressTest, PostContentProviderProgress) {
  7270. TestContentProviderUploadProgress(
  7271. [](Server &svr) {
  7272. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  7273. res.set_content("provider received", "text/plain");
  7274. });
  7275. },
  7276. [](Client &cli, UploadProgress progress_callback) {
  7277. return cli.Post(
  7278. "/test", 10,
  7279. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  7280. sink.os << "test data";
  7281. return true;
  7282. },
  7283. "text/plain", progress_callback);
  7284. });
  7285. }
  7286. // Helper function for multipart upload progress tests
  7287. template <typename SetupHandler, typename ClientCall>
  7288. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  7289. ClientCall &&client_call,
  7290. const string &endpoint) {
  7291. Server svr;
  7292. setup_handler(svr);
  7293. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7294. auto se = detail::scope_exit([&] {
  7295. svr.stop();
  7296. t.join();
  7297. });
  7298. svr.wait_until_ready();
  7299. Client cli(HOST, PORT);
  7300. vector<uint64_t> progress_values;
  7301. UploadFormDataItems items = {
  7302. {"field1", "value1", "", ""},
  7303. {"field2", "longer value for progress tracking test", "", ""},
  7304. {"file1", "file content data for upload progress", "test.txt",
  7305. "text/plain"}};
  7306. auto res = client_call(cli, endpoint, items,
  7307. [&](uint64_t current, uint64_t /*total*/) -> bool {
  7308. progress_values.push_back(current);
  7309. return true;
  7310. });
  7311. ASSERT_TRUE(res);
  7312. EXPECT_EQ(200, res->status);
  7313. EXPECT_FALSE(progress_values.empty());
  7314. }
  7315. TEST(UploadProgressTest, PostMultipartProgress) {
  7316. TestMultipartUploadProgress(
  7317. [](Server &svr) {
  7318. svr.Post("/multipart", [](const Request &req, Response &res) {
  7319. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  7320. res.set_content("multipart received", "text/plain");
  7321. });
  7322. },
  7323. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  7324. UploadProgress progress_callback) {
  7325. return cli.Post(endpoint, items, progress_callback);
  7326. },
  7327. "/multipart");
  7328. }
  7329. // Helper function for basic download progress tests
  7330. template <typename SetupHandler, typename ClientCall>
  7331. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  7332. ClientCall &&client_call, const string &endpoint,
  7333. size_t expected_content_size) {
  7334. Server svr;
  7335. setup_handler(svr);
  7336. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7337. auto se = detail::scope_exit([&] {
  7338. svr.stop();
  7339. t.join();
  7340. });
  7341. svr.wait_until_ready();
  7342. Client cli(HOST, PORT);
  7343. vector<uint64_t> progress_values;
  7344. auto res = client_call(cli, endpoint,
  7345. [&](uint64_t current, uint64_t /*total*/) -> bool {
  7346. progress_values.push_back(current);
  7347. return true;
  7348. });
  7349. ASSERT_TRUE(res);
  7350. EXPECT_EQ(200, res->status);
  7351. EXPECT_FALSE(progress_values.empty());
  7352. EXPECT_EQ(expected_content_size, res->body.size());
  7353. }
  7354. TEST(DownloadProgressTest, GetBasic) {
  7355. TestBasicDownloadProgress(
  7356. [](Server &svr) {
  7357. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  7358. string content(1000, 'D');
  7359. res.set_content(content, "text/plain");
  7360. });
  7361. },
  7362. [](Client &cli, const string &endpoint,
  7363. DownloadProgress progress_callback) {
  7364. return cli.Get(endpoint, progress_callback);
  7365. },
  7366. "/download", 1000u);
  7367. }
  7368. // Helper function for content receiver download progress tests
  7369. template <typename SetupHandler, typename ClientCall>
  7370. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  7371. ClientCall &&client_call,
  7372. const string &endpoint,
  7373. size_t expected_content_size) {
  7374. Server svr;
  7375. setup_handler(svr);
  7376. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7377. auto se = detail::scope_exit([&] {
  7378. svr.stop();
  7379. t.join();
  7380. });
  7381. svr.wait_until_ready();
  7382. Client cli(HOST, PORT);
  7383. vector<uint64_t> progress_values;
  7384. string received_body;
  7385. auto res = client_call(
  7386. cli, endpoint,
  7387. [&](const char *data, size_t data_length) -> bool {
  7388. received_body.append(data, data_length);
  7389. return true;
  7390. },
  7391. [&](uint64_t current, uint64_t /*total*/) -> bool {
  7392. progress_values.push_back(current);
  7393. return true;
  7394. });
  7395. ASSERT_TRUE(res);
  7396. EXPECT_EQ(200, res->status);
  7397. EXPECT_FALSE(progress_values.empty());
  7398. EXPECT_EQ(expected_content_size, received_body.size());
  7399. EXPECT_TRUE(res->body.empty());
  7400. }
  7401. TEST(DownloadProgressTest, GetWithContentReceiver) {
  7402. TestContentReceiverDownloadProgress(
  7403. [](Server &svr) {
  7404. svr.Get("/download-receiver",
  7405. [](const Request & /*req*/, Response &res) {
  7406. string content(2000, 'R');
  7407. res.set_content(content, "text/plain");
  7408. });
  7409. },
  7410. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  7411. DownloadProgress progress_callback) {
  7412. return cli.Get(endpoint, content_receiver, progress_callback);
  7413. },
  7414. "/download-receiver", 2000u);
  7415. }
  7416. TEST(StreamingTest, NoContentLengthStreaming) {
  7417. Server svr;
  7418. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  7419. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  7420. if (offset < 6) {
  7421. sink.os << (offset < 3 ? "a" : "b");
  7422. } else {
  7423. sink.done();
  7424. }
  7425. return true;
  7426. });
  7427. });
  7428. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7429. auto listen_se = detail::scope_exit([&] {
  7430. svr.stop();
  7431. listen_thread.join();
  7432. ASSERT_FALSE(svr.is_running());
  7433. });
  7434. svr.wait_until_ready();
  7435. Client client(HOST, PORT);
  7436. auto get_thread = std::thread([&client]() {
  7437. std::string s;
  7438. auto res =
  7439. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  7440. s += std::string(data, len);
  7441. return true;
  7442. });
  7443. ASSERT_TRUE(res);
  7444. EXPECT_EQ(StatusCode::OK_200, res->status);
  7445. EXPECT_EQ("aaabbb", s);
  7446. });
  7447. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  7448. // Give GET time to get a few messages.
  7449. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  7450. }
  7451. TEST(MountTest, Unmount) {
  7452. Server svr;
  7453. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7454. auto se = detail::scope_exit([&] {
  7455. svr.stop();
  7456. listen_thread.join();
  7457. ASSERT_FALSE(svr.is_running());
  7458. });
  7459. svr.wait_until_ready();
  7460. Client cli("localhost", PORT);
  7461. svr.set_mount_point("/mount2", "./www2");
  7462. auto res = cli.Get("/");
  7463. ASSERT_TRUE(res);
  7464. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7465. res = cli.Get("/mount2/dir/test.html");
  7466. ASSERT_TRUE(res);
  7467. EXPECT_EQ(StatusCode::OK_200, res->status);
  7468. svr.set_mount_point("/", "./www");
  7469. res = cli.Get("/dir/");
  7470. ASSERT_TRUE(res);
  7471. EXPECT_EQ(StatusCode::OK_200, res->status);
  7472. svr.remove_mount_point("/");
  7473. res = cli.Get("/dir/");
  7474. ASSERT_TRUE(res);
  7475. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7476. svr.remove_mount_point("/mount2");
  7477. res = cli.Get("/mount2/dir/test.html");
  7478. ASSERT_TRUE(res);
  7479. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7480. }
  7481. TEST(MountTest, Redicect) {
  7482. Server svr;
  7483. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7484. auto se = detail::scope_exit([&] {
  7485. svr.stop();
  7486. listen_thread.join();
  7487. ASSERT_FALSE(svr.is_running());
  7488. });
  7489. svr.set_mount_point("/", "./www");
  7490. svr.wait_until_ready();
  7491. Client cli("localhost", PORT);
  7492. auto res = cli.Get("/dir/");
  7493. ASSERT_TRUE(res);
  7494. EXPECT_EQ(StatusCode::OK_200, res->status);
  7495. res = cli.Get("/dir");
  7496. ASSERT_TRUE(res);
  7497. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7498. res = cli.Get("/file");
  7499. ASSERT_TRUE(res);
  7500. EXPECT_EQ(StatusCode::OK_200, res->status);
  7501. res = cli.Get("/file/");
  7502. ASSERT_TRUE(res);
  7503. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7504. cli.set_follow_location(true);
  7505. res = cli.Get("/dir");
  7506. ASSERT_TRUE(res);
  7507. EXPECT_EQ(StatusCode::OK_200, res->status);
  7508. }
  7509. TEST(MountTest, MultibytesPathName) {
  7510. Server svr;
  7511. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7512. auto se = detail::scope_exit([&] {
  7513. svr.stop();
  7514. listen_thread.join();
  7515. ASSERT_FALSE(svr.is_running());
  7516. });
  7517. svr.set_mount_point("/", "./www");
  7518. svr.wait_until_ready();
  7519. Client cli("localhost", PORT);
  7520. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  7521. ASSERT_TRUE(res);
  7522. EXPECT_EQ(StatusCode::OK_200, res->status);
  7523. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  7524. }
  7525. #ifdef _WIN32
  7526. // Issue #2435: mmap::open() must succeed even when another handle holds
  7527. // the file open for writing (e.g. an active log file).
  7528. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  7529. const char *path = "mmap_concurrent_writer_test.txt";
  7530. const char *content = "hello";
  7531. {
  7532. std::ofstream f(path, std::ios::binary);
  7533. f.write(content, static_cast<std::streamsize>(strlen(content)));
  7534. }
  7535. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  7536. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  7537. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  7538. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  7539. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  7540. detail::mmap m(path);
  7541. ASSERT_TRUE(m.is_open());
  7542. EXPECT_EQ(strlen(content), m.size());
  7543. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  7544. }
  7545. #endif
  7546. TEST(KeepAliveTest, ReadTimeout) {
  7547. Server svr;
  7548. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  7549. std::this_thread::sleep_for(std::chrono::seconds(2));
  7550. res.set_content("a", "text/plain");
  7551. });
  7552. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  7553. res.set_content("b", "text/plain");
  7554. });
  7555. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7556. auto se = detail::scope_exit([&] {
  7557. svr.stop();
  7558. listen_thread.join();
  7559. ASSERT_FALSE(svr.is_running());
  7560. });
  7561. svr.wait_until_ready();
  7562. Client cli("localhost", PORT);
  7563. cli.set_keep_alive(true);
  7564. cli.set_read_timeout(std::chrono::seconds(1));
  7565. auto resa = cli.Get("/a");
  7566. ASSERT_FALSE(resa);
  7567. EXPECT_EQ(Error::Read, resa.error());
  7568. auto resb = cli.Get("/b");
  7569. ASSERT_TRUE(resb);
  7570. EXPECT_EQ(StatusCode::OK_200, resb->status);
  7571. EXPECT_EQ("b", resb->body);
  7572. }
  7573. TEST(KeepAliveTest, MaxCount) {
  7574. size_t keep_alive_max_count = 3;
  7575. Server svr;
  7576. svr.set_keep_alive_max_count(keep_alive_max_count);
  7577. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  7578. res.set_content("Hello World!", "text/plain");
  7579. });
  7580. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7581. auto se = detail::scope_exit([&] {
  7582. svr.stop();
  7583. listen_thread.join();
  7584. ASSERT_FALSE(svr.is_running());
  7585. });
  7586. svr.wait_until_ready();
  7587. Client cli(HOST, PORT);
  7588. cli.set_keep_alive(true);
  7589. for (size_t i = 0; i < 5; i++) {
  7590. auto result = cli.Get("/hi");
  7591. ASSERT_TRUE(result);
  7592. EXPECT_EQ(StatusCode::OK_200, result->status);
  7593. if (i == keep_alive_max_count - 1) {
  7594. EXPECT_EQ("close", result->get_header_value("Connection"));
  7595. } else {
  7596. EXPECT_FALSE(result->has_header("Connection"));
  7597. }
  7598. }
  7599. }
  7600. TEST(KeepAliveTest, Issue1041) {
  7601. Server svr;
  7602. svr.set_keep_alive_timeout(3);
  7603. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  7604. res.set_content("Hello World!", "text/plain");
  7605. });
  7606. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7607. auto se = detail::scope_exit([&] {
  7608. svr.stop();
  7609. listen_thread.join();
  7610. ASSERT_FALSE(svr.is_running());
  7611. });
  7612. svr.wait_until_ready();
  7613. Client cli(HOST, PORT);
  7614. cli.set_keep_alive(true);
  7615. auto result = cli.Get("/hi");
  7616. ASSERT_TRUE(result);
  7617. EXPECT_EQ(StatusCode::OK_200, result->status);
  7618. std::this_thread::sleep_for(std::chrono::seconds(5));
  7619. result = cli.Get("/hi");
  7620. ASSERT_TRUE(result);
  7621. EXPECT_EQ(StatusCode::OK_200, result->status);
  7622. }
  7623. TEST(KeepAliveTest, Issue1959) {
  7624. Server svr;
  7625. svr.set_keep_alive_timeout(5);
  7626. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  7627. res.set_content("a", "text/plain");
  7628. });
  7629. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7630. auto se = detail::scope_exit([&] {
  7631. if (!svr.is_running()) return;
  7632. svr.stop();
  7633. listen_thread.join();
  7634. ASSERT_FALSE(svr.is_running());
  7635. });
  7636. svr.wait_until_ready();
  7637. Client cli("localhost", PORT);
  7638. cli.set_keep_alive(true);
  7639. using namespace std::chrono;
  7640. auto start = steady_clock::now();
  7641. cli.Get("/a");
  7642. svr.stop();
  7643. listen_thread.join();
  7644. auto end = steady_clock::now();
  7645. auto elapsed = duration_cast<milliseconds>(end - start).count();
  7646. EXPECT_LT(elapsed, 5000);
  7647. }
  7648. #ifdef CPPHTTPLIB_SSL_ENABLED
  7649. TEST(KeepAliveTest, SSLClientReconnection) {
  7650. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7651. ASSERT_TRUE(svr.is_valid());
  7652. svr.set_keep_alive_timeout(1);
  7653. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  7654. res.set_content("Hello World!", "text/plain");
  7655. });
  7656. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7657. auto se = detail::scope_exit([&] {
  7658. svr.stop();
  7659. listen_thread.join();
  7660. ASSERT_FALSE(svr.is_running());
  7661. });
  7662. svr.wait_until_ready();
  7663. SSLClient cli(HOST, PORT);
  7664. cli.enable_server_certificate_verification(false);
  7665. cli.set_keep_alive(true);
  7666. auto result = cli.Get("/hi");
  7667. ASSERT_TRUE(result);
  7668. EXPECT_EQ(StatusCode::OK_200, result->status);
  7669. result = cli.Get("/hi");
  7670. ASSERT_TRUE(result);
  7671. EXPECT_EQ(StatusCode::OK_200, result->status);
  7672. std::this_thread::sleep_for(std::chrono::seconds(2));
  7673. // Recoonect
  7674. result = cli.Get("/hi");
  7675. ASSERT_TRUE(result);
  7676. EXPECT_EQ(StatusCode::OK_200, result->status);
  7677. result = cli.Get("/hi");
  7678. ASSERT_TRUE(result);
  7679. EXPECT_EQ(StatusCode::OK_200, result->status);
  7680. }
  7681. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  7682. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7683. ASSERT_TRUE(svr.is_valid());
  7684. svr.set_keep_alive_timeout(1);
  7685. std::string content = "reconnect";
  7686. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  7687. res.set_content("Hello World!", "text/plain");
  7688. });
  7689. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7690. auto se = detail::scope_exit([&] {
  7691. svr.stop();
  7692. listen_thread.join();
  7693. ASSERT_FALSE(svr.is_running());
  7694. });
  7695. svr.wait_until_ready();
  7696. SSLClient cli(HOST, PORT);
  7697. cli.enable_server_certificate_verification(false);
  7698. cli.set_keep_alive(true);
  7699. auto result = cli.Post(
  7700. "/hi", content.size(),
  7701. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7702. sink.write(content.c_str(), content.size());
  7703. return true;
  7704. },
  7705. "text/plain");
  7706. ASSERT_TRUE(result);
  7707. EXPECT_EQ(200, result->status);
  7708. std::this_thread::sleep_for(std::chrono::seconds(2));
  7709. // Recoonect
  7710. result = cli.Post(
  7711. "/hi", content.size(),
  7712. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7713. sink.write(content.c_str(), content.size());
  7714. return true;
  7715. },
  7716. "text/plain");
  7717. ASSERT_TRUE(result);
  7718. EXPECT_EQ(200, result->status);
  7719. result = cli.Post(
  7720. "/hi", content.size(),
  7721. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7722. sink.write(content.c_str(), content.size());
  7723. return true;
  7724. },
  7725. "text/plain");
  7726. ASSERT_TRUE(result);
  7727. EXPECT_EQ(200, result->status);
  7728. }
  7729. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  7730. using namespace httplib::tls;
  7731. {
  7732. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7733. ASSERT_TRUE(svr.is_valid());
  7734. svr.Get("/sni", [&](const Request &req, Response &res) {
  7735. std::string expected = req.sni();
  7736. EXPECT_EQ(expected, req.get_param_value("expected"));
  7737. res.set_content("ok", "text/plain");
  7738. });
  7739. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7740. auto se = detail::scope_exit([&] {
  7741. svr.stop();
  7742. listen_thread.join();
  7743. ASSERT_FALSE(svr.is_running());
  7744. });
  7745. svr.wait_until_ready();
  7746. {
  7747. SSLClient cli("localhost", PORT);
  7748. cli.enable_server_certificate_verification(false);
  7749. auto res = cli.Get("/sni?expected=localhost");
  7750. ASSERT_TRUE(res);
  7751. }
  7752. {
  7753. SSLClient cli("::1", PORT);
  7754. cli.enable_server_certificate_verification(false);
  7755. auto res = cli.Get("/sni?expected=");
  7756. // NOTE: This may fail if the server is listening on IPv4 only
  7757. // (e.g., when localhost resolves to 127.0.0.1 only)
  7758. if (res) {
  7759. EXPECT_EQ(StatusCode::OK_200, res->status);
  7760. } else {
  7761. EXPECT_EQ(Error::Connection, res.error());
  7762. }
  7763. }
  7764. }
  7765. }
  7766. #endif
  7767. TEST(ClientProblemDetectionTest, ContentProvider) {
  7768. Server svr;
  7769. size_t content_length = 1024 * 1024;
  7770. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7771. res.set_content_provider(
  7772. content_length, "text/plain",
  7773. [&](size_t offset, size_t length, DataSink &sink) {
  7774. auto out_len = std::min(length, static_cast<size_t>(1024));
  7775. std::string out(out_len, '@');
  7776. sink.write(out.data(), out_len);
  7777. return offset < 4096;
  7778. },
  7779. [](bool success) { ASSERT_FALSE(success); });
  7780. });
  7781. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  7782. res.set_content_provider(
  7783. 0, "text/plain",
  7784. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  7785. EXPECT_TRUE(false);
  7786. return true;
  7787. },
  7788. [](bool success) { ASSERT_FALSE(success); });
  7789. });
  7790. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7791. auto se = detail::scope_exit([&] {
  7792. svr.stop();
  7793. listen_thread.join();
  7794. ASSERT_FALSE(svr.is_running());
  7795. });
  7796. svr.wait_until_ready();
  7797. Client cli("localhost", PORT);
  7798. {
  7799. auto res = cli.Get("/hi", [&](const char * /*data*/,
  7800. size_t /*data_length*/) { return false; });
  7801. ASSERT_FALSE(res);
  7802. }
  7803. {
  7804. auto res = cli.Get("/empty", [&](const char * /*data*/,
  7805. size_t /*data_length*/) { return false; });
  7806. ASSERT_TRUE(res);
  7807. }
  7808. }
  7809. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  7810. Server svr;
  7811. svr.set_error_handler([](Request const &, Response &res) -> void {
  7812. res.set_chunked_content_provider(
  7813. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  7814. sink.os << "hello";
  7815. sink.os << "world";
  7816. sink.done();
  7817. return true;
  7818. });
  7819. });
  7820. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7821. auto se = detail::scope_exit([&] {
  7822. svr.stop();
  7823. listen_thread.join();
  7824. ASSERT_FALSE(svr.is_running());
  7825. });
  7826. svr.wait_until_ready();
  7827. Client cli("localhost", PORT);
  7828. auto res = cli.Get("/");
  7829. ASSERT_TRUE(res);
  7830. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7831. EXPECT_EQ("helloworld", res->body);
  7832. }
  7833. TEST(LongPollingTest, ClientCloseDetection) {
  7834. Server svr;
  7835. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  7836. res.set_chunked_content_provider(
  7837. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  7838. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  7839. sink.os << "hello";
  7840. auto count = 10;
  7841. while (count > 0 && sink.is_writable()) {
  7842. this_thread::sleep_for(chrono::milliseconds(10));
  7843. count--;
  7844. }
  7845. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  7846. return true;
  7847. });
  7848. });
  7849. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7850. auto se = detail::scope_exit([&] {
  7851. svr.stop();
  7852. listen_thread.join();
  7853. ASSERT_FALSE(svr.is_running());
  7854. });
  7855. svr.wait_until_ready();
  7856. Client cli("localhost", PORT);
  7857. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  7858. EXPECT_EQ("hello", string(data, data_length));
  7859. return false; // close the socket immediately.
  7860. });
  7861. ASSERT_FALSE(res);
  7862. }
  7863. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  7864. Server svr;
  7865. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  7866. res.set_chunked_content_provider(
  7867. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  7868. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  7869. sink.os << "hello";
  7870. EXPECT_TRUE(sink.os.good());
  7871. // Wait for the client to close the connection
  7872. auto count = 10;
  7873. while (count > 0 && sink.is_writable()) {
  7874. this_thread::sleep_for(chrono::milliseconds(10));
  7875. count--;
  7876. }
  7877. // After client disconnect, write repeatedly until the socket
  7878. // write actually fails (small writes may be absorbed by the
  7879. // kernel buffer)
  7880. std::string chunk(1024, 'x');
  7881. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  7882. sink.os << chunk;
  7883. }
  7884. EXPECT_TRUE(sink.os.fail());
  7885. return true;
  7886. });
  7887. });
  7888. auto port = svr.bind_to_any_port("localhost");
  7889. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  7890. auto se = detail::scope_exit([&] {
  7891. svr.stop();
  7892. listen_thread.join();
  7893. ASSERT_FALSE(svr.is_running());
  7894. });
  7895. svr.wait_until_ready();
  7896. Client cli("localhost", port);
  7897. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  7898. EXPECT_EQ("hello", string(data, data_length));
  7899. return false; // close the socket immediately.
  7900. });
  7901. ASSERT_FALSE(res);
  7902. }
  7903. TEST(GetWithParametersTest, GetWithParameters) {
  7904. Server svr;
  7905. svr.Get("/", [&](const Request &req, Response &) {
  7906. EXPECT_EQ("world", req.get_param_value("hello"));
  7907. EXPECT_EQ("world2", req.get_param_value("hello2"));
  7908. EXPECT_EQ("world3", req.get_param_value("hello3"));
  7909. });
  7910. svr.Get("/params", [&](const Request &req, Response &) {
  7911. EXPECT_EQ("world", req.get_param_value("hello"));
  7912. EXPECT_EQ("world2", req.get_param_value("hello2"));
  7913. EXPECT_EQ("world3", req.get_param_value("hello3"));
  7914. });
  7915. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  7916. EXPECT_EQ("resource-id", req.matches[1]);
  7917. EXPECT_EQ("foo", req.get_param_value("param1"));
  7918. EXPECT_EQ("bar", req.get_param_value("param2"));
  7919. });
  7920. svr.Get("/users/:id", [&](const Request &req, Response &) {
  7921. EXPECT_EQ("user-id", req.path_params.at("id"));
  7922. EXPECT_EQ("foo", req.get_param_value("param1"));
  7923. EXPECT_EQ("bar", req.get_param_value("param2"));
  7924. });
  7925. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  7926. auto se = detail::scope_exit([&] {
  7927. svr.stop();
  7928. listen_thread.join();
  7929. ASSERT_FALSE(svr.is_running());
  7930. });
  7931. svr.wait_until_ready();
  7932. {
  7933. Client cli(HOST, PORT);
  7934. Params params;
  7935. params.emplace("hello", "world");
  7936. params.emplace("hello2", "world2");
  7937. params.emplace("hello3", "world3");
  7938. auto res = cli.Get("/", params, Headers{});
  7939. ASSERT_TRUE(res);
  7940. EXPECT_EQ(StatusCode::OK_200, res->status);
  7941. }
  7942. {
  7943. Client cli(HOST, PORT);
  7944. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  7945. ASSERT_TRUE(res);
  7946. EXPECT_EQ(StatusCode::OK_200, res->status);
  7947. }
  7948. {
  7949. Client cli(HOST, PORT);
  7950. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  7951. ASSERT_TRUE(res);
  7952. EXPECT_EQ(StatusCode::OK_200, res->status);
  7953. }
  7954. {
  7955. Client cli(HOST, PORT);
  7956. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  7957. ASSERT_TRUE(res);
  7958. EXPECT_EQ(StatusCode::OK_200, res->status);
  7959. }
  7960. }
  7961. TEST(GetWithParametersTest, GetWithParameters2) {
  7962. Server svr;
  7963. svr.Get("/", [&](const Request &req, Response &res) {
  7964. auto text = req.get_param_value("hello");
  7965. res.set_content(text, "text/plain");
  7966. });
  7967. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7968. auto se = detail::scope_exit([&] {
  7969. svr.stop();
  7970. listen_thread.join();
  7971. ASSERT_FALSE(svr.is_running());
  7972. });
  7973. svr.wait_until_ready();
  7974. Client cli("localhost", PORT);
  7975. Params params;
  7976. params.emplace("hello", "world");
  7977. std::string body;
  7978. auto res = cli.Get("/", params, Headers{},
  7979. [&](const char *data, size_t data_length) {
  7980. body.append(data, data_length);
  7981. return true;
  7982. });
  7983. ASSERT_TRUE(res);
  7984. EXPECT_EQ(StatusCode::OK_200, res->status);
  7985. EXPECT_EQ("world", body);
  7986. }
  7987. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  7988. Server svr;
  7989. svr.Get("/search", [&](const Request &req, Response &res) {
  7990. auto q = req.get_param_value("q");
  7991. res.set_content(q, "text/plain");
  7992. });
  7993. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7994. auto se = detail::scope_exit([&] {
  7995. svr.stop();
  7996. listen_thread.join();
  7997. ASSERT_FALSE(svr.is_running());
  7998. });
  7999. svr.wait_until_ready();
  8000. Client cli("localhost", PORT);
  8001. // Verify that Get(path, params) works without requiring Headers argument
  8002. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  8003. ASSERT_TRUE(res);
  8004. EXPECT_EQ(StatusCode::OK_200, res->status);
  8005. EXPECT_EQ("cpp-httplib", res->body);
  8006. }
  8007. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  8008. auto host = "httpbingo.org";
  8009. auto path = std::string{"/range/32"};
  8010. #ifdef CPPHTTPLIB_SSL_ENABLED
  8011. SSLClient cli(host);
  8012. #else
  8013. Client cli(host);
  8014. #endif
  8015. cli.set_default_headers({make_range_header({{1, 10}})});
  8016. cli.set_connection_timeout(5);
  8017. {
  8018. auto res = cli.Get(path);
  8019. ASSERT_TRUE(res);
  8020. EXPECT_EQ("bcdefghijk", res->body);
  8021. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8022. }
  8023. {
  8024. auto res = cli.Get(path);
  8025. ASSERT_TRUE(res);
  8026. EXPECT_EQ("bcdefghijk", res->body);
  8027. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8028. }
  8029. }
  8030. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  8031. Server svr;
  8032. svr.set_default_headers({{"Hello", "World"}});
  8033. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  8034. res.set_content("ok", "text/plain");
  8035. });
  8036. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8037. auto se = detail::scope_exit([&] {
  8038. svr.stop();
  8039. listen_thread.join();
  8040. ASSERT_FALSE(svr.is_running());
  8041. });
  8042. svr.wait_until_ready();
  8043. Client cli("localhost", PORT);
  8044. auto res = cli.Get("/");
  8045. ASSERT_TRUE(res);
  8046. EXPECT_EQ(StatusCode::OK_200, res->status);
  8047. EXPECT_EQ("ok", res->body);
  8048. EXPECT_EQ("World", res->get_header_value("Hello"));
  8049. }
  8050. #ifdef CPPHTTPLIB_SSL_ENABLED
  8051. TEST(KeepAliveTest, ReadTimeoutSSL) {
  8052. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8053. ASSERT_TRUE(svr.is_valid());
  8054. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  8055. std::this_thread::sleep_for(std::chrono::seconds(2));
  8056. res.set_content("a", "text/plain");
  8057. });
  8058. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  8059. res.set_content("b", "text/plain");
  8060. });
  8061. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8062. auto se = detail::scope_exit([&] {
  8063. svr.stop();
  8064. listen_thread.join();
  8065. ASSERT_FALSE(svr.is_running());
  8066. });
  8067. svr.wait_until_ready();
  8068. SSLClient cli("localhost", PORT);
  8069. cli.enable_server_certificate_verification(false);
  8070. cli.set_keep_alive(true);
  8071. cli.set_read_timeout(std::chrono::seconds(1));
  8072. auto resa = cli.Get("/a");
  8073. ASSERT_TRUE(!resa);
  8074. EXPECT_EQ(Error::Read, resa.error());
  8075. auto resb = cli.Get("/b");
  8076. ASSERT_TRUE(resb);
  8077. EXPECT_EQ(StatusCode::OK_200, resb->status);
  8078. EXPECT_EQ("b", resb->body);
  8079. }
  8080. #endif
  8081. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  8082. protected:
  8083. ServerTestWithAI_PASSIVE()
  8084. : cli_(HOST, PORT)
  8085. #ifdef CPPHTTPLIB_SSL_ENABLED
  8086. ,
  8087. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  8088. #endif
  8089. {
  8090. #ifdef CPPHTTPLIB_SSL_ENABLED
  8091. cli_.enable_server_certificate_verification(false);
  8092. #endif
  8093. }
  8094. virtual void SetUp() {
  8095. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  8096. res.set_content("Hello World!", "text/plain");
  8097. });
  8098. t_ = thread(
  8099. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  8100. svr_.wait_until_ready();
  8101. }
  8102. virtual void TearDown() {
  8103. svr_.stop();
  8104. t_.join();
  8105. }
  8106. #ifdef CPPHTTPLIB_SSL_ENABLED
  8107. SSLClient cli_;
  8108. SSLServer svr_;
  8109. #else
  8110. Client cli_;
  8111. Server svr_;
  8112. #endif
  8113. thread t_;
  8114. };
  8115. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  8116. auto res = cli_.Get("/hi");
  8117. ASSERT_TRUE(res);
  8118. EXPECT_EQ(StatusCode::OK_200, res->status);
  8119. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8120. EXPECT_EQ("Hello World!", res->body);
  8121. }
  8122. class ServerUpDownTest : public ::testing::Test {
  8123. protected:
  8124. ServerUpDownTest() : cli_(HOST, PORT) {}
  8125. virtual void SetUp() {
  8126. t_ = thread([&]() {
  8127. svr_.bind_to_any_port(HOST);
  8128. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  8129. ASSERT_TRUE(svr_.listen_after_bind());
  8130. });
  8131. svr_.wait_until_ready();
  8132. }
  8133. virtual void TearDown() {
  8134. svr_.stop();
  8135. t_.join();
  8136. }
  8137. Client cli_;
  8138. Server svr_;
  8139. thread t_;
  8140. };
  8141. TEST_F(ServerUpDownTest, QuickStartStop) {
  8142. // Should not crash, especially when run with
  8143. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  8144. }
  8145. class PayloadMaxLengthTest : public ::testing::Test {
  8146. protected:
  8147. PayloadMaxLengthTest()
  8148. : cli_(HOST, PORT)
  8149. #ifdef CPPHTTPLIB_SSL_ENABLED
  8150. ,
  8151. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  8152. #endif
  8153. {
  8154. #ifdef CPPHTTPLIB_SSL_ENABLED
  8155. cli_.enable_server_certificate_verification(false);
  8156. #endif
  8157. }
  8158. virtual void SetUp() {
  8159. svr_.set_payload_max_length(8);
  8160. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  8161. res.set_content("test", "text/plain");
  8162. });
  8163. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  8164. svr_.wait_until_ready();
  8165. }
  8166. virtual void TearDown() {
  8167. svr_.stop();
  8168. t_.join();
  8169. }
  8170. #ifdef CPPHTTPLIB_SSL_ENABLED
  8171. SSLClient cli_;
  8172. SSLServer svr_;
  8173. #else
  8174. Client cli_;
  8175. Server svr_;
  8176. #endif
  8177. thread t_;
  8178. };
  8179. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  8180. auto res = cli_.Post("/test", "123456789", "text/plain");
  8181. ASSERT_TRUE(res);
  8182. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8183. res = cli_.Post("/test", "12345678", "text/plain");
  8184. ASSERT_TRUE(res);
  8185. EXPECT_EQ(StatusCode::OK_200, res->status);
  8186. }
  8187. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  8188. // Test chunked encoding with payload exceeding the 8-byte limit
  8189. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  8190. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  8191. ASSERT_TRUE(res);
  8192. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8193. }
  8194. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  8195. // Test chunked encoding with payload within the 8-byte limit
  8196. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  8197. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  8198. ASSERT_TRUE(res);
  8199. EXPECT_EQ(StatusCode::OK_200, res->status);
  8200. }
  8201. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  8202. // Test using send_request to send chunked data exceeding payload limit
  8203. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  8204. "Host: " +
  8205. std::string(HOST) + ":" + std::to_string(PORT) +
  8206. "\r\n"
  8207. "Transfer-Encoding: chunked\r\n"
  8208. "Connection: close\r\n"
  8209. "\r\n"
  8210. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  8211. "0123456789\r\n"
  8212. "0\r\n" // End chunk
  8213. "\r\n";
  8214. std::string response;
  8215. bool result = send_request(1, chunked_request, &response);
  8216. if (!result) {
  8217. // If send_request fails, it might be because the server closed the
  8218. // connection due to payload limit enforcement, which is acceptable
  8219. SUCCEED()
  8220. << "Server rejected oversized chunked request (connection closed)";
  8221. } else {
  8222. // If we got a response, check if it's an error response or connection was
  8223. // closed early Short response length indicates connection was closed due to
  8224. // payload limit
  8225. if (response.length() <= 10) {
  8226. SUCCEED() << "Server closed connection for oversized chunked request";
  8227. } else {
  8228. // Check for error status codes
  8229. EXPECT_TRUE(response.find("413") != std::string::npos ||
  8230. response.find("Payload Too Large") != std::string::npos ||
  8231. response.find("400") != std::string::npos);
  8232. }
  8233. }
  8234. }
  8235. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  8236. // Test request without Content-Length header exceeding payload limit
  8237. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8238. "Host: " +
  8239. std::string(HOST) + ":" +
  8240. std::to_string(PORT) +
  8241. "\r\n"
  8242. "Connection: close\r\n"
  8243. "\r\n";
  8244. // Add payload exceeding the 8-byte limit
  8245. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  8246. request_without_content_length += large_payload;
  8247. std::string response;
  8248. bool result = send_request(1, request_without_content_length, &response);
  8249. if (!result) {
  8250. // If send_request fails, server likely closed connection due to payload
  8251. // limit
  8252. SUCCEED() << "Server rejected oversized request without Content-Length "
  8253. "(connection closed)";
  8254. } else {
  8255. // Check if server responded with error or closed connection early
  8256. if (response.length() <= 10) {
  8257. SUCCEED() << "Server closed connection for oversized request without "
  8258. "Content-Length";
  8259. } else {
  8260. // Check for error status codes
  8261. EXPECT_TRUE(response.find("413") != std::string::npos ||
  8262. response.find("Payload Too Large") != std::string::npos ||
  8263. response.find("400") != std::string::npos);
  8264. }
  8265. }
  8266. }
  8267. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  8268. // Test request without Content-Length header within payload limit
  8269. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8270. "Host: " +
  8271. std::string(HOST) + ":" +
  8272. std::to_string(PORT) +
  8273. "\r\n"
  8274. "Connection: close\r\n"
  8275. "\r\n";
  8276. // Add payload within the 8-byte limit
  8277. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  8278. request_without_content_length += small_payload;
  8279. std::string response;
  8280. bool result = send_request(1, request_without_content_length, &response);
  8281. // For requests without Content-Length, the server may have different behavior
  8282. // The key is that it should not reject due to payload limit for small
  8283. // payloads
  8284. if (result) {
  8285. // Check for any HTTP response (success or error, but not connection closed)
  8286. if (response.length() > 10) {
  8287. SUCCEED()
  8288. << "Server processed request without Content-Length within limit";
  8289. } else {
  8290. // Short response might indicate connection closed, which is acceptable
  8291. SUCCEED() << "Server closed connection for request without "
  8292. "Content-Length (acceptable behavior)";
  8293. }
  8294. } else {
  8295. // Connection failure might be due to protocol requirements
  8296. SUCCEED() << "Connection issue with request without Content-Length "
  8297. "(environment-specific)";
  8298. }
  8299. }
  8300. class LargePayloadMaxLengthTest : public ::testing::Test {
  8301. protected:
  8302. LargePayloadMaxLengthTest()
  8303. : cli_(HOST, PORT)
  8304. #ifdef CPPHTTPLIB_SSL_ENABLED
  8305. ,
  8306. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  8307. #endif
  8308. {
  8309. #ifdef CPPHTTPLIB_SSL_ENABLED
  8310. cli_.enable_server_certificate_verification(false);
  8311. #endif
  8312. }
  8313. virtual void SetUp() {
  8314. // Set 10MB payload limit
  8315. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  8316. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  8317. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  8318. res.set_content("Large payload test", "text/plain");
  8319. });
  8320. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  8321. svr_.wait_until_ready();
  8322. }
  8323. virtual void TearDown() {
  8324. svr_.stop();
  8325. t_.join();
  8326. }
  8327. #ifdef CPPHTTPLIB_SSL_ENABLED
  8328. SSLClient cli_;
  8329. SSLServer svr_;
  8330. #else
  8331. Client cli_;
  8332. Server svr_;
  8333. #endif
  8334. thread t_;
  8335. };
  8336. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  8337. // Test chunked encoding with payload within 10MB limit
  8338. std::string medium_payload(5 * 1024 * 1024,
  8339. 'A'); // 5MB payload, within 10MB limit
  8340. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  8341. ASSERT_TRUE(res);
  8342. EXPECT_EQ(StatusCode::OK_200, res->status);
  8343. }
  8344. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  8345. // Test chunked encoding with payload exceeding 10MB limit
  8346. std::string large_payload(12 * 1024 * 1024,
  8347. 'B'); // 12MB payload, exceeds 10MB limit
  8348. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  8349. // Server may either return 413 or close the connection
  8350. if (res) {
  8351. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8352. } else {
  8353. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  8354. }
  8355. }
  8356. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  8357. // Test request without Content-Length header within 10MB limit
  8358. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8359. "Host: " +
  8360. std::string(HOST) + ":" +
  8361. std::to_string(PORT) +
  8362. "\r\n"
  8363. "Connection: close\r\n"
  8364. "\r\n";
  8365. // Add 1MB payload (within 10MB limit)
  8366. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  8367. request_without_content_length += medium_payload;
  8368. std::string response;
  8369. bool result = send_request(5, request_without_content_length, &response);
  8370. if (result) {
  8371. // Should get a proper HTTP response for payloads within limit
  8372. if (response.length() > 10) {
  8373. SUCCEED() << "Server processed 1MB request without Content-Length within "
  8374. "10MB limit";
  8375. } else {
  8376. SUCCEED() << "Server closed connection (acceptable behavior for no "
  8377. "Content-Length)";
  8378. }
  8379. } else {
  8380. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  8381. }
  8382. }
  8383. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  8384. // Test request without Content-Length header exceeding 10MB limit
  8385. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8386. "Host: " +
  8387. std::string(HOST) + ":" +
  8388. std::to_string(PORT) +
  8389. "\r\n"
  8390. "Connection: close\r\n"
  8391. "\r\n";
  8392. // Add 12MB payload (exceeds 10MB limit)
  8393. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  8394. request_without_content_length += large_payload;
  8395. std::string response;
  8396. bool result = send_request(10, request_without_content_length, &response);
  8397. if (!result) {
  8398. // Server should close connection due to payload limit
  8399. SUCCEED() << "Server rejected 12MB request without Content-Length "
  8400. "(connection closed)";
  8401. } else {
  8402. // Check for error response
  8403. if (response.length() <= 10) {
  8404. SUCCEED()
  8405. << "Server closed connection for 12MB request exceeding 10MB limit";
  8406. } else {
  8407. EXPECT_TRUE(response.find("413") != std::string::npos ||
  8408. response.find("Payload Too Large") != std::string::npos ||
  8409. response.find("400") != std::string::npos);
  8410. }
  8411. }
  8412. }
  8413. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8414. // `payload_max_length` is not enforced on decompressed body in ContentReader
  8415. // path.
  8416. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  8417. Server svr;
  8418. const size_t LIMIT = 64 * 1024; // 64KB
  8419. svr.set_payload_max_length(LIMIT);
  8420. size_t total = 0;
  8421. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  8422. const ContentReader &content_reader) {
  8423. content_reader([&](const char * /*data*/, size_t len) {
  8424. total += len;
  8425. return true;
  8426. });
  8427. res.status = 200;
  8428. res.set_content("stream_ok", "text/plain");
  8429. });
  8430. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8431. auto se = detail::scope_exit([&] {
  8432. svr.stop();
  8433. thread.join();
  8434. ASSERT_FALSE(svr.is_running());
  8435. });
  8436. svr.wait_until_ready();
  8437. // Prepare 256KB raw data and gzip-compress it
  8438. std::string raw(256 * 1024, 'A');
  8439. std::string gz;
  8440. {
  8441. z_stream zs{};
  8442. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  8443. Z_DEFAULT_STRATEGY);
  8444. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  8445. zs.avail_in = static_cast<uInt>(raw.size());
  8446. char outbuf[4096];
  8447. int ret;
  8448. do {
  8449. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  8450. zs.avail_out = sizeof(outbuf);
  8451. ret = deflate(&zs, Z_FINISH);
  8452. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  8453. } while (ret != Z_STREAM_END);
  8454. deflateEnd(&zs);
  8455. }
  8456. Client cli(HOST, PORT);
  8457. cli.set_connection_timeout(std::chrono::seconds(5));
  8458. Headers headers = {{"Content-Encoding", "gzip"}};
  8459. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  8460. "application/octet-stream");
  8461. ASSERT_TRUE(res);
  8462. // Server must reject oversized decompressed payloads with 413.
  8463. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8464. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  8465. EXPECT_LE(total, LIMIT);
  8466. }
  8467. #endif
  8468. // Regression test for DoS vulnerability: a malicious server sending a response
  8469. // without Content-Length header must not cause unbounded memory consumption on
  8470. // the client side. The client should stop reading after a reasonable limit,
  8471. // similar to the server-side set_payload_max_length protection.
  8472. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  8473. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  8474. #ifndef _WIN32
  8475. signal(SIGPIPE, SIG_IGN);
  8476. #endif
  8477. auto server_thread = std::thread([] {
  8478. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  8479. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8480. default_socket_options(srv);
  8481. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8482. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8483. sockaddr_in addr{};
  8484. addr.sin_family = AF_INET;
  8485. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8486. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8487. int opt = 1;
  8488. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8489. #ifdef _WIN32
  8490. reinterpret_cast<const char *>(&opt),
  8491. #else
  8492. &opt,
  8493. #endif
  8494. sizeof(opt));
  8495. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8496. ::listen(srv, 1);
  8497. sockaddr_in cli_addr{};
  8498. socklen_t cli_len = sizeof(cli_addr);
  8499. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8500. if (cli != INVALID_SOCKET) {
  8501. char buf[4096];
  8502. ::recv(cli, buf, sizeof(buf), 0);
  8503. // Malicious response: no Content-Length, no chunked encoding
  8504. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8505. "Connection: close\r\n"
  8506. "\r\n";
  8507. ::send(cli,
  8508. #ifdef _WIN32
  8509. static_cast<const char *>(response_header.c_str()),
  8510. static_cast<int>(response_header.size()),
  8511. #else
  8512. response_header.c_str(), response_header.size(),
  8513. #endif
  8514. 0);
  8515. // Send 10MB of data
  8516. std::string chunk(64 * 1024, 'A');
  8517. size_t total_sent = 0;
  8518. while (total_sent < MALICIOUS_DATA_SIZE) {
  8519. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  8520. auto sent = ::send(cli,
  8521. #ifdef _WIN32
  8522. static_cast<const char *>(chunk.c_str()),
  8523. static_cast<int>(to_send),
  8524. #else
  8525. chunk.c_str(), to_send,
  8526. #endif
  8527. 0);
  8528. if (sent <= 0) break;
  8529. total_sent += static_cast<size_t>(sent);
  8530. }
  8531. detail::close_socket(cli);
  8532. }
  8533. detail::close_socket(srv);
  8534. });
  8535. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8536. size_t total_read = 0;
  8537. {
  8538. Client cli("127.0.0.1", PORT + 2);
  8539. cli.set_read_timeout(5, 0);
  8540. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  8541. auto stream = cli.open_stream("GET", "/malicious");
  8542. ASSERT_TRUE(stream.is_valid());
  8543. char buffer[64 * 1024];
  8544. ssize_t n;
  8545. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  8546. total_read += static_cast<size_t>(n);
  8547. }
  8548. } // StreamHandle and Client destroyed here, closing the socket
  8549. server_thread.join();
  8550. // With set_payload_max_length, the client must stop reading before consuming
  8551. // all 10MB. The read loop should be cut off at or near the configured limit.
  8552. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  8553. << "Client read " << total_read << " bytes, exceeding the configured "
  8554. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  8555. }
  8556. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  8557. // the entire response body without truncation.
  8558. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  8559. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  8560. #ifndef _WIN32
  8561. signal(SIGPIPE, SIG_IGN);
  8562. #endif
  8563. auto server_thread = std::thread([] {
  8564. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8565. default_socket_options(srv);
  8566. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8567. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8568. sockaddr_in addr{};
  8569. addr.sin_family = AF_INET;
  8570. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8571. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8572. int opt = 1;
  8573. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8574. #ifdef _WIN32
  8575. reinterpret_cast<const char *>(&opt),
  8576. #else
  8577. &opt,
  8578. #endif
  8579. sizeof(opt));
  8580. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8581. ::listen(srv, 1);
  8582. sockaddr_in cli_addr{};
  8583. socklen_t cli_len = sizeof(cli_addr);
  8584. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8585. if (cli != INVALID_SOCKET) {
  8586. char buf[4096];
  8587. ::recv(cli, buf, sizeof(buf), 0);
  8588. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8589. "Connection: close\r\n"
  8590. "\r\n";
  8591. ::send(cli,
  8592. #ifdef _WIN32
  8593. static_cast<const char *>(response_header.c_str()),
  8594. static_cast<int>(response_header.size()),
  8595. #else
  8596. response_header.c_str(), response_header.size(),
  8597. #endif
  8598. 0);
  8599. std::string chunk(64 * 1024, 'A');
  8600. size_t total_sent = 0;
  8601. while (total_sent < DATA_SIZE) {
  8602. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8603. auto sent = ::send(cli,
  8604. #ifdef _WIN32
  8605. static_cast<const char *>(chunk.c_str()),
  8606. static_cast<int>(to_send),
  8607. #else
  8608. chunk.c_str(), to_send,
  8609. #endif
  8610. 0);
  8611. if (sent <= 0) break;
  8612. total_sent += static_cast<size_t>(sent);
  8613. }
  8614. #ifdef _WIN32
  8615. ::shutdown(cli, SD_SEND);
  8616. #else
  8617. ::shutdown(cli, SHUT_WR);
  8618. #endif
  8619. // Drain until the client closes its end, ensuring all data is delivered
  8620. char drain[1024];
  8621. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  8622. detail::close_socket(cli);
  8623. }
  8624. detail::close_socket(srv);
  8625. });
  8626. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8627. size_t total_read = 0;
  8628. {
  8629. Client cli("127.0.0.1", PORT + 2);
  8630. cli.set_read_timeout(5, 0);
  8631. cli.set_payload_max_length(0); // 0 means no limit
  8632. auto stream = cli.open_stream("GET", "/data");
  8633. ASSERT_TRUE(stream.is_valid());
  8634. char buffer[64 * 1024];
  8635. ssize_t n;
  8636. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  8637. total_read += static_cast<size_t>(n);
  8638. }
  8639. }
  8640. server_thread.join();
  8641. EXPECT_EQ(total_read, DATA_SIZE)
  8642. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  8643. << " bytes without truncation, but only read " << total_read << " bytes.";
  8644. }
  8645. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  8646. // enormous Content-Length must not cause the client to pre-allocate a huge
  8647. // response body buffer. The reservation is capped at payload_max_length_, and
  8648. // the read itself fails when the body exceeds the limit.
  8649. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  8650. #ifndef _WIN32
  8651. signal(SIGPIPE, SIG_IGN);
  8652. #endif
  8653. auto server_thread = std::thread([] {
  8654. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8655. default_socket_options(srv);
  8656. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8657. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8658. sockaddr_in addr{};
  8659. addr.sin_family = AF_INET;
  8660. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8661. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8662. int opt = 1;
  8663. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8664. #ifdef _WIN32
  8665. reinterpret_cast<const char *>(&opt),
  8666. #else
  8667. &opt,
  8668. #endif
  8669. sizeof(opt));
  8670. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8671. ::listen(srv, 1);
  8672. sockaddr_in cli_addr{};
  8673. socklen_t cli_len = sizeof(cli_addr);
  8674. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8675. if (cli != INVALID_SOCKET) {
  8676. char buf[4096];
  8677. ::recv(cli, buf, sizeof(buf), 0);
  8678. // Malicious response: claim a 20GB body but send only a tiny payload.
  8679. std::string response = "HTTP/1.1 200 OK\r\n"
  8680. "Content-Length: 20000000000\r\n"
  8681. "\r\n"
  8682. "abc";
  8683. ::send(cli,
  8684. #ifdef _WIN32
  8685. static_cast<const char *>(response.c_str()),
  8686. static_cast<int>(response.size()),
  8687. #else
  8688. response.c_str(), response.size(),
  8689. #endif
  8690. 0);
  8691. detail::close_socket(cli);
  8692. }
  8693. detail::close_socket(srv);
  8694. });
  8695. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8696. {
  8697. Client cli("127.0.0.1", PORT + 2);
  8698. cli.set_read_timeout(5, 0);
  8699. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  8700. // result in a 20GB pre-allocation. The Get() call is expected to fail
  8701. // (server claims more bytes than payload_max_length permits), but it must
  8702. // not exhaust memory before getting there.
  8703. auto res = cli.Get("/malicious");
  8704. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  8705. }
  8706. server_thread.join();
  8707. }
  8708. // Verify that content_receiver bypasses the default payload_max_length,
  8709. // allowing streaming downloads larger than 100MB without requiring an explicit
  8710. // set_payload_max_length call.
  8711. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  8712. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  8713. #ifndef _WIN32
  8714. signal(SIGPIPE, SIG_IGN);
  8715. #endif
  8716. auto server_thread = std::thread([] {
  8717. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8718. default_socket_options(srv);
  8719. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8720. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8721. sockaddr_in addr{};
  8722. addr.sin_family = AF_INET;
  8723. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8724. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8725. int opt = 1;
  8726. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8727. #ifdef _WIN32
  8728. reinterpret_cast<const char *>(&opt),
  8729. #else
  8730. &opt,
  8731. #endif
  8732. sizeof(opt));
  8733. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8734. ::listen(srv, 1);
  8735. sockaddr_in cli_addr{};
  8736. socklen_t cli_len = sizeof(cli_addr);
  8737. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8738. if (cli != INVALID_SOCKET) {
  8739. char buf[4096];
  8740. ::recv(cli, buf, sizeof(buf), 0);
  8741. // Response with Content-Length larger than default 100MB limit
  8742. auto content_length = std::to_string(DATA_SIZE);
  8743. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8744. "Content-Length: " +
  8745. content_length +
  8746. "\r\n"
  8747. "Connection: close\r\n"
  8748. "\r\n";
  8749. ::send(cli,
  8750. #ifdef _WIN32
  8751. static_cast<const char *>(response_header.c_str()),
  8752. static_cast<int>(response_header.size()),
  8753. #else
  8754. response_header.c_str(), response_header.size(),
  8755. #endif
  8756. 0);
  8757. std::string chunk(64 * 1024, 'A');
  8758. size_t total_sent = 0;
  8759. while (total_sent < DATA_SIZE) {
  8760. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8761. auto sent = ::send(cli,
  8762. #ifdef _WIN32
  8763. static_cast<const char *>(chunk.c_str()),
  8764. static_cast<int>(to_send),
  8765. #else
  8766. chunk.c_str(), to_send,
  8767. #endif
  8768. 0);
  8769. if (sent <= 0) break;
  8770. total_sent += static_cast<size_t>(sent);
  8771. }
  8772. detail::close_socket(cli);
  8773. }
  8774. detail::close_socket(srv);
  8775. });
  8776. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8777. size_t total_received = 0;
  8778. {
  8779. Client cli("127.0.0.1", PORT + 2);
  8780. cli.set_read_timeout(10, 0);
  8781. // Do NOT call set_payload_max_length — use the default 100MB limit
  8782. auto res =
  8783. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  8784. total_received += data_length;
  8785. return true;
  8786. });
  8787. ASSERT_TRUE(res);
  8788. EXPECT_EQ(StatusCode::OK_200, res->status);
  8789. }
  8790. server_thread.join();
  8791. EXPECT_EQ(total_received, DATA_SIZE)
  8792. << "With content_receiver, the client should read all " << DATA_SIZE
  8793. << " bytes despite the default 100MB payload_max_length, but only read "
  8794. << total_received << " bytes.";
  8795. }
  8796. // Verify that an explicit set_payload_max_length smaller than the response is
  8797. // enforced even when a content_receiver is used.
  8798. TEST(ClientVulnerabilityTest,
  8799. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  8800. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  8801. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  8802. #ifndef _WIN32
  8803. signal(SIGPIPE, SIG_IGN);
  8804. #endif
  8805. auto server_thread = std::thread([] {
  8806. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8807. default_socket_options(srv);
  8808. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8809. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8810. sockaddr_in addr{};
  8811. addr.sin_family = AF_INET;
  8812. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8813. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8814. int opt = 1;
  8815. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8816. #ifdef _WIN32
  8817. reinterpret_cast<const char *>(&opt),
  8818. #else
  8819. &opt,
  8820. #endif
  8821. sizeof(opt));
  8822. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8823. ::listen(srv, 1);
  8824. sockaddr_in cli_addr{};
  8825. socklen_t cli_len = sizeof(cli_addr);
  8826. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8827. if (cli != INVALID_SOCKET) {
  8828. char buf[4096];
  8829. ::recv(cli, buf, sizeof(buf), 0);
  8830. auto content_length = std::to_string(DATA_SIZE);
  8831. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8832. "Content-Length: " +
  8833. content_length +
  8834. "\r\n"
  8835. "Connection: close\r\n"
  8836. "\r\n";
  8837. ::send(cli,
  8838. #ifdef _WIN32
  8839. static_cast<const char *>(response_header.c_str()),
  8840. static_cast<int>(response_header.size()),
  8841. #else
  8842. response_header.c_str(), response_header.size(),
  8843. #endif
  8844. 0);
  8845. std::string chunk(64 * 1024, 'A');
  8846. size_t total_sent = 0;
  8847. while (total_sent < DATA_SIZE) {
  8848. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8849. auto sent = ::send(cli,
  8850. #ifdef _WIN32
  8851. static_cast<const char *>(chunk.c_str()),
  8852. static_cast<int>(to_send),
  8853. #else
  8854. chunk.c_str(), to_send,
  8855. #endif
  8856. 0);
  8857. if (sent <= 0) break;
  8858. total_sent += static_cast<size_t>(sent);
  8859. }
  8860. detail::close_socket(cli);
  8861. }
  8862. detail::close_socket(srv);
  8863. });
  8864. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8865. size_t total_received = 0;
  8866. {
  8867. Client cli("127.0.0.1", PORT + 2);
  8868. cli.set_read_timeout(10, 0);
  8869. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  8870. auto res =
  8871. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  8872. total_received += data_length;
  8873. return true;
  8874. });
  8875. // Should fail because 200MB exceeds the explicit 150MB limit
  8876. EXPECT_FALSE(res);
  8877. }
  8878. server_thread.join();
  8879. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  8880. << "Client with content_receiver should respect the explicit "
  8881. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  8882. << total_received << " bytes.";
  8883. }
  8884. // Verify that an explicit set_payload_max_length larger than the response
  8885. // allows the content_receiver to read all data successfully.
  8886. TEST(ClientVulnerabilityTest,
  8887. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  8888. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  8889. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  8890. #ifndef _WIN32
  8891. signal(SIGPIPE, SIG_IGN);
  8892. #endif
  8893. auto server_thread = std::thread([] {
  8894. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8895. default_socket_options(srv);
  8896. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8897. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8898. sockaddr_in addr{};
  8899. addr.sin_family = AF_INET;
  8900. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8901. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8902. int opt = 1;
  8903. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8904. #ifdef _WIN32
  8905. reinterpret_cast<const char *>(&opt),
  8906. #else
  8907. &opt,
  8908. #endif
  8909. sizeof(opt));
  8910. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8911. ::listen(srv, 1);
  8912. sockaddr_in cli_addr{};
  8913. socklen_t cli_len = sizeof(cli_addr);
  8914. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8915. if (cli != INVALID_SOCKET) {
  8916. char buf[4096];
  8917. ::recv(cli, buf, sizeof(buf), 0);
  8918. auto content_length = std::to_string(DATA_SIZE);
  8919. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8920. "Content-Length: " +
  8921. content_length +
  8922. "\r\n"
  8923. "Connection: close\r\n"
  8924. "\r\n";
  8925. ::send(cli,
  8926. #ifdef _WIN32
  8927. static_cast<const char *>(response_header.c_str()),
  8928. static_cast<int>(response_header.size()),
  8929. #else
  8930. response_header.c_str(), response_header.size(),
  8931. #endif
  8932. 0);
  8933. std::string chunk(64 * 1024, 'A');
  8934. size_t total_sent = 0;
  8935. while (total_sent < DATA_SIZE) {
  8936. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8937. auto sent = ::send(cli,
  8938. #ifdef _WIN32
  8939. static_cast<const char *>(chunk.c_str()),
  8940. static_cast<int>(to_send),
  8941. #else
  8942. chunk.c_str(), to_send,
  8943. #endif
  8944. 0);
  8945. if (sent <= 0) break;
  8946. total_sent += static_cast<size_t>(sent);
  8947. }
  8948. #ifdef _WIN32
  8949. ::shutdown(cli, SD_SEND);
  8950. #else
  8951. ::shutdown(cli, SHUT_WR);
  8952. #endif
  8953. char drain[1024];
  8954. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  8955. detail::close_socket(cli);
  8956. }
  8957. detail::close_socket(srv);
  8958. });
  8959. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8960. size_t total_received = 0;
  8961. {
  8962. Client cli("127.0.0.1", PORT + 2);
  8963. cli.set_read_timeout(10, 0);
  8964. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  8965. auto res =
  8966. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  8967. total_received += data_length;
  8968. return true;
  8969. });
  8970. ASSERT_TRUE(res);
  8971. EXPECT_EQ(StatusCode::OK_200, res->status);
  8972. }
  8973. server_thread.join();
  8974. EXPECT_EQ(total_received, DATA_SIZE)
  8975. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  8976. << " bytes (larger than " << DATA_SIZE
  8977. << " bytes response), content_receiver should read all data, but only "
  8978. "read "
  8979. << total_received << " bytes.";
  8980. }
  8981. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  8982. // Regression test for "zip bomb" attack on the client side: a malicious server
  8983. // sends a small gzip-compressed response that decompresses to a huge payload.
  8984. // The client must enforce payload_max_length on the decompressed size.
  8985. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  8986. constexpr size_t DECOMPRESSED_SIZE =
  8987. 10 * 1024 * 1024; // 10MB after decompression
  8988. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  8989. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  8990. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  8991. std::string compressed;
  8992. {
  8993. httplib::detail::gzip_compressor compressor;
  8994. bool ok =
  8995. compressor.compress(uncompressed.data(), uncompressed.size(),
  8996. /*last=*/true, [&](const char *buf, size_t len) {
  8997. compressed.append(buf, len);
  8998. return true;
  8999. });
  9000. ASSERT_TRUE(ok);
  9001. }
  9002. // Sanity: compressed data should be much smaller than the decompressed size
  9003. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  9004. #ifndef _WIN32
  9005. signal(SIGPIPE, SIG_IGN);
  9006. #endif
  9007. // Set up the listening socket in the main thread so the server is guaranteed
  9008. // to be ready before the client connects (eliminates race condition).
  9009. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9010. default_socket_options(srv);
  9011. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9012. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9013. sockaddr_in addr{};
  9014. addr.sin_family = AF_INET;
  9015. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  9016. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9017. int opt = 1;
  9018. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9019. #ifdef _WIN32
  9020. reinterpret_cast<const char *>(&opt),
  9021. #else
  9022. &opt,
  9023. #endif
  9024. sizeof(opt));
  9025. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  9026. ASSERT_EQ(0, ::listen(srv, 1));
  9027. auto server_thread = std::thread([&compressed, srv] {
  9028. sockaddr_in cli_addr{};
  9029. socklen_t cli_len = sizeof(cli_addr);
  9030. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9031. if (cli != INVALID_SOCKET) {
  9032. // Read the full HTTP request (until \r\n\r\n)
  9033. char buf[4096];
  9034. size_t total = 0;
  9035. while (total < sizeof(buf)) {
  9036. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  9037. if (n <= 0) break;
  9038. total += static_cast<size_t>(n);
  9039. // Check for end of headers
  9040. if (total >= 4) {
  9041. std::string req(buf, total);
  9042. if (req.find("\r\n\r\n") != std::string::npos) break;
  9043. }
  9044. }
  9045. // Malicious response: gzip-compressed body, no Content-Length
  9046. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9047. "Content-Encoding: gzip\r\n"
  9048. "Connection: close\r\n"
  9049. "\r\n";
  9050. ::send(cli,
  9051. #ifdef _WIN32
  9052. static_cast<const char *>(response_header.c_str()),
  9053. static_cast<int>(response_header.size()),
  9054. #else
  9055. response_header.c_str(), response_header.size(),
  9056. #endif
  9057. 0);
  9058. // Send the compressed payload (small on the wire, huge when decompressed)
  9059. size_t total_sent = 0;
  9060. while (total_sent < compressed.size()) {
  9061. auto to_send = std::min(compressed.size() - total_sent,
  9062. static_cast<size_t>(64 * 1024));
  9063. auto sent =
  9064. ::send(cli,
  9065. #ifdef _WIN32
  9066. static_cast<const char *>(compressed.c_str() + total_sent),
  9067. static_cast<int>(to_send),
  9068. #else
  9069. compressed.c_str() + total_sent, to_send,
  9070. #endif
  9071. 0);
  9072. if (sent <= 0) break;
  9073. total_sent += static_cast<size_t>(sent);
  9074. }
  9075. detail::close_socket(cli);
  9076. }
  9077. });
  9078. auto se = detail::scope_exit([&] {
  9079. detail::close_socket(srv);
  9080. server_thread.join();
  9081. });
  9082. size_t total_decompressed = 0;
  9083. {
  9084. Client cli("127.0.0.1", PORT + 3);
  9085. cli.set_read_timeout(5, 0);
  9086. cli.set_decompress(true);
  9087. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  9088. auto stream = cli.open_stream("GET", "/zipbomb");
  9089. ASSERT_TRUE(stream.is_valid());
  9090. char buffer[64 * 1024];
  9091. ssize_t n;
  9092. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  9093. total_decompressed += static_cast<size_t>(n);
  9094. }
  9095. }
  9096. // The decompressed size must be capped by payload_max_length. Without
  9097. // protection, the client would decompress the full 10MB from a tiny
  9098. // compressed payload, enabling a zip bomb DoS attack.
  9099. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  9100. << "Client decompressed " << total_decompressed
  9101. << " bytes from a gzip response. The decompressed size should be "
  9102. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  9103. }
  9104. #endif
  9105. TEST(HostAndPortPropertiesTest, NoSSL) {
  9106. httplib::Client cli("www.google.com", 1234);
  9107. ASSERT_EQ("www.google.com", cli.host());
  9108. ASSERT_EQ(1234, cli.port());
  9109. }
  9110. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  9111. httplib::Client cli("www.google.com:1234");
  9112. ASSERT_EQ("www.google.com", cli.host());
  9113. ASSERT_EQ(1234, cli.port());
  9114. }
  9115. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  9116. // Port number that overflows int — should not crash, client becomes invalid
  9117. httplib::Client cli("http://www.google.com:99999999999999999999");
  9118. ASSERT_FALSE(cli.is_valid());
  9119. }
  9120. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  9121. // Port 99999 exceeds valid range (1-65535) — should not crash
  9122. httplib::Client cli("http://www.google.com:99999");
  9123. ASSERT_FALSE(cli.is_valid());
  9124. }
  9125. #ifdef CPPHTTPLIB_SSL_ENABLED
  9126. TEST(HostAndPortPropertiesTest, SSL) {
  9127. httplib::SSLClient cli("www.google.com");
  9128. ASSERT_EQ("www.google.com", cli.host());
  9129. ASSERT_EQ(443, cli.port());
  9130. }
  9131. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  9132. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  9133. std::string cert;
  9134. read_file(CA_CERT_FILE, cert);
  9135. httplib::SSLClient httplib_client("www.google.com");
  9136. // Load CA store first time
  9137. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  9138. // Load CA store second time (update)
  9139. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  9140. // Verify client is still valid and can make connections
  9141. httplib_client.enable_server_certificate_verification(true);
  9142. auto res = httplib_client.Get("/");
  9143. ASSERT_TRUE(res);
  9144. // Google may return 200 or 301 depending on various factors
  9145. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  9146. res->status == StatusCode::MovedPermanently_301);
  9147. }
  9148. TEST(SSLClientTest, ServerNameIndication_Online) {
  9149. auto host = "httpbingo.org";
  9150. auto path = std::string{"/get"};
  9151. SSLClient cli(host, 443);
  9152. auto res = cli.Get(path);
  9153. ASSERT_TRUE(res);
  9154. ASSERT_EQ(StatusCode::OK_200, res->status);
  9155. }
  9156. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  9157. // Use a site that will cause SSL verification failure due to self-signed cert
  9158. SSLClient cli("self-signed.badssl.com", 443);
  9159. cli.enable_server_certificate_verification(true);
  9160. auto res = cli.Get("/");
  9161. ASSERT_TRUE(!res);
  9162. EXPECT_EQ(Error::SSLServerVerification, res.error());
  9163. // Verify backend error is captured for SSLServerVerification
  9164. // This occurs when certificate verification fails
  9165. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  9166. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  9167. EXPECT_NE(0UL, res.ssl_backend_error());
  9168. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9169. // For OpenSSL, ssl_error is 0 for verification errors
  9170. EXPECT_EQ(0, res.ssl_error());
  9171. #if !defined(_WIN32) || \
  9172. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  9173. // On non-Windows or when Windows Schannel is disabled, the error comes
  9174. // from OpenSSL's verification
  9175. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  9176. res.ssl_backend_error());
  9177. #endif
  9178. #endif
  9179. }
  9180. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  9181. // Use a site where hostname doesn't match the certificate
  9182. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  9183. SSLClient cli("wrong.host.badssl.com", 443);
  9184. cli.enable_server_certificate_verification(true);
  9185. cli.enable_server_hostname_verification(true);
  9186. auto res = cli.Get("/");
  9187. ASSERT_TRUE(!res);
  9188. // The error type depends on when hostname verification occurs:
  9189. // - OpenSSL: SSLServerHostnameVerification (post-handshake verification)
  9190. // - Mbed TLS: SSLServerVerification (during handshake)
  9191. EXPECT_TRUE(res.error() == Error::SSLServerHostnameVerification ||
  9192. res.error() == Error::SSLServerVerification);
  9193. // Verify backend error is captured for hostname verification failure
  9194. EXPECT_NE(0UL, res.ssl_backend_error());
  9195. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9196. // For OpenSSL, ssl_error is 0 for verification errors
  9197. EXPECT_EQ(0, res.ssl_error());
  9198. #if !defined(_WIN32) || \
  9199. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  9200. // On non-Windows or when Windows Schannel is disabled, the error comes
  9201. // from OpenSSL's hostname verification
  9202. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  9203. res.ssl_backend_error());
  9204. #endif
  9205. #endif
  9206. }
  9207. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  9208. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  9209. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  9210. SSLClient cli("www.google.com", 443);
  9211. cli.enable_server_certificate_verification(true);
  9212. auto res = cli.Get("/");
  9213. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  9214. }
  9215. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  9216. SSLClient cli("www.google.com", 443);
  9217. cli.enable_server_certificate_verification(true);
  9218. cli.enable_windows_certificate_verification(false);
  9219. auto res = cli.Get("/");
  9220. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  9221. }
  9222. #endif
  9223. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  9224. Client cli("https://google.com");
  9225. auto res = cli.Get("/");
  9226. ASSERT_TRUE(res);
  9227. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9228. }
  9229. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  9230. SSLClient cli("google.com");
  9231. cli.set_ca_cert_path(CA_CERT_FILE);
  9232. auto res = cli.Get("/");
  9233. ASSERT_TRUE(res);
  9234. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9235. }
  9236. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  9237. SSLClient cli("google.com");
  9238. cli.enable_server_certificate_verification(true);
  9239. cli.set_ca_cert_path("hello");
  9240. auto res = cli.Get("/");
  9241. ASSERT_TRUE(!res);
  9242. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  9243. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  9244. // should be set
  9245. EXPECT_EQ(0, res.ssl_error());
  9246. // Verify backend error is captured for SSLLoadingCerts
  9247. // This error occurs when loading CA certificates fails
  9248. EXPECT_NE(0UL, res.ssl_backend_error());
  9249. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9250. // OpenSSL specific error codes:
  9251. // > openssl errstr 0x80000002
  9252. // error:80000002:system library::No such file or directory
  9253. // > openssl errstr 0xA000126
  9254. // error:0A000126:SSL routines::unexpected eof while reading
  9255. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  9256. res.ssl_backend_error() == 0xA000126);
  9257. #endif
  9258. }
  9259. TEST(SSLClientTest, ServerCertificateVerification4) {
  9260. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9261. ASSERT_TRUE(svr.is_valid());
  9262. svr.Get("/test", [&](const Request &, Response &res) {
  9263. res.set_content("test", "text/plain");
  9264. svr.stop();
  9265. ASSERT_TRUE(true);
  9266. });
  9267. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  9268. auto se = detail::scope_exit([&] {
  9269. t.join();
  9270. ASSERT_FALSE(svr.is_running());
  9271. });
  9272. svr.wait_until_ready();
  9273. SSLClient cli("127.0.0.1", PORT);
  9274. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  9275. cli.enable_server_certificate_verification(true);
  9276. cli.set_connection_timeout(30);
  9277. auto res = cli.Get("/test");
  9278. ASSERT_TRUE(res);
  9279. ASSERT_EQ(StatusCode::OK_200, res->status);
  9280. }
  9281. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  9282. std::string cert;
  9283. read_file(CA_CERT_FILE, cert);
  9284. SSLClient cli("google.com");
  9285. cli.load_ca_cert_store(cert.data(), cert.size());
  9286. const auto res = cli.Get("/");
  9287. ASSERT_TRUE(res);
  9288. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9289. }
  9290. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  9291. // clang-format off
  9292. static constexpr char cert[] =
  9293. "GlobalSign Root CA\n"
  9294. "==================\n"
  9295. "-----BEGIN CERTIFICATE-----\n"
  9296. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  9297. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  9298. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  9299. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  9300. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  9301. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  9302. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  9303. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  9304. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  9305. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  9306. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  9307. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  9308. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  9309. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  9310. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  9311. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  9312. "-----END CERTIFICATE-----\n";
  9313. // clang-format on
  9314. SSLClient cli("google.com");
  9315. cli.load_ca_cert_store(cert, sizeof(cert));
  9316. const auto res = cli.Get("/");
  9317. ASSERT_TRUE(res);
  9318. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9319. }
  9320. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  9321. SSLClient cli("www.youtube.com");
  9322. cli.set_ca_cert_path(CA_CERT_FILE);
  9323. cli.enable_server_certificate_verification(true);
  9324. cli.set_follow_location(true);
  9325. auto res = cli.Get("/");
  9326. ASSERT_TRUE(res);
  9327. ASSERT_EQ(StatusCode::OK_200, res->status);
  9328. }
  9329. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  9330. SSLClient cli("wWw.YouTube.Com");
  9331. cli.set_ca_cert_path(CA_CERT_FILE);
  9332. cli.enable_server_certificate_verification(true);
  9333. cli.enable_server_hostname_verification(true);
  9334. cli.set_follow_location(true);
  9335. auto res = cli.Get("/");
  9336. ASSERT_TRUE(res);
  9337. ASSERT_EQ(StatusCode::OK_200, res->status);
  9338. }
  9339. TEST(SSLClientTest, HostNameMatchCase_Online) {
  9340. SSLClient cli("gOoGlE.COm");
  9341. cli.enable_server_certificate_verification(true);
  9342. cli.enable_server_hostname_verification(true);
  9343. cli.set_follow_location(true);
  9344. auto res = cli.Get("/");
  9345. ASSERT_TRUE(res);
  9346. ASSERT_EQ(StatusCode::OK_200, res->status);
  9347. }
  9348. TEST(SSLClientTest, Issue2004_Online) {
  9349. Client client("https://google.com");
  9350. client.set_follow_location(true);
  9351. auto res = client.Get("/");
  9352. ASSERT_TRUE(res);
  9353. ASSERT_EQ(StatusCode::OK_200, res->status);
  9354. auto body = res->body;
  9355. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  9356. }
  9357. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  9358. // Create SSLClient with invalid cert/key to make is_valid() return false
  9359. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  9360. "nonexistent_key.pem");
  9361. // is_valid() should be false due to cert loading failure
  9362. ASSERT_FALSE(cli.is_valid());
  9363. auto res = cli.Get("/");
  9364. ASSERT_FALSE(res);
  9365. EXPECT_EQ(Error::SSLConnection, res.error());
  9366. }
  9367. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  9368. // Test for Issue #2251: SSL error not properly reported when client cert
  9369. // and key paths are swapped or mismatched
  9370. // This simulates the scenario where user accidentally swaps the cert and key
  9371. // files
  9372. // Using client cert file as private key and vice versa (completely wrong)
  9373. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  9374. // Should fail validation due to cert/key mismatch
  9375. ASSERT_FALSE(cli.is_valid());
  9376. // Attempt to make a request should fail with proper error
  9377. auto res = cli.Get("/");
  9378. ASSERT_FALSE(res);
  9379. EXPECT_EQ(Error::SSLConnection, res.error());
  9380. // SSL error should be recorded in the Result object (this is the key fix for
  9381. // Issue #2251)
  9382. auto backend_error = res.ssl_backend_error();
  9383. EXPECT_NE(0u, backend_error);
  9384. }
  9385. // Tests cert/key mismatch detection at the TLS context level
  9386. TEST(TlsApiTest, ClientCertKeyMismatch) {
  9387. // Test that using mismatched cert/key causes connection failure.
  9388. // We verify this at the SSLClient level rather than through internal
  9389. // TLS API functions.
  9390. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  9391. cli.enable_server_certificate_verification(false);
  9392. cli.set_connection_timeout(2);
  9393. // The mismatch should cause a connection or handshake error
  9394. auto res = cli.Get("/test");
  9395. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  9396. // Either way, the request should fail
  9397. EXPECT_FALSE(res);
  9398. }
  9399. #endif
  9400. #if 0
  9401. TEST(SSLClientTest, SetInterfaceWithINET6) {
  9402. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  9403. ASSERT_TRUE(cli != nullptr);
  9404. cli->set_address_family(AF_INET6);
  9405. cli->set_interface("en0");
  9406. auto res = cli->Get("/get");
  9407. ASSERT_TRUE(res);
  9408. ASSERT_EQ(StatusCode::OK_200, res->status);
  9409. }
  9410. #endif
  9411. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  9412. #ifdef CPPHTTPLIB_SSL_ENABLED
  9413. void ClientCertPresent(
  9414. const std::string &client_cert_file,
  9415. const std::string &client_private_key_file,
  9416. const std::string &client_encrypted_private_key_pass = std::string()) {
  9417. using namespace httplib::tls;
  9418. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  9419. CLIENT_CA_CERT_DIR);
  9420. ASSERT_TRUE(svr.is_valid());
  9421. svr.Get("/test", [&](const Request &req, Response &res) {
  9422. res.set_content("test", "text/plain");
  9423. auto cert = req.peer_cert();
  9424. ASSERT_TRUE(static_cast<bool>(cert));
  9425. std::string common_name = cert.subject_cn();
  9426. EXPECT_EQ("Common Name", common_name);
  9427. });
  9428. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9429. auto se = detail::scope_exit([&] {
  9430. svr.stop();
  9431. t.join();
  9432. ASSERT_FALSE(svr.is_running());
  9433. });
  9434. svr.wait_until_ready();
  9435. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  9436. client_encrypted_private_key_pass);
  9437. cli.enable_server_certificate_verification(false);
  9438. cli.set_connection_timeout(30);
  9439. auto res = cli.Get("/test");
  9440. ASSERT_TRUE(res);
  9441. ASSERT_EQ(StatusCode::OK_200, res->status);
  9442. }
  9443. TEST(SSLClientServerTest, ClientCertPresent) {
  9444. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9445. }
  9446. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  9447. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  9448. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  9449. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  9450. }
  9451. // PEM memory-based constructor tests (works with all TLS backends)
  9452. void PemMemoryClientCertPresent(
  9453. const std::string &client_cert_file,
  9454. const std::string &client_private_key_file,
  9455. const std::string &client_encrypted_private_key_pass = std::string()) {
  9456. // Read PEM files into memory
  9457. std::string server_cert_pem, server_key_pem;
  9458. std::string client_ca_pem;
  9459. std::string client_cert_pem, client_key_pem;
  9460. read_file(SERVER_CERT_FILE, server_cert_pem);
  9461. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  9462. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  9463. read_file(client_cert_file, client_cert_pem);
  9464. read_file(client_private_key_file, client_key_pem);
  9465. // Create server with PEM memory
  9466. SSLServer::PemMemory server_pem = {
  9467. server_cert_pem.c_str(),
  9468. server_cert_pem.size(),
  9469. server_key_pem.c_str(),
  9470. server_key_pem.size(),
  9471. client_ca_pem.c_str(),
  9472. client_ca_pem.size(),
  9473. nullptr // no password for server key
  9474. };
  9475. SSLServer svr(server_pem);
  9476. ASSERT_TRUE(svr.is_valid());
  9477. svr.Get("/test", [&](const Request &, Response &res) {
  9478. res.set_content("test", "text/plain");
  9479. });
  9480. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9481. auto se = detail::scope_exit([&] {
  9482. svr.stop();
  9483. t.join();
  9484. ASSERT_FALSE(svr.is_running());
  9485. });
  9486. svr.wait_until_ready();
  9487. // Create client with PEM memory
  9488. const char *password = client_encrypted_private_key_pass.empty()
  9489. ? nullptr
  9490. : client_encrypted_private_key_pass.c_str();
  9491. SSLClient::PemMemory client_pem = {
  9492. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  9493. client_key_pem.size(), password};
  9494. SSLClient cli(HOST, PORT, client_pem);
  9495. cli.enable_server_certificate_verification(false);
  9496. cli.set_connection_timeout(30);
  9497. auto res = cli.Get("/test");
  9498. ASSERT_TRUE(res);
  9499. ASSERT_EQ(StatusCode::OK_200, res->status);
  9500. }
  9501. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  9502. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9503. }
  9504. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  9505. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  9506. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  9507. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  9508. }
  9509. TEST(SSLClientServerTest, ClientCertMissing) {
  9510. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  9511. CLIENT_CA_CERT_DIR);
  9512. ASSERT_TRUE(svr.is_valid());
  9513. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  9514. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9515. auto se = detail::scope_exit([&] {
  9516. svr.stop();
  9517. t.join();
  9518. ASSERT_FALSE(svr.is_running());
  9519. });
  9520. svr.wait_until_ready();
  9521. SSLClient cli(HOST, PORT);
  9522. cli.set_connection_timeout(30);
  9523. auto res = cli.Get("/test");
  9524. ASSERT_TRUE(!res);
  9525. // When client cert is missing and server requires it, connection fails
  9526. // Error type depends on backend implementation
  9527. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  9528. res.error() == Error::SSLConnection);
  9529. // Verify backend error is captured
  9530. // Note: This test may have different error codes depending on the exact
  9531. // verification failure
  9532. EXPECT_NE(0UL, res.ssl_backend_error());
  9533. }
  9534. TEST(SSLClientServerTest, TrustDirOptional) {
  9535. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  9536. ASSERT_TRUE(svr.is_valid());
  9537. svr.Get("/test", [&](const Request &, Response &res) {
  9538. res.set_content("test", "text/plain");
  9539. });
  9540. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9541. auto se = detail::scope_exit([&] {
  9542. svr.stop();
  9543. t.join();
  9544. ASSERT_FALSE(svr.is_running());
  9545. });
  9546. svr.wait_until_ready();
  9547. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9548. cli.enable_server_certificate_verification(false);
  9549. cli.set_connection_timeout(30);
  9550. auto res = cli.Get("/test");
  9551. ASSERT_TRUE(res);
  9552. ASSERT_EQ(StatusCode::OK_200, res->status);
  9553. }
  9554. TEST(SSLClientServerTest, SSLConnectTimeout) {
  9555. class NoListenSSLServer : public SSLServer {
  9556. public:
  9557. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  9558. const char *client_ca_cert_file_path,
  9559. const char *client_ca_cert_dir_path = nullptr)
  9560. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  9561. client_ca_cert_dir_path),
  9562. stop_(false) {}
  9563. std::atomic_bool stop_;
  9564. private:
  9565. bool process_and_close_socket(socket_t /*sock*/) override {
  9566. // Don't create SSL context
  9567. while (!stop_.load()) {
  9568. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9569. }
  9570. return true;
  9571. }
  9572. };
  9573. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  9574. CLIENT_CA_CERT_FILE);
  9575. ASSERT_TRUE(svr.is_valid());
  9576. svr.Get("/test", [&](const Request &, Response &res) {
  9577. res.set_content("test", "text/plain");
  9578. });
  9579. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9580. auto se = detail::scope_exit([&] {
  9581. svr.stop_ = true;
  9582. svr.stop();
  9583. t.join();
  9584. ASSERT_FALSE(svr.is_running());
  9585. });
  9586. svr.wait_until_ready();
  9587. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9588. cli.enable_server_certificate_verification(false);
  9589. cli.set_connection_timeout(1);
  9590. auto res = cli.Get("/test");
  9591. ASSERT_TRUE(!res);
  9592. EXPECT_EQ(Error::SSLConnection, res.error());
  9593. // Timeout results in WantRead error code (maps to backend-specific value)
  9594. EXPECT_NE(0, res.ssl_error());
  9595. }
  9596. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  9597. // Test SSLServer with client certificate verification using the standard
  9598. // constructor (ContextSetupCallback is tested by backend-specific tests)
  9599. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  9600. CLIENT_CA_CERT_DIR);
  9601. ASSERT_TRUE(svr.is_valid());
  9602. svr.Get("/test", [&](const Request &req, Response &res) {
  9603. res.set_content("test", "text/plain");
  9604. auto cert = req.peer_cert();
  9605. ASSERT_TRUE(static_cast<bool>(cert));
  9606. auto common_name = cert.subject_cn();
  9607. EXPECT_EQ("Common Name", common_name);
  9608. });
  9609. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9610. auto se = detail::scope_exit([&] {
  9611. svr.stop();
  9612. t.join();
  9613. ASSERT_FALSE(svr.is_running());
  9614. });
  9615. svr.wait_until_ready();
  9616. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9617. cli.enable_server_certificate_verification(false);
  9618. cli.set_connection_timeout(30);
  9619. auto res = cli.Get("/test");
  9620. ASSERT_TRUE(res);
  9621. ASSERT_EQ(StatusCode::OK_200, res->status);
  9622. }
  9623. // Test verify_hostname for both OpenSSL and MbedTLS backends
  9624. // Verifies that wildcard matching and exact matching work consistently
  9625. TEST(SSLClientServerTest, TlsVerifyHostname) {
  9626. using namespace httplib::tls;
  9627. // We need a running server to test against
  9628. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9629. ASSERT_TRUE(svr.is_valid());
  9630. svr.Get("/test", [](const Request &, Response &res) {
  9631. res.set_content("ok", "text/plain");
  9632. });
  9633. thread t([&]() { svr.listen(HOST, PORT); });
  9634. auto se = detail::scope_exit([&] {
  9635. svr.stop();
  9636. t.join();
  9637. });
  9638. svr.wait_until_ready();
  9639. bool verify_callback_called = false;
  9640. bool verify_result_wrong = false;
  9641. SSLClient cli(HOST, PORT);
  9642. cli.enable_server_certificate_verification(true);
  9643. cli.set_ca_cert_path(CA_CERT_FILE);
  9644. cli.set_connection_timeout(5);
  9645. // Note: Test certificate has CN="Common Name", not "localhost"
  9646. bool verify_result_cn = false;
  9647. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9648. verify_callback_called = true;
  9649. if (!ctx.cert) return false;
  9650. // Test 1: "Common Name" should match (our test server cert CN)
  9651. verify_result_cn = ctx.check_hostname("Common Name");
  9652. // Test 2: wrong hostname should not match
  9653. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  9654. return true; // Accept for the purpose of this test
  9655. });
  9656. auto res = cli.Get("/test");
  9657. // The request may succeed or fail depending on cert configuration
  9658. // but the callback should have been called
  9659. ASSERT_TRUE(verify_callback_called)
  9660. << "Verify callback should have been called";
  9661. // CN="Common Name" should match our test certificate
  9662. //
  9663. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  9664. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  9665. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  9666. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  9667. // <openssl/base.h>, which is included transitively when
  9668. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  9669. #if defined(OPENSSL_IS_BORINGSSL)
  9670. EXPECT_FALSE(verify_result_cn)
  9671. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  9672. #else
  9673. EXPECT_TRUE(verify_result_cn)
  9674. << "verify_hostname should match 'Common Name' (certificate CN)";
  9675. #endif
  9676. // Wrong hostname should not match
  9677. EXPECT_FALSE(verify_result_wrong)
  9678. << "verify_hostname should not match 'wronghost.example.com'";
  9679. }
  9680. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  9681. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  9682. // X509_check_ip behavior and must hold for every backend.
  9683. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  9684. using namespace httplib::tls;
  9685. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  9686. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  9687. ASSERT_TRUE(svr.is_valid());
  9688. svr.Get("/test", [](const Request &, Response &res) {
  9689. res.set_content("ok", "text/plain");
  9690. });
  9691. thread t([&]() { svr.listen(HOST, PORT); });
  9692. auto se = detail::scope_exit([&] {
  9693. svr.stop();
  9694. t.join();
  9695. });
  9696. svr.wait_until_ready();
  9697. bool verify_callback_called = false;
  9698. bool ip_matched_via_cn = true;
  9699. SSLClient cli(HOST, PORT);
  9700. cli.enable_server_certificate_verification(true);
  9701. cli.set_ca_cert_path(CA_CERT_FILE);
  9702. cli.set_connection_timeout(5);
  9703. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9704. verify_callback_called = true;
  9705. if (!ctx.cert) return false;
  9706. // The IP appears only in the CN, so it must NOT be accepted.
  9707. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  9708. return true; // Accept for the purpose of this test
  9709. });
  9710. cli.Get("/test");
  9711. ASSERT_TRUE(verify_callback_called)
  9712. << "Verify callback should have been called";
  9713. EXPECT_FALSE(ip_matched_via_cn)
  9714. << "An IP host must not be authenticated via the certificate CN";
  9715. }
  9716. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  9717. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  9718. using namespace httplib::tls;
  9719. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  9720. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  9721. ASSERT_TRUE(svr.is_valid());
  9722. svr.Get("/test", [](const Request &, Response &res) {
  9723. res.set_content("ok", "text/plain");
  9724. });
  9725. thread t([&]() { svr.listen(HOST, PORT); });
  9726. auto se = detail::scope_exit([&] {
  9727. svr.stop();
  9728. t.join();
  9729. });
  9730. svr.wait_until_ready();
  9731. bool verify_callback_called = false;
  9732. bool san_matched = false;
  9733. bool wrong_ipv6_matched = true;
  9734. bool cn_ipv6_matched = true;
  9735. SSLClient cli(HOST, PORT);
  9736. cli.enable_server_certificate_verification(true);
  9737. cli.set_ca_cert_path(CA_CERT_FILE);
  9738. cli.set_connection_timeout(5);
  9739. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9740. verify_callback_called = true;
  9741. if (!ctx.cert) return false;
  9742. // Matches the IPv6 iPAddress SAN.
  9743. san_matched = ctx.check_hostname("2001:db8::1");
  9744. // A different IPv6 address must not match.
  9745. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  9746. // "::1" lives only in the CN, so it must not be accepted.
  9747. cn_ipv6_matched = ctx.check_hostname("::1");
  9748. return true; // Accept for the purpose of this test
  9749. });
  9750. cli.Get("/test");
  9751. ASSERT_TRUE(verify_callback_called)
  9752. << "Verify callback should have been called";
  9753. EXPECT_TRUE(san_matched)
  9754. << "verify_hostname should match an IPv6 iPAddress SAN";
  9755. EXPECT_FALSE(wrong_ipv6_matched)
  9756. << "verify_hostname should not match a non-matching IPv6 address";
  9757. EXPECT_FALSE(cn_ipv6_matched)
  9758. << "An IPv6 host must not be authenticated via the certificate CN";
  9759. }
  9760. #endif
  9761. // mbedTLS-specific callback constructor test
  9762. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  9763. #ifdef CPPHTTPLIB_SSL_ENABLED
  9764. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  9765. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  9766. ASSERT_TRUE(svr.is_valid());
  9767. // Set up a handler to verify client certificate is present
  9768. bool client_cert_verified = false;
  9769. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  9770. // Verify that client certificate was provided
  9771. client_cert_verified = true;
  9772. res.set_content("success", "text/plain");
  9773. });
  9774. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9775. auto se = detail::scope_exit([&] {
  9776. svr.stop();
  9777. t.join();
  9778. ASSERT_FALSE(svr.is_running());
  9779. });
  9780. svr.wait_until_ready();
  9781. // Client with certificate
  9782. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9783. cli.enable_server_certificate_verification(false);
  9784. cli.set_connection_timeout(30);
  9785. auto res = cli.Get("/test");
  9786. ASSERT_TRUE(res);
  9787. ASSERT_EQ(StatusCode::OK_200, res->status);
  9788. ASSERT_TRUE(client_cert_verified);
  9789. EXPECT_EQ("success", res->body);
  9790. }
  9791. #endif
  9792. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  9793. // backends
  9794. #ifdef CPPHTTPLIB_SSL_ENABLED
  9795. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  9796. using namespace httplib::tls;
  9797. // Test that when client CA cert file is provided,
  9798. // the server properly requests and validates client certificates
  9799. // Create a server with client authentication
  9800. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  9801. ASSERT_TRUE(svr.is_valid());
  9802. bool handler_called = false;
  9803. svr.Get("/test", [&](const Request &req, Response &res) {
  9804. handler_called = true;
  9805. // Verify that a client certificate was provided
  9806. auto cert = req.peer_cert();
  9807. ASSERT_TRUE(static_cast<bool>(cert));
  9808. // Get the issuer name
  9809. std::string issuer_str = cert.issuer_name();
  9810. ASSERT_FALSE(issuer_str.empty());
  9811. // The client certificate should be issued by our test CA
  9812. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  9813. res.set_content("authenticated", "text/plain");
  9814. });
  9815. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9816. auto se = detail::scope_exit([&] {
  9817. svr.stop();
  9818. t.join();
  9819. ASSERT_FALSE(svr.is_running());
  9820. });
  9821. svr.wait_until_ready();
  9822. // Connect with a client certificate issued by the CA
  9823. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9824. cli.enable_server_certificate_verification(false);
  9825. cli.set_connection_timeout(30);
  9826. auto res = cli.Get("/test");
  9827. ASSERT_TRUE(res);
  9828. ASSERT_EQ(StatusCode::OK_200, res->status);
  9829. ASSERT_TRUE(handler_called);
  9830. EXPECT_EQ("authenticated", res->body);
  9831. }
  9832. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  9833. using namespace httplib::tls;
  9834. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9835. ASSERT_TRUE(svr.is_valid());
  9836. svr.Get("/test", [](const Request &, Response &res) {
  9837. res.set_content("ok", "text/plain");
  9838. });
  9839. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9840. auto se = detail::scope_exit([&] {
  9841. svr.stop();
  9842. t.join();
  9843. });
  9844. svr.wait_until_ready();
  9845. SSLClient cli(HOST, PORT);
  9846. cli.enable_server_certificate_verification(false);
  9847. cli.set_connection_timeout(30);
  9848. bool cert_checked = false;
  9849. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9850. if (ctx.cert) {
  9851. auto sans = ctx.sans();
  9852. // Test certificate may or may not have SANs - just verify the API
  9853. // works If SANs exist, verify the types are valid
  9854. for (const auto &san : sans) {
  9855. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  9856. san.type == SanType::EMAIL || san.type == SanType::URI ||
  9857. san.type == SanType::OTHER);
  9858. EXPECT_FALSE(san.value.empty());
  9859. }
  9860. cert_checked = true;
  9861. }
  9862. return true;
  9863. });
  9864. auto res = cli.Get("/test");
  9865. ASSERT_TRUE(res);
  9866. EXPECT_TRUE(cert_checked);
  9867. }
  9868. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  9869. using namespace httplib::tls;
  9870. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9871. ASSERT_TRUE(svr.is_valid());
  9872. svr.Get("/test", [](const Request &, Response &res) {
  9873. res.set_content("ok", "text/plain");
  9874. });
  9875. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9876. auto se = detail::scope_exit([&] {
  9877. svr.stop();
  9878. t.join();
  9879. });
  9880. svr.wait_until_ready();
  9881. SSLClient cli(HOST, PORT);
  9882. cli.enable_server_certificate_verification(false);
  9883. cli.set_connection_timeout(30);
  9884. bool validity_checked = false;
  9885. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9886. if (ctx.cert) {
  9887. time_t not_before = 0, not_after = 0;
  9888. bool result = ctx.validity(not_before, not_after);
  9889. EXPECT_TRUE(result);
  9890. // Verify that not_before < now < not_after for a valid cert
  9891. time_t now = time(nullptr);
  9892. EXPECT_LT(not_before, now);
  9893. EXPECT_GT(not_after, now);
  9894. validity_checked = true;
  9895. }
  9896. return true;
  9897. });
  9898. auto res = cli.Get("/test");
  9899. ASSERT_TRUE(res);
  9900. EXPECT_TRUE(validity_checked);
  9901. }
  9902. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  9903. using namespace httplib::tls;
  9904. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9905. ASSERT_TRUE(svr.is_valid());
  9906. svr.Get("/test", [](const Request &, Response &res) {
  9907. res.set_content("ok", "text/plain");
  9908. });
  9909. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9910. auto se = detail::scope_exit([&] {
  9911. svr.stop();
  9912. t.join();
  9913. });
  9914. svr.wait_until_ready();
  9915. SSLClient cli(HOST, PORT);
  9916. cli.enable_server_certificate_verification(false);
  9917. cli.set_connection_timeout(30);
  9918. bool serial_checked = false;
  9919. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9920. if (ctx.cert) {
  9921. std::string serial = ctx.serial();
  9922. EXPECT_FALSE(serial.empty());
  9923. // Serial should be a hex string
  9924. for (char c : serial) {
  9925. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  9926. (c >= 'a' && c <= 'f'));
  9927. }
  9928. serial_checked = true;
  9929. }
  9930. return true;
  9931. });
  9932. auto res = cli.Get("/test");
  9933. ASSERT_TRUE(res);
  9934. EXPECT_TRUE(serial_checked);
  9935. }
  9936. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  9937. // Test 1: Valid CA file - no error should be recorded
  9938. {
  9939. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  9940. CLIENT_CA_CERT_FILE);
  9941. ASSERT_TRUE(svr.is_valid());
  9942. // With valid setup, last_ssl_error should be 0
  9943. EXPECT_EQ(0, svr.ssl_last_error());
  9944. }
  9945. // Test 2: Invalid CA file content
  9946. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  9947. {
  9948. // Create a temporary file with completely invalid content
  9949. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  9950. {
  9951. std::ofstream ofs(temp_invalid_ca);
  9952. ofs << "This is not a certificate file at all\n";
  9953. ofs << "Just plain text content\n";
  9954. }
  9955. // Create server with invalid CA file
  9956. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  9957. // Clean up temporary file
  9958. std::remove(temp_invalid_ca);
  9959. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  9960. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  9961. // Note: SSL_CTX_load_verify_locations typically fails first,
  9962. // but our error handling code path is still exercised
  9963. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  9964. }
  9965. }
  9966. TEST(VerifyCallbackTest, VerifyContextFields) {
  9967. using namespace httplib::tls;
  9968. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9969. ASSERT_TRUE(svr.is_valid());
  9970. svr.Get("/test", [](const Request &, Response &res) {
  9971. res.set_content("ok", "text/plain");
  9972. });
  9973. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9974. auto se = detail::scope_exit([&] {
  9975. svr.stop();
  9976. t.join();
  9977. });
  9978. svr.wait_until_ready();
  9979. SSLClient cli(HOST, PORT);
  9980. cli.enable_server_certificate_verification(false);
  9981. cli.set_connection_timeout(30);
  9982. int callback_count = 0;
  9983. bool saw_leaf_cert = false;
  9984. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9985. if (ctx.cert) {
  9986. callback_count++;
  9987. // We should see at least one certificate (the leaf)
  9988. std::string cn = ctx.subject_cn();
  9989. if (!cn.empty()) { saw_leaf_cert = true; }
  9990. // Verify context fields are populated
  9991. EXPECT_NE(ctx.session, nullptr);
  9992. EXPECT_GE(ctx.depth, 0);
  9993. }
  9994. return true;
  9995. });
  9996. auto res = cli.Get("/test");
  9997. ASSERT_TRUE(res);
  9998. EXPECT_GT(callback_count, 0);
  9999. EXPECT_TRUE(saw_leaf_cert);
  10000. }
  10001. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  10002. using httplib::tls::TlsError;
  10003. // Test that verify_error_to_string returns empty for success
  10004. std::string success_str = TlsError::verify_error_to_string(0);
  10005. EXPECT_TRUE(success_str.empty());
  10006. // Test that verify_error_to_string returns non-empty for error codes
  10007. // Using a common error code (certificate expired)
  10008. std::string error_str =
  10009. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  10010. EXPECT_FALSE(error_str.empty());
  10011. }
  10012. TEST(SessionVerifierTest, CertificateAccepted) {
  10013. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10014. ASSERT_TRUE(svr.is_valid());
  10015. svr.Get("/test", [](const Request &, Response &res) {
  10016. res.set_content("ok", "text/plain");
  10017. });
  10018. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10019. auto se = detail::scope_exit([&] {
  10020. svr.stop();
  10021. t.join();
  10022. });
  10023. svr.wait_until_ready();
  10024. SSLClient cli(HOST, PORT);
  10025. cli.enable_server_certificate_verification(false);
  10026. cli.set_connection_timeout(30);
  10027. bool callback_called = false;
  10028. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  10029. EXPECT_NE(session, nullptr);
  10030. callback_called = true;
  10031. return SSLVerifierResponse::CertificateAccepted;
  10032. });
  10033. auto res = cli.Get("/test");
  10034. ASSERT_TRUE(res);
  10035. EXPECT_EQ(200, res->status);
  10036. EXPECT_TRUE(callback_called);
  10037. }
  10038. TEST(SessionVerifierTest, CertificateRejected) {
  10039. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10040. ASSERT_TRUE(svr.is_valid());
  10041. svr.Get("/test", [](const Request &, Response &res) {
  10042. res.set_content("ok", "text/plain");
  10043. });
  10044. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10045. auto se = detail::scope_exit([&] {
  10046. svr.stop();
  10047. t.join();
  10048. });
  10049. svr.wait_until_ready();
  10050. SSLClient cli(HOST, PORT);
  10051. cli.enable_server_certificate_verification(false);
  10052. cli.set_connection_timeout(30);
  10053. bool callback_called = false;
  10054. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  10055. EXPECT_NE(session, nullptr);
  10056. callback_called = true;
  10057. return SSLVerifierResponse::CertificateRejected;
  10058. });
  10059. auto res = cli.Get("/test");
  10060. EXPECT_FALSE(res);
  10061. EXPECT_TRUE(callback_called);
  10062. }
  10063. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  10064. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10065. ASSERT_TRUE(svr.is_valid());
  10066. svr.Get("/test", [](const Request &, Response &res) {
  10067. res.set_content("ok", "text/plain");
  10068. });
  10069. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10070. auto se = detail::scope_exit([&] {
  10071. svr.stop();
  10072. t.join();
  10073. });
  10074. svr.wait_until_ready();
  10075. // NoDecisionMade with verification disabled should succeed (no default check)
  10076. SSLClient cli(HOST, PORT);
  10077. cli.enable_server_certificate_verification(false);
  10078. cli.set_connection_timeout(30);
  10079. bool callback_called = false;
  10080. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  10081. EXPECT_NE(session, nullptr);
  10082. callback_called = true;
  10083. return SSLVerifierResponse::NoDecisionMade;
  10084. });
  10085. auto res = cli.Get("/test");
  10086. ASSERT_TRUE(res);
  10087. EXPECT_EQ(200, res->status);
  10088. EXPECT_TRUE(callback_called);
  10089. }
  10090. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  10091. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10092. ASSERT_TRUE(svr.is_valid());
  10093. svr.Get("/test", [](const Request &, Response &res) {
  10094. res.set_content("ok", "text/plain");
  10095. });
  10096. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10097. auto se = detail::scope_exit([&] {
  10098. svr.stop();
  10099. t.join();
  10100. });
  10101. svr.wait_until_ready();
  10102. // NoDecisionMade with verification enabled should fail (self-signed cert).
  10103. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  10104. // so we only check that the request fails, not whether the callback was
  10105. // called.
  10106. SSLClient cli(HOST, PORT);
  10107. cli.enable_server_certificate_verification(true);
  10108. cli.set_connection_timeout(30);
  10109. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  10110. EXPECT_NE(session, nullptr);
  10111. return SSLVerifierResponse::NoDecisionMade;
  10112. });
  10113. auto res = cli.Get("/test");
  10114. EXPECT_FALSE(res);
  10115. }
  10116. TEST(SSLClientServerTest, ClientCAListFromPem) {
  10117. // Test SSL server using PemMemory constructor with client CA certificates
  10118. // Read PEM files
  10119. std::string server_cert_pem, server_key_pem, client_ca_pem;
  10120. read_file(SERVER_CERT_FILE, server_cert_pem);
  10121. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  10122. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  10123. // Create SSLServer with PemMemory constructor including client CA
  10124. SSLServer::PemMemory server_pem = {
  10125. server_cert_pem.c_str(),
  10126. server_cert_pem.size(),
  10127. server_key_pem.c_str(),
  10128. server_key_pem.size(),
  10129. client_ca_pem.c_str(),
  10130. client_ca_pem.size(),
  10131. nullptr // no password for server key
  10132. };
  10133. SSLServer svr(server_pem);
  10134. ASSERT_TRUE(svr.is_valid());
  10135. // No SSL error should be recorded for valid setup
  10136. EXPECT_EQ(0, svr.ssl_last_error());
  10137. // Set up server endpoints
  10138. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  10139. res.set_content("ok", "text/plain");
  10140. });
  10141. // Start server in a thread
  10142. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  10143. svr.wait_until_ready();
  10144. // Connect with client certificate (using constructor with paths)
  10145. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10146. cli.enable_server_certificate_verification(false);
  10147. auto res = cli.Get("/test-pem-ca");
  10148. ASSERT_TRUE(res);
  10149. EXPECT_EQ(200, res->status);
  10150. EXPECT_EQ("ok", res->body);
  10151. svr.stop();
  10152. server_thread.join();
  10153. }
  10154. #endif
  10155. #ifdef _WIN32
  10156. TEST(CleanupTest, WSACleanup) {
  10157. int ret = WSACleanup();
  10158. ASSERT_EQ(0, ret);
  10159. }
  10160. #endif
  10161. #ifndef CPPHTTPLIB_SSL_ENABLED
  10162. TEST(NoSSLSupport, SimpleInterface) {
  10163. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  10164. }
  10165. #endif
  10166. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10167. TEST(InvalidScheme, SimpleInterface) {
  10168. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  10169. }
  10170. #endif
  10171. TEST(NoScheme, SimpleInterface) {
  10172. Client cli("yahoo.com:80");
  10173. ASSERT_TRUE(cli.is_valid());
  10174. }
  10175. TEST(SendAPI, SimpleInterface_Online) {
  10176. Client cli("http://yahoo.com");
  10177. Request req;
  10178. req.method = "GET";
  10179. req.path = "/";
  10180. auto res = cli.send(req);
  10181. ASSERT_TRUE(res);
  10182. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10183. }
  10184. TEST(SendAPI, WithParamsInRequest) {
  10185. Server svr;
  10186. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  10187. EXPECT_TRUE(req.has_param("test"));
  10188. EXPECT_EQ("test_value", req.get_param_value("test"));
  10189. });
  10190. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  10191. auto se = detail::scope_exit([&] {
  10192. svr.stop();
  10193. t.join();
  10194. ASSERT_FALSE(svr.is_running());
  10195. });
  10196. svr.wait_until_ready();
  10197. Client cli(HOST, PORT);
  10198. {
  10199. Request req;
  10200. req.method = "GET";
  10201. req.path = "/";
  10202. req.params.emplace("test", "test_value");
  10203. auto res = cli.send(req);
  10204. ASSERT_TRUE(res);
  10205. }
  10206. {
  10207. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  10208. ASSERT_TRUE(res);
  10209. }
  10210. }
  10211. TEST(ClientImplMethods, GetSocketTest) {
  10212. httplib::Server svr;
  10213. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  10214. res.status = StatusCode::OK_200;
  10215. });
  10216. auto port = svr.bind_to_any_port("127.0.0.1");
  10217. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  10218. auto se = detail::scope_exit([&] {
  10219. svr.stop();
  10220. thread.join();
  10221. ASSERT_FALSE(svr.is_running());
  10222. });
  10223. svr.wait_until_ready();
  10224. {
  10225. httplib::Client cli("127.0.0.1", port);
  10226. cli.set_keep_alive(true);
  10227. // Use the behavior of cpp-httplib of opening the connection
  10228. // only when the first request happens. If that changes,
  10229. // this test would be obsolete.
  10230. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  10231. // This also implicitly tests the server. But other tests would fail much
  10232. // earlier than this one to be considered.
  10233. auto res = cli.Get("/");
  10234. ASSERT_TRUE(res);
  10235. EXPECT_EQ(StatusCode::OK_200, res->status);
  10236. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  10237. }
  10238. }
  10239. #ifdef CPPHTTPLIB_SSL_ENABLED
  10240. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  10241. Client cli("http://yahoo.com");
  10242. auto res = cli.Get("/");
  10243. ASSERT_TRUE(res);
  10244. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10245. cli.set_follow_location(true);
  10246. res = cli.Get("/");
  10247. ASSERT_TRUE(res);
  10248. EXPECT_EQ(StatusCode::OK_200, res->status);
  10249. EXPECT_EQ("https://www.yahoo.com/", res->location);
  10250. }
  10251. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  10252. Client cli("https://yahoo.com");
  10253. auto res = cli.Get("/");
  10254. ASSERT_TRUE(res);
  10255. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10256. cli.set_follow_location(true);
  10257. res = cli.Get("/");
  10258. ASSERT_TRUE(res);
  10259. EXPECT_EQ(StatusCode::OK_200, res->status);
  10260. EXPECT_EQ("https://www.yahoo.com/", res->location);
  10261. }
  10262. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  10263. Client cli("https://yahoo.com");
  10264. auto res = cli.Get("/");
  10265. ASSERT_TRUE(res);
  10266. ASSERT_FALSE(!res);
  10267. ASSERT_TRUE(res);
  10268. ASSERT_FALSE(res == nullptr);
  10269. ASSERT_TRUE(res != nullptr);
  10270. EXPECT_EQ(Error::Success, res.error());
  10271. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  10272. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  10273. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10274. cli.set_follow_location(true);
  10275. res = cli.Get("/");
  10276. ASSERT_TRUE(res);
  10277. EXPECT_EQ(Error::Success, res.error());
  10278. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  10279. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  10280. EXPECT_EQ(StatusCode::OK_200, res->status);
  10281. EXPECT_EQ("https://www.yahoo.com/", res->location);
  10282. }
  10283. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  10284. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  10285. Client cli("https://cdnjs.cloudflare.com");
  10286. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  10287. Headers{{"Accept-Encoding", "br"}});
  10288. ASSERT_TRUE(res);
  10289. EXPECT_EQ(StatusCode::OK_200, res->status);
  10290. EXPECT_EQ(287630U, res->body.size());
  10291. EXPECT_EQ("application/javascript; charset=utf-8",
  10292. res->get_header_value("Content-Type"));
  10293. }
  10294. #endif
  10295. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  10296. #undef REDIR_HOST // Silence compiler warning
  10297. #define REDIR_HOST "https://httpbingo.org"
  10298. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  10299. Client cli(REDIR_HOST);
  10300. cli.set_follow_location(true);
  10301. auto res =
  10302. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  10303. ASSERT_TRUE(res);
  10304. EXPECT_EQ(StatusCode::OK_200, res->status);
  10305. }
  10306. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  10307. Client cli(REDIR_HOST);
  10308. cli.set_follow_location(true);
  10309. Params params;
  10310. params.emplace("url", "http://example.com");
  10311. params.emplace("status_code", "302");
  10312. auto res = cli.Get(REDIR_PATH, params, Headers{});
  10313. ASSERT_TRUE(res);
  10314. EXPECT_EQ(StatusCode::OK_200, res->status);
  10315. }
  10316. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  10317. Client cli(REDIR_HOST);
  10318. cli.set_follow_location(true);
  10319. Params params;
  10320. params.emplace("url", "http://example.com");
  10321. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  10322. ASSERT_TRUE(res);
  10323. EXPECT_EQ(StatusCode::OK_200, res->status);
  10324. }
  10325. TEST(HttpToHttpsRedirectTest, CertFile) {
  10326. auto ssl_port = PORT + 1;
  10327. Server svr;
  10328. ASSERT_TRUE(svr.is_valid());
  10329. svr.Get("/index", [&](const Request &, Response &res) {
  10330. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  10331. "/index");
  10332. svr.stop();
  10333. });
  10334. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10335. ASSERT_TRUE(ssl_svr.is_valid());
  10336. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  10337. res.set_content("test", "text/plain");
  10338. ssl_svr.stop();
  10339. });
  10340. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10341. thread t2 =
  10342. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  10343. auto se = detail::scope_exit([&] {
  10344. t2.join();
  10345. t.join();
  10346. ASSERT_FALSE(svr.is_running());
  10347. });
  10348. svr.wait_until_ready();
  10349. ssl_svr.wait_until_ready();
  10350. Client cli("127.0.0.1", PORT);
  10351. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  10352. cli.enable_server_certificate_verification(true);
  10353. cli.set_follow_location(true);
  10354. cli.set_connection_timeout(30);
  10355. auto res = cli.Get("/index");
  10356. ASSERT_TRUE(res);
  10357. ASSERT_EQ(StatusCode::OK_200, res->status);
  10358. }
  10359. TEST(SSLClientRedirectTest, CertFile) {
  10360. auto ssl_port = PORT + 1;
  10361. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10362. ASSERT_TRUE(ssl_svr1.is_valid());
  10363. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  10364. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  10365. "/index");
  10366. ssl_svr1.stop();
  10367. });
  10368. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10369. ASSERT_TRUE(ssl_svr2.is_valid());
  10370. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  10371. res.set_content("test", "text/plain");
  10372. ssl_svr2.stop();
  10373. });
  10374. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  10375. thread t2 =
  10376. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  10377. auto se = detail::scope_exit([&] {
  10378. t2.join();
  10379. t.join();
  10380. ASSERT_FALSE(ssl_svr1.is_running());
  10381. });
  10382. ssl_svr1.wait_until_ready();
  10383. ssl_svr2.wait_until_ready();
  10384. SSLClient cli("127.0.0.1", PORT);
  10385. std::string cert;
  10386. read_file(SERVER_CERT2_FILE, cert);
  10387. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10388. cli.enable_server_certificate_verification(true);
  10389. cli.set_follow_location(true);
  10390. cli.set_connection_timeout(30);
  10391. auto res = cli.Get("/index");
  10392. ASSERT_TRUE(res);
  10393. ASSERT_EQ(StatusCode::OK_200, res->status);
  10394. }
  10395. #endif
  10396. #ifdef CPPHTTPLIB_SSL_ENABLED
  10397. // Test that set_ca_cert_store() skips system certs (consistent with
  10398. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  10399. // should be trusted - system certs should NOT be loaded.
  10400. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  10401. // Load a specific cert that is NOT a system CA cert
  10402. std::string cert;
  10403. read_file(SERVER_CERT2_FILE, cert);
  10404. SSLClient cli("google.com");
  10405. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10406. cli.enable_server_certificate_verification(true);
  10407. // This should FAIL because:
  10408. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  10409. // 2. System certs should NOT be loaded when custom store is set
  10410. // If system certs WERE loaded, this would succeed
  10411. auto res = cli.Get("/");
  10412. ASSERT_FALSE(res);
  10413. EXPECT_EQ(Error::SSLServerVerification, res.error());
  10414. }
  10415. // Same as above, but through the native store handle path. Regression test:
  10416. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  10417. // merged system certs into the user-provided store.
  10418. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  10419. std::string cert;
  10420. read_file(SERVER_CERT2_FILE, cert);
  10421. SSLClient cli("google.com");
  10422. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  10423. cli.enable_server_certificate_verification(true);
  10424. auto res = cli.Get("/");
  10425. ASSERT_FALSE(res);
  10426. EXPECT_EQ(Error::SSLServerVerification, res.error());
  10427. }
  10428. // A custom store set via the native handle must still verify a server whose
  10429. // cert it does contain.
  10430. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  10431. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10432. ASSERT_TRUE(svr.is_valid());
  10433. svr.Get("/test", [&](const Request &, Response &res) {
  10434. res.set_content("test", "text/plain");
  10435. });
  10436. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10437. auto se = detail::scope_exit([&] {
  10438. svr.stop();
  10439. t.join();
  10440. ASSERT_FALSE(svr.is_running());
  10441. });
  10442. svr.wait_until_ready();
  10443. SSLClient cli("127.0.0.1", PORT);
  10444. std::string cert;
  10445. read_file(SERVER_CERT2_FILE, cert);
  10446. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  10447. cli.enable_server_certificate_verification(true);
  10448. cli.set_connection_timeout(30);
  10449. auto res = cli.Get("/test");
  10450. ASSERT_TRUE(res);
  10451. ASSERT_EQ(StatusCode::OK_200, res->status);
  10452. }
  10453. // CA certs loaded through the universal Client must be transferred to the
  10454. // client created internally for following an HTTPS redirect. Regression test:
  10455. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  10456. // the CA data for redirect transfer.
  10457. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  10458. auto ssl_port = PORT + 1;
  10459. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10460. ASSERT_TRUE(ssl_svr1.is_valid());
  10461. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  10462. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  10463. "/index");
  10464. });
  10465. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10466. ASSERT_TRUE(ssl_svr2.is_valid());
  10467. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  10468. res.set_content("test", "text/plain");
  10469. });
  10470. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  10471. thread t2 =
  10472. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  10473. auto se = detail::scope_exit([&] {
  10474. ssl_svr2.stop();
  10475. ssl_svr1.stop();
  10476. t2.join();
  10477. t.join();
  10478. ASSERT_FALSE(ssl_svr1.is_running());
  10479. });
  10480. ssl_svr1.wait_until_ready();
  10481. ssl_svr2.wait_until_ready();
  10482. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  10483. std::string cert;
  10484. read_file(SERVER_CERT2_FILE, cert);
  10485. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10486. cli.enable_server_certificate_verification(true);
  10487. cli.set_follow_location(true);
  10488. cli.set_connection_timeout(30);
  10489. auto res = cli.Get("/index");
  10490. ASSERT_TRUE(res);
  10491. ASSERT_EQ(StatusCode::OK_200, res->status);
  10492. }
  10493. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  10494. // so a host signed by a system CA verifies even though a custom CA is set
  10495. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  10496. std::string cert;
  10497. read_file(SERVER_CERT2_FILE, cert);
  10498. SSLClient cli("google.com");
  10499. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10500. cli.enable_system_ca(true);
  10501. cli.enable_server_certificate_verification(true);
  10502. auto res = cli.Get("/");
  10503. ASSERT_TRUE(res);
  10504. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10505. }
  10506. // The custom CA remains effective when combined with the system CA
  10507. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  10508. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10509. ASSERT_TRUE(svr.is_valid());
  10510. svr.Get("/test", [&](const Request &, Response &res) {
  10511. res.set_content("test", "text/plain");
  10512. });
  10513. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10514. auto se = detail::scope_exit([&] {
  10515. svr.stop();
  10516. t.join();
  10517. ASSERT_FALSE(svr.is_running());
  10518. });
  10519. svr.wait_until_ready();
  10520. SSLClient cli("127.0.0.1", PORT);
  10521. std::string cert;
  10522. read_file(SERVER_CERT2_FILE, cert);
  10523. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10524. cli.enable_system_ca(true);
  10525. cli.enable_server_certificate_verification(true);
  10526. cli.set_connection_timeout(30);
  10527. auto res = cli.Get("/test");
  10528. ASSERT_TRUE(res);
  10529. ASSERT_EQ(StatusCode::OK_200, res->status);
  10530. }
  10531. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  10532. // skip chain verification entirely (only the certificate identity was
  10533. // checked), so a server presenting an untrusted certificate with a matching
  10534. // IP SAN was accepted. The chain must be validated for IP hosts too.
  10535. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  10536. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10537. ASSERT_TRUE(svr.is_valid());
  10538. svr.Get("/test", [&](const Request &, Response &res) {
  10539. res.set_content("test", "text/plain");
  10540. });
  10541. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10542. auto se = detail::scope_exit([&] {
  10543. svr.stop();
  10544. t.join();
  10545. ASSERT_FALSE(svr.is_running());
  10546. });
  10547. svr.wait_until_ready();
  10548. SSLClient cli("127.0.0.1", PORT);
  10549. std::string cert;
  10550. // A trusted CA that did not sign the server certificate. The server cert
  10551. // (cert2) carries the matching IP SAN, so only chain validation can reject
  10552. // this connection.
  10553. read_file(CLIENT_CA_CERT_FILE, cert);
  10554. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10555. cli.enable_server_certificate_verification(true);
  10556. cli.set_connection_timeout(30);
  10557. auto res = cli.Get("/test");
  10558. ASSERT_FALSE(res);
  10559. }
  10560. // enable_system_ca(false) prevents system CA loading entirely
  10561. TEST(SSLClientTest, DisableSystemCa_Online) {
  10562. SSLClient cli("google.com");
  10563. cli.enable_system_ca(false);
  10564. cli.enable_server_certificate_verification(true);
  10565. auto res = cli.Get("/");
  10566. ASSERT_FALSE(res);
  10567. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  10568. // itself when the CA chain is empty
  10569. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  10570. res.error() == Error::SSLConnection);
  10571. }
  10572. // The universal Client forwards enable_system_ca()
  10573. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  10574. std::string cert;
  10575. read_file(SERVER_CERT2_FILE, cert);
  10576. Client cli("https://google.com");
  10577. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10578. cli.enable_system_ca(true);
  10579. cli.enable_server_certificate_verification(true);
  10580. auto res = cli.Get("/");
  10581. ASSERT_TRUE(res);
  10582. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10583. }
  10584. // The system CA policy must carry over to the client created internally for
  10585. // following a cross-host HTTPS redirect
  10586. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  10587. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10588. ASSERT_TRUE(svr.is_valid());
  10589. svr.Get("/index", [&](const Request &, Response &res) {
  10590. res.set_redirect("https://www.google.com/");
  10591. });
  10592. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10593. auto se = detail::scope_exit([&] {
  10594. svr.stop();
  10595. t.join();
  10596. ASSERT_FALSE(svr.is_running());
  10597. });
  10598. svr.wait_until_ready();
  10599. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  10600. std::string cert;
  10601. read_file(SERVER_CERT2_FILE, cert);
  10602. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10603. cli.enable_system_ca(true);
  10604. cli.enable_server_certificate_verification(true);
  10605. cli.set_follow_location(true);
  10606. cli.set_connection_timeout(30);
  10607. // Receiving any response proves the redirect client completed the TLS
  10608. // handshake with a system-CA-signed host
  10609. auto res = cli.Get("/index");
  10610. ASSERT_TRUE(res);
  10611. }
  10612. TEST(MultipartFormDataTest, LargeData) {
  10613. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10614. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  10615. const ContentReader &content_reader) {
  10616. if (req.is_multipart_form_data()) {
  10617. std::vector<FormData> items;
  10618. content_reader(
  10619. [&](const FormData &file) {
  10620. items.push_back(file);
  10621. return true;
  10622. },
  10623. [&](const char *data, size_t data_length) {
  10624. items.back().content.append(data, data_length);
  10625. return true;
  10626. });
  10627. EXPECT_TRUE(std::string(items[0].name) == "document");
  10628. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  10629. EXPECT_TRUE(items[0].filename == "2MB_data");
  10630. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  10631. EXPECT_TRUE(items[1].name == "hello");
  10632. EXPECT_TRUE(items[1].content == "world");
  10633. EXPECT_TRUE(items[1].filename == "");
  10634. EXPECT_TRUE(items[1].content_type == "");
  10635. } else {
  10636. std::string body;
  10637. content_reader([&](const char *data, size_t data_length) {
  10638. body.append(data, data_length);
  10639. return true;
  10640. });
  10641. }
  10642. });
  10643. auto port = svr.bind_to_any_port(HOST);
  10644. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10645. auto se = detail::scope_exit([&] {
  10646. svr.stop();
  10647. t.join();
  10648. ASSERT_FALSE(svr.is_running());
  10649. });
  10650. svr.wait_until_ready();
  10651. {
  10652. std::string data(1024 * 1024 * 2, '.');
  10653. std::stringstream buffer;
  10654. buffer << data;
  10655. SSLClient cli(HOST, port);
  10656. cli.enable_server_certificate_verification(false);
  10657. UploadFormDataItems items{
  10658. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10659. {"hello", "world", "", ""},
  10660. };
  10661. auto res = cli.Post("/post", items);
  10662. ASSERT_TRUE(res);
  10663. ASSERT_EQ(StatusCode::OK_200, res->status);
  10664. }
  10665. }
  10666. TEST(MultipartFormDataTest, DataProviderItems) {
  10667. std::random_device seed_gen;
  10668. std::mt19937 random(seed_gen());
  10669. std::string rand1;
  10670. rand1.resize(1000);
  10671. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  10672. std::string rand2;
  10673. rand2.resize(3000);
  10674. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  10675. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10676. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  10677. const ContentReader &content_reader) {
  10678. ASSERT_FALSE(req.is_multipart_form_data());
  10679. std::string body;
  10680. content_reader([&](const char *data, size_t data_length) {
  10681. body.append(data, data_length);
  10682. return true;
  10683. });
  10684. EXPECT_EQ(body, "");
  10685. });
  10686. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  10687. const ContentReader &content_reader) {
  10688. ASSERT_TRUE(req.is_multipart_form_data());
  10689. std::vector<FormData> items;
  10690. content_reader(
  10691. [&](const FormData &file) {
  10692. items.push_back(file);
  10693. return true;
  10694. },
  10695. [&](const char *data, size_t data_length) {
  10696. items.back().content.append(data, data_length);
  10697. return true;
  10698. });
  10699. ASSERT_TRUE(items.size() == 2);
  10700. EXPECT_EQ(std::string(items[0].name), "name1");
  10701. EXPECT_EQ(items[0].content, "Testing123");
  10702. EXPECT_EQ(items[0].filename, "filename1");
  10703. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  10704. EXPECT_EQ(items[1].name, "name2");
  10705. EXPECT_EQ(items[1].content, "Testing456");
  10706. EXPECT_EQ(items[1].filename, "");
  10707. EXPECT_EQ(items[1].content_type, "");
  10708. });
  10709. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  10710. const ContentReader &content_reader) {
  10711. ASSERT_TRUE(req.is_multipart_form_data());
  10712. std::vector<FormData> items;
  10713. content_reader(
  10714. [&](const FormData &file) {
  10715. items.push_back(file);
  10716. return true;
  10717. },
  10718. [&](const char *data, size_t data_length) {
  10719. items.back().content.append(data, data_length);
  10720. return true;
  10721. });
  10722. ASSERT_TRUE(items.size() == 2);
  10723. EXPECT_EQ(items[0].name, "name3");
  10724. EXPECT_EQ(items[0].content, rand1);
  10725. EXPECT_EQ(items[0].filename, "filename3");
  10726. EXPECT_EQ(items[0].content_type, "");
  10727. EXPECT_EQ(items[1].name, "name4");
  10728. EXPECT_EQ(items[1].content, rand2);
  10729. EXPECT_EQ(items[1].filename, "filename4");
  10730. EXPECT_EQ(items[1].content_type, "");
  10731. });
  10732. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  10733. const ContentReader &content_reader) {
  10734. ASSERT_TRUE(req.is_multipart_form_data());
  10735. std::vector<FormData> items;
  10736. content_reader(
  10737. [&](const FormData &file) {
  10738. items.push_back(file);
  10739. return true;
  10740. },
  10741. [&](const char *data, size_t data_length) {
  10742. items.back().content.append(data, data_length);
  10743. return true;
  10744. });
  10745. ASSERT_TRUE(items.size() == 4);
  10746. EXPECT_EQ(std::string(items[0].name), "name1");
  10747. EXPECT_EQ(items[0].content, "Testing123");
  10748. EXPECT_EQ(items[0].filename, "filename1");
  10749. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  10750. EXPECT_EQ(items[1].name, "name2");
  10751. EXPECT_EQ(items[1].content, "Testing456");
  10752. EXPECT_EQ(items[1].filename, "");
  10753. EXPECT_EQ(items[1].content_type, "");
  10754. EXPECT_EQ(items[2].name, "name3");
  10755. EXPECT_EQ(items[2].content, rand1);
  10756. EXPECT_EQ(items[2].filename, "filename3");
  10757. EXPECT_EQ(items[2].content_type, "");
  10758. EXPECT_EQ(items[3].name, "name4");
  10759. EXPECT_EQ(items[3].content, rand2);
  10760. EXPECT_EQ(items[3].filename, "filename4");
  10761. EXPECT_EQ(items[3].content_type, "");
  10762. });
  10763. auto port = svr.bind_to_any_port("localhost");
  10764. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10765. auto se = detail::scope_exit([&] {
  10766. svr.stop();
  10767. t.join();
  10768. ASSERT_FALSE(svr.is_running());
  10769. });
  10770. svr.wait_until_ready();
  10771. {
  10772. SSLClient cli("localhost", port);
  10773. cli.enable_server_certificate_verification(false);
  10774. UploadFormDataItems items{
  10775. {"name1", "Testing123", "filename1", "application/octet-stream"},
  10776. {"name2", "Testing456", "", ""}, // not a file
  10777. };
  10778. {
  10779. auto res = cli.Post("/post-none", {}, {}, {});
  10780. ASSERT_TRUE(res);
  10781. ASSERT_EQ(StatusCode::OK_200, res->status);
  10782. }
  10783. FormDataProviderItems providers;
  10784. {
  10785. auto res =
  10786. cli.Post("/post-items", {}, items, providers); // empty providers
  10787. ASSERT_TRUE(res);
  10788. ASSERT_EQ(StatusCode::OK_200, res->status);
  10789. }
  10790. providers.push_back({"name3",
  10791. [&](size_t offset, httplib::DataSink &sink) -> bool {
  10792. // test the offset is given correctly at each step
  10793. if (!offset)
  10794. sink.os.write(rand1.data(), 30);
  10795. else if (offset == 30)
  10796. sink.os.write(rand1.data() + 30, 300);
  10797. else if (offset == 330)
  10798. sink.os.write(rand1.data() + 330, 670);
  10799. else if (offset == rand1.size())
  10800. sink.done();
  10801. return true;
  10802. },
  10803. "filename3",
  10804. {}});
  10805. providers.push_back({"name4",
  10806. [&](size_t offset, httplib::DataSink &sink) -> bool {
  10807. // test the offset is given correctly at each step
  10808. if (!offset)
  10809. sink.os.write(rand2.data(), 2000);
  10810. else if (offset == 2000)
  10811. sink.os.write(rand2.data() + 2000, 1);
  10812. else if (offset == 2001)
  10813. sink.os.write(rand2.data() + 2001, 999);
  10814. else if (offset == rand2.size())
  10815. sink.done();
  10816. return true;
  10817. },
  10818. "filename4",
  10819. {}});
  10820. {
  10821. auto res = cli.Post("/post-providers", {}, {}, providers);
  10822. ASSERT_TRUE(res);
  10823. ASSERT_EQ(StatusCode::OK_200, res->status);
  10824. }
  10825. {
  10826. auto res = cli.Post("/post-both", {}, items, providers);
  10827. ASSERT_TRUE(res);
  10828. ASSERT_EQ(StatusCode::OK_200, res->status);
  10829. }
  10830. }
  10831. }
  10832. TEST(MultipartFormDataTest, BadHeader) {
  10833. Server svr;
  10834. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  10835. res.set_content("ok", "text/plain");
  10836. });
  10837. thread t = thread([&] { svr.listen(HOST, PORT); });
  10838. auto se = detail::scope_exit([&] {
  10839. svr.stop();
  10840. t.join();
  10841. ASSERT_FALSE(svr.is_running());
  10842. });
  10843. svr.wait_until_ready();
  10844. const std::string body =
  10845. "This is the preamble. It is to be ignored, though it\r\n"
  10846. "is a handy place for composition agents to include an\r\n"
  10847. "explanatory note to non-MIME conformant readers.\r\n"
  10848. "\r\n"
  10849. "\r\n"
  10850. "--simple boundary\r\n"
  10851. "Content-Disposition: form-data; name=\"field1\"\r\n"
  10852. ": BAD...\r\n"
  10853. "\r\n"
  10854. "value1\r\n"
  10855. "--simple boundary\r\n"
  10856. "Content-Disposition: form-data; name=\"field2\"; "
  10857. "filename=\"example.txt\"\r\n"
  10858. "\r\n"
  10859. "value2\r\n"
  10860. "--simple boundary--\r\n"
  10861. "This is the epilogue. It is also to be ignored.\r\n";
  10862. std::string content_type =
  10863. R"(multipart/form-data; boundary="simple boundary")";
  10864. Client cli(HOST, PORT);
  10865. auto res = cli.Post("/post", body, content_type.c_str());
  10866. ASSERT_TRUE(res);
  10867. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  10868. }
  10869. TEST(MultipartFormDataTest, WithPreamble) {
  10870. Server svr;
  10871. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  10872. res.set_content("ok", "text/plain");
  10873. });
  10874. thread t = thread([&] { svr.listen(HOST, PORT); });
  10875. auto se = detail::scope_exit([&] {
  10876. svr.stop();
  10877. t.join();
  10878. ASSERT_FALSE(svr.is_running());
  10879. });
  10880. svr.wait_until_ready();
  10881. const std::string body =
  10882. "This is the preamble. It is to be ignored, though it\r\n"
  10883. "is a handy place for composition agents to include an\r\n"
  10884. "explanatory note to non-MIME conformant readers.\r\n"
  10885. "\r\n"
  10886. "\r\n"
  10887. "--simple boundary\r\n"
  10888. "Content-Disposition: form-data; name=\"field1\"\r\n"
  10889. "\r\n"
  10890. "value1\r\n"
  10891. "--simple boundary\r\n"
  10892. "Content-Disposition: form-data; name=\"field2\"; "
  10893. "filename=\"example.txt\"\r\n"
  10894. "\r\n"
  10895. "value2\r\n"
  10896. "--simple boundary--\r\n"
  10897. "This is the epilogue. It is also to be ignored.\r\n";
  10898. std::string content_type =
  10899. R"(multipart/form-data; boundary="simple boundary")";
  10900. Client cli(HOST, PORT);
  10901. auto res = cli.Post("/post", body, content_type.c_str());
  10902. ASSERT_TRUE(res);
  10903. EXPECT_EQ(StatusCode::OK_200, res->status);
  10904. }
  10905. TEST(MultipartFormDataTest, PostCustomBoundary) {
  10906. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10907. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  10908. const ContentReader &content_reader) {
  10909. if (req.is_multipart_form_data()) {
  10910. std::vector<FormData> items;
  10911. content_reader(
  10912. [&](const FormData &file) {
  10913. items.push_back(file);
  10914. return true;
  10915. },
  10916. [&](const char *data, size_t data_length) {
  10917. items.back().content.append(data, data_length);
  10918. return true;
  10919. });
  10920. EXPECT_TRUE(std::string(items[0].name) == "document");
  10921. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  10922. EXPECT_TRUE(items[0].filename == "2MB_data");
  10923. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  10924. EXPECT_TRUE(items[1].name == "hello");
  10925. EXPECT_TRUE(items[1].content == "world");
  10926. EXPECT_TRUE(items[1].filename == "");
  10927. EXPECT_TRUE(items[1].content_type == "");
  10928. } else {
  10929. std::string body;
  10930. content_reader([&](const char *data, size_t data_length) {
  10931. body.append(data, data_length);
  10932. return true;
  10933. });
  10934. }
  10935. });
  10936. auto port = svr.bind_to_any_port("localhost");
  10937. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10938. auto se = detail::scope_exit([&] {
  10939. svr.stop();
  10940. t.join();
  10941. ASSERT_FALSE(svr.is_running());
  10942. });
  10943. svr.wait_until_ready();
  10944. {
  10945. std::string data(1024 * 1024 * 2, '.');
  10946. std::stringstream buffer;
  10947. buffer << data;
  10948. SSLClient cli("localhost", port);
  10949. cli.enable_server_certificate_verification(false);
  10950. UploadFormDataItems items{
  10951. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10952. {"hello", "world", "", ""},
  10953. };
  10954. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  10955. ASSERT_TRUE(res);
  10956. ASSERT_EQ(StatusCode::OK_200, res->status);
  10957. }
  10958. }
  10959. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  10960. std::string data(1024 * 1024 * 2, '&');
  10961. std::stringstream buffer;
  10962. buffer << data;
  10963. Client cli("https://localhost:8080");
  10964. UploadFormDataItems items{
  10965. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10966. {"hello", "world", "", ""},
  10967. };
  10968. for (const char &c : " \t\r\n") {
  10969. auto res =
  10970. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  10971. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  10972. ASSERT_FALSE(res);
  10973. }
  10974. }
  10975. TEST(MultipartFormDataTest, PutFormData) {
  10976. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10977. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  10978. const ContentReader &content_reader) {
  10979. if (req.is_multipart_form_data()) {
  10980. std::vector<FormData> items;
  10981. content_reader(
  10982. [&](const FormData &file) {
  10983. items.push_back(file);
  10984. return true;
  10985. },
  10986. [&](const char *data, size_t data_length) {
  10987. items.back().content.append(data, data_length);
  10988. return true;
  10989. });
  10990. EXPECT_TRUE(std::string(items[0].name) == "document");
  10991. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  10992. EXPECT_TRUE(items[0].filename == "2MB_data");
  10993. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  10994. EXPECT_TRUE(items[1].name == "hello");
  10995. EXPECT_TRUE(items[1].content == "world");
  10996. EXPECT_TRUE(items[1].filename == "");
  10997. EXPECT_TRUE(items[1].content_type == "");
  10998. } else {
  10999. std::string body;
  11000. content_reader([&](const char *data, size_t data_length) {
  11001. body.append(data, data_length);
  11002. return true;
  11003. });
  11004. }
  11005. });
  11006. auto port = svr.bind_to_any_port("localhost");
  11007. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11008. auto se = detail::scope_exit([&] {
  11009. svr.stop();
  11010. t.join();
  11011. ASSERT_FALSE(svr.is_running());
  11012. });
  11013. svr.wait_until_ready();
  11014. {
  11015. std::string data(1024 * 1024 * 2, '&');
  11016. std::stringstream buffer;
  11017. buffer << data;
  11018. SSLClient cli("localhost", port);
  11019. cli.enable_server_certificate_verification(false);
  11020. UploadFormDataItems items{
  11021. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11022. {"hello", "world", "", ""},
  11023. };
  11024. auto res = cli.Put("/put", items);
  11025. ASSERT_TRUE(res);
  11026. ASSERT_EQ(StatusCode::OK_200, res->status);
  11027. }
  11028. }
  11029. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  11030. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11031. svr.Put("/put_customboundary",
  11032. [&](const Request &req, const Response & /*res*/,
  11033. const ContentReader &content_reader) {
  11034. if (req.is_multipart_form_data()) {
  11035. std::vector<FormData> items;
  11036. content_reader(
  11037. [&](const FormData &file) {
  11038. items.push_back(file);
  11039. return true;
  11040. },
  11041. [&](const char *data, size_t data_length) {
  11042. items.back().content.append(data, data_length);
  11043. return true;
  11044. });
  11045. EXPECT_TRUE(std::string(items[0].name) == "document");
  11046. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  11047. EXPECT_TRUE(items[0].filename == "2MB_data");
  11048. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  11049. EXPECT_TRUE(items[1].name == "hello");
  11050. EXPECT_TRUE(items[1].content == "world");
  11051. EXPECT_TRUE(items[1].filename == "");
  11052. EXPECT_TRUE(items[1].content_type == "");
  11053. } else {
  11054. std::string body;
  11055. content_reader([&](const char *data, size_t data_length) {
  11056. body.append(data, data_length);
  11057. return true;
  11058. });
  11059. }
  11060. });
  11061. auto port = svr.bind_to_any_port("localhost");
  11062. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11063. auto se = detail::scope_exit([&] {
  11064. svr.stop();
  11065. t.join();
  11066. ASSERT_FALSE(svr.is_running());
  11067. });
  11068. svr.wait_until_ready();
  11069. {
  11070. std::string data(1024 * 1024 * 2, '&');
  11071. std::stringstream buffer;
  11072. buffer << data;
  11073. SSLClient cli("localhost", port);
  11074. cli.enable_server_certificate_verification(false);
  11075. UploadFormDataItems items{
  11076. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11077. {"hello", "world", "", ""},
  11078. };
  11079. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  11080. ASSERT_TRUE(res);
  11081. ASSERT_EQ(StatusCode::OK_200, res->status);
  11082. }
  11083. }
  11084. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  11085. std::string data(1024 * 1024 * 2, '&');
  11086. std::stringstream buffer;
  11087. buffer << data;
  11088. Client cli("https://localhost:8080");
  11089. cli.enable_server_certificate_verification(false);
  11090. UploadFormDataItems items{
  11091. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11092. {"hello", "world", "", ""},
  11093. };
  11094. for (const char &c : " \t\r\n") {
  11095. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  11096. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  11097. ASSERT_FALSE(res);
  11098. }
  11099. }
  11100. TEST(MultipartFormDataTest, AlternateFilename) {
  11101. auto handled = false;
  11102. Server svr;
  11103. svr.Post("/test", [&](const Request &req, Response &res) {
  11104. ASSERT_EQ(2u, req.form.files.size());
  11105. ASSERT_EQ(1u, req.form.fields.size());
  11106. // Test files
  11107. const auto &file1 = req.form.get_file("file1");
  11108. ASSERT_EQ("file1", file1.name);
  11109. ASSERT_EQ("A.txt", file1.filename);
  11110. ASSERT_EQ("text/plain", file1.content_type);
  11111. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  11112. const auto &file2 = req.form.get_file("file2");
  11113. ASSERT_EQ("file2", file2.name);
  11114. ASSERT_EQ("a.html", file2.filename);
  11115. ASSERT_EQ("text/html", file2.content_type);
  11116. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  11117. file2.content);
  11118. // Test text field
  11119. const auto &text = req.form.get_field("text");
  11120. ASSERT_EQ("text default", text);
  11121. res.set_content("ok", "text/plain");
  11122. handled = true;
  11123. });
  11124. thread t = thread([&] { svr.listen(HOST, PORT); });
  11125. auto se = detail::scope_exit([&] {
  11126. svr.stop();
  11127. t.join();
  11128. ASSERT_FALSE(svr.is_running());
  11129. ASSERT_TRUE(handled);
  11130. });
  11131. svr.wait_until_ready();
  11132. auto req = "POST /test HTTP/1.1\r\n"
  11133. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11134. "Content-Length: 399\r\n"
  11135. "\r\n"
  11136. "----------\r\n"
  11137. "Content-Disposition: form-data; name=\"text\"\r\n"
  11138. "\r\n"
  11139. "text default\r\n"
  11140. "----------\r\n"
  11141. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  11142. "filename=\"a.txt\"; name=\"file1\"\r\n"
  11143. "Content-Type: text/plain\r\n"
  11144. "\r\n"
  11145. "Content of a.txt.\r\n"
  11146. "\r\n"
  11147. "----------\r\n"
  11148. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  11149. "\"a.html\"\r\n"
  11150. "Content-Type: text/html\r\n"
  11151. "\r\n"
  11152. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  11153. "\r\n"
  11154. "------------\r\n";
  11155. ASSERT_TRUE(send_request(1, req));
  11156. }
  11157. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  11158. auto handled = false;
  11159. Server svr;
  11160. svr.Post("/test", [&](const Request &req, Response &res) {
  11161. // Case-insensitive "utf-8''" prefix with a long value
  11162. const auto &file = req.form.get_file("file1");
  11163. ASSERT_EQ("file1", file.name);
  11164. // 8000 chars exercises both the Content-Disposition parser and the
  11165. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  11166. // Prior to the fix, std::regex_match on this header would cause O(N)
  11167. // stack recursion in libstdc++, leading to SIGSEGV.
  11168. std::string expected_filename(8000, 'A');
  11169. ASSERT_EQ(expected_filename, file.filename);
  11170. res.set_content("ok", "text/plain");
  11171. handled = true;
  11172. });
  11173. thread t = thread([&] { svr.listen(HOST, PORT); });
  11174. auto se = detail::scope_exit([&] {
  11175. svr.stop();
  11176. t.join();
  11177. ASSERT_FALSE(svr.is_running());
  11178. ASSERT_TRUE(handled);
  11179. });
  11180. svr.wait_until_ready();
  11181. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  11182. // Regression test for GHSA-qq6v-r583-3h69
  11183. std::string long_filename(8000, 'A');
  11184. std::string body = "----------\r\n"
  11185. "Content-Disposition: form-data; name=\"file1\"; "
  11186. "filename*=\"Utf-8''" +
  11187. long_filename +
  11188. "\"\r\n"
  11189. "\r\n"
  11190. "hello\r\n"
  11191. "------------\r\n";
  11192. auto req = "POST /test HTTP/1.1\r\n"
  11193. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11194. "Content-Length: " +
  11195. std::to_string(body.size()) + "\r\n\r\n" + body;
  11196. ASSERT_TRUE(send_request(1, req));
  11197. }
  11198. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  11199. auto handled = false;
  11200. Server svr;
  11201. svr.Post("/test", [&](const Request &req, Response &) {
  11202. ASSERT_EQ(2u, req.form.fields.size());
  11203. const auto &text1 = req.form.get_field("text1");
  11204. ASSERT_EQ("text1", text1);
  11205. const auto &text2 = req.form.get_field("text2");
  11206. ASSERT_EQ("text2", text2);
  11207. handled = true;
  11208. });
  11209. thread t = thread([&] { svr.listen(HOST, PORT); });
  11210. auto se = detail::scope_exit([&] {
  11211. svr.stop();
  11212. t.join();
  11213. ASSERT_FALSE(svr.is_running());
  11214. ASSERT_TRUE(handled);
  11215. });
  11216. svr.wait_until_ready();
  11217. auto req = "POST /test HTTP/1.1\r\n"
  11218. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11219. "Content-Length: 146\r\n"
  11220. "\r\n----------\r\n"
  11221. "Content-Disposition: form-data; name=\"text1\"\r\n"
  11222. "\r\n"
  11223. "text1"
  11224. "\r\n----------\r\n"
  11225. "Content-Disposition: form-data; name=\"text2\"\r\n"
  11226. "\r\n"
  11227. "text2"
  11228. "\r\n------------";
  11229. std::string response;
  11230. ASSERT_TRUE(send_request(1, req, &response));
  11231. ASSERT_EQ("200", response.substr(9, 3));
  11232. }
  11233. TEST(MultipartFormDataTest, ContentLength) {
  11234. auto handled = false;
  11235. Server svr;
  11236. svr.Post("/test", [&](const Request &req, Response &) {
  11237. ASSERT_EQ(2u, req.form.fields.size());
  11238. const auto &text1 = req.form.get_field("text1");
  11239. ASSERT_EQ("text1", text1);
  11240. const auto &text2 = req.form.get_field("text2");
  11241. ASSERT_EQ("text2", text2);
  11242. handled = true;
  11243. });
  11244. thread t = thread([&] { svr.listen(HOST, PORT); });
  11245. auto se = detail::scope_exit([&] {
  11246. svr.stop();
  11247. t.join();
  11248. ASSERT_FALSE(svr.is_running());
  11249. ASSERT_TRUE(handled);
  11250. });
  11251. svr.wait_until_ready();
  11252. auto req = "POST /test HTTP/1.1\r\n"
  11253. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11254. "Content-Length: 167\r\n"
  11255. "\r\n----------\r\n"
  11256. "Content-Disposition: form-data; name=\"text1\"\r\n"
  11257. "Content-Length: 5\r\n"
  11258. "\r\n"
  11259. "text1"
  11260. "\r\n----------\r\n"
  11261. "Content-Disposition: form-data; name=\"text2\"\r\n"
  11262. "\r\n"
  11263. "text2"
  11264. "\r\n------------\r\n";
  11265. std::string response;
  11266. ASSERT_TRUE(send_request(1, req, &response));
  11267. ASSERT_EQ("200", response.substr(9, 3));
  11268. }
  11269. TEST(MultipartFormDataTest, AccessPartHeaders) {
  11270. auto handled = false;
  11271. Server svr;
  11272. svr.Post("/test", [&](const Request &req, Response &) {
  11273. ASSERT_EQ(2u, req.form.fields.size());
  11274. const auto &text1 = req.form.get_field("text1");
  11275. ASSERT_EQ("text1", text1);
  11276. // TODO: Add header access for text fields if needed
  11277. const auto &text2 = req.form.get_field("text2");
  11278. ASSERT_EQ("text2", text2);
  11279. // TODO: Header access for text fields needs to be implemented
  11280. // auto &headers = it->second.headers;
  11281. // ASSERT_EQ(3U, headers.size());
  11282. // auto custom_header = headers.find("x-whatever");
  11283. // ASSERT_TRUE(custom_header != headers.end());
  11284. // ASSERT_NE("customvalue", custom_header->second);
  11285. // ASSERT_EQ("CustomValue", custom_header->second);
  11286. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  11287. handled = true;
  11288. });
  11289. thread t = thread([&] { svr.listen(HOST, PORT); });
  11290. auto se = detail::scope_exit([&] {
  11291. svr.stop();
  11292. t.join();
  11293. ASSERT_FALSE(svr.is_running());
  11294. ASSERT_TRUE(handled);
  11295. });
  11296. svr.wait_until_ready();
  11297. auto req = "POST /test HTTP/1.1\r\n"
  11298. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11299. "Content-Length: 232\r\n"
  11300. "\r\n----------\r\n"
  11301. "Content-Disposition: form-data; name=\"text1\"\r\n"
  11302. "Content-Length: 5\r\n"
  11303. "X-Test: 1\r\n"
  11304. "\r\n"
  11305. "text1"
  11306. "\r\n----------\r\n"
  11307. "Content-Disposition: form-data; name=\"text2\"\r\n"
  11308. "Content-Type: text/plain\r\n"
  11309. "X-Whatever: CustomValue\r\n"
  11310. "\r\n"
  11311. "text2"
  11312. "\r\n------------\r\n"
  11313. "That should be disregarded. Not even read";
  11314. std::string response;
  11315. ASSERT_TRUE(send_request(1, req, &response));
  11316. ASSERT_EQ("200", response.substr(9, 3));
  11317. }
  11318. TEST(MultipartFormDataTest, LargeHeader) {
  11319. auto handled = false;
  11320. Server svr;
  11321. svr.Post("/test", [&](const Request &req, Response &) {
  11322. ASSERT_EQ(1u, req.form.fields.size());
  11323. const auto &text = req.form.get_field("name1");
  11324. ASSERT_EQ("text1", text);
  11325. handled = true;
  11326. });
  11327. thread t = thread([&] { svr.listen(HOST, PORT); });
  11328. auto se = detail::scope_exit([&] {
  11329. svr.stop();
  11330. t.join();
  11331. ASSERT_FALSE(svr.is_running());
  11332. ASSERT_TRUE(handled);
  11333. });
  11334. svr.wait_until_ready();
  11335. auto boundary = std::string("cpp-httplib-multipart-data");
  11336. std::string content = "--" + boundary +
  11337. "\r\n"
  11338. "Content-Disposition: form-data; name=\"name1\"\r\n"
  11339. "\r\n"
  11340. "text1\r\n"
  11341. "--" +
  11342. boundary + "--\r\n";
  11343. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  11344. "Content-Type: multipart/form-data;boundary=" +
  11345. boundary +
  11346. "\r\n"
  11347. "Content-Length: " +
  11348. std::to_string(content.size()) +
  11349. "\r\n"
  11350. "Dummy-Header: ";
  11351. std::string header_suffix = "\r\n"
  11352. "\r\n";
  11353. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  11354. size_t header_dummy_size =
  11355. read_buff_size -
  11356. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  11357. auto header_dummy = std::string(header_dummy_size, '@');
  11358. auto req = header_prefix + header_dummy + header_suffix + content;
  11359. std::string response;
  11360. ASSERT_TRUE(send_request(1, req, &response));
  11361. ASSERT_EQ("200", response.substr(9, 3));
  11362. }
  11363. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  11364. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  11365. // (not chunked Transfer-Encoding) after the streaming refactor.
  11366. auto handled = false;
  11367. Server svr;
  11368. svr.Post("/upload", [&](const Request &req, Response &res) {
  11369. auto cl_it = req.headers.find("Content-Length");
  11370. EXPECT_TRUE(cl_it != req.headers.end());
  11371. auto te_it = req.headers.find("Transfer-Encoding");
  11372. EXPECT_TRUE(te_it == req.headers.end());
  11373. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  11374. res.set_content("ok", "text/plain");
  11375. handled = true;
  11376. });
  11377. auto port = svr.bind_to_any_port(HOST);
  11378. auto t = thread([&] { svr.listen_after_bind(); });
  11379. auto se = detail::scope_exit([&] {
  11380. svr.stop();
  11381. t.join();
  11382. ASSERT_FALSE(svr.is_running());
  11383. ASSERT_TRUE(handled);
  11384. });
  11385. svr.wait_until_ready();
  11386. UploadFormDataItems items = {
  11387. {"field1", "hello", "", "text/plain"},
  11388. {"file1", "world", "test.txt", "application/octet-stream"},
  11389. };
  11390. Client cli(HOST, port);
  11391. auto res = cli.Post("/upload", {}, items);
  11392. ASSERT_TRUE(res);
  11393. EXPECT_EQ(StatusCode::OK_200, res->status);
  11394. }
  11395. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  11396. // Verify that make_multipart_content_provider coalesces many small segments
  11397. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  11398. constexpr size_t kItemCount = 1000;
  11399. UploadFormDataItems items;
  11400. items.reserve(kItemCount);
  11401. for (size_t i = 0; i < kItemCount; i++) {
  11402. items.push_back(
  11403. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  11404. }
  11405. const std::string boundary = "----test-boundary";
  11406. auto content_length = detail::get_multipart_content_length(items, boundary);
  11407. auto provider = detail::make_multipart_content_provider(items, boundary);
  11408. // Drive the provider the same way write_content_with_progress does
  11409. size_t write_count = 0;
  11410. size_t total_bytes = 0;
  11411. DataSink sink;
  11412. size_t offset = 0;
  11413. sink.write = [&](const char *d, size_t l) -> bool {
  11414. (void)d;
  11415. write_count++;
  11416. total_bytes += l;
  11417. offset += l;
  11418. return true;
  11419. };
  11420. sink.is_writable = []() -> bool { return true; };
  11421. while (offset < content_length) {
  11422. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  11423. }
  11424. EXPECT_EQ(content_length, total_bytes);
  11425. // The total number of segments is 3 * kItemCount + 1 = 3001.
  11426. // With buffering into 64KB blocks, write_count should be much smaller.
  11427. auto segment_count = 3 * kItemCount + 1;
  11428. EXPECT_LT(write_count, segment_count / 10);
  11429. }
  11430. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  11431. // Integration test: send many UploadFormDataItems and verify the server
  11432. // receives all of them correctly (#2410).
  11433. constexpr size_t kItemCount = 500;
  11434. auto handled = false;
  11435. Server svr;
  11436. svr.Post("/upload", [&](const Request &req, Response &res) {
  11437. EXPECT_EQ(kItemCount, req.form.fields.size());
  11438. for (size_t i = 0; i < kItemCount; i++) {
  11439. auto key = "field" + std::to_string(i);
  11440. auto val = "value" + std::to_string(i);
  11441. auto it = req.form.fields.find(key);
  11442. if (it != req.form.fields.end()) {
  11443. EXPECT_EQ(val, it->second.content);
  11444. } else {
  11445. ADD_FAILURE() << "Missing field: " << key;
  11446. }
  11447. }
  11448. res.set_content("ok", "text/plain");
  11449. handled = true;
  11450. });
  11451. auto port = svr.bind_to_any_port(HOST);
  11452. auto t = thread([&] { svr.listen_after_bind(); });
  11453. auto se = detail::scope_exit([&] {
  11454. svr.stop();
  11455. t.join();
  11456. ASSERT_FALSE(svr.is_running());
  11457. ASSERT_TRUE(handled);
  11458. });
  11459. svr.wait_until_ready();
  11460. UploadFormDataItems items;
  11461. items.reserve(kItemCount);
  11462. for (size_t i = 0; i < kItemCount; i++) {
  11463. items.push_back(
  11464. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  11465. }
  11466. Client cli(HOST, port);
  11467. auto res = cli.Post("/upload", items);
  11468. ASSERT_TRUE(res);
  11469. EXPECT_EQ(StatusCode::OK_200, res->status);
  11470. }
  11471. TEST(MultipartFormDataTest, MakeFileProvider) {
  11472. // Verify make_file_provider sends a file's contents correctly.
  11473. const std::string file_content(4096, 'Z');
  11474. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  11475. {
  11476. std::ofstream ofs(tmp_path, std::ios::binary);
  11477. ofs.write(file_content.data(),
  11478. static_cast<std::streamsize>(file_content.size()));
  11479. }
  11480. auto handled = false;
  11481. Server svr;
  11482. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  11483. const ContentReader &content_reader) {
  11484. ASSERT_TRUE(req.is_multipart_form_data());
  11485. std::vector<FormData> items;
  11486. content_reader(
  11487. [&](const FormData &file) {
  11488. items.push_back(file);
  11489. return true;
  11490. },
  11491. [&](const char *data, size_t data_length) {
  11492. items.back().content.append(data, data_length);
  11493. return true;
  11494. });
  11495. ASSERT_EQ(1u, items.size());
  11496. EXPECT_EQ("myfile", items[0].name);
  11497. EXPECT_EQ("data.bin", items[0].filename);
  11498. EXPECT_EQ("application/octet-stream", items[0].content_type);
  11499. EXPECT_EQ(file_content, items[0].content);
  11500. handled = true;
  11501. });
  11502. auto port = svr.bind_to_any_port(HOST);
  11503. auto t = thread([&] { svr.listen_after_bind(); });
  11504. auto se = detail::scope_exit([&] {
  11505. svr.stop();
  11506. t.join();
  11507. ASSERT_FALSE(svr.is_running());
  11508. ASSERT_TRUE(handled);
  11509. std::remove(tmp_path.c_str());
  11510. });
  11511. svr.wait_until_ready();
  11512. FormDataProviderItems providers;
  11513. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  11514. "application/octet-stream"));
  11515. Client cli(HOST, port);
  11516. auto res = cli.Post("/upload", {}, {}, providers);
  11517. ASSERT_TRUE(res);
  11518. EXPECT_EQ(StatusCode::OK_200, res->status);
  11519. }
  11520. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  11521. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  11522. // (100) headers is rejected with a 400 Bad Request response.
  11523. Server svr;
  11524. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  11525. res.set_content("ok", "text/plain");
  11526. });
  11527. thread t = thread([&] { svr.listen(HOST, PORT); });
  11528. auto se = detail::scope_exit([&] {
  11529. svr.stop();
  11530. t.join();
  11531. ASSERT_FALSE(svr.is_running());
  11532. });
  11533. svr.wait_until_ready();
  11534. // Build a multipart part with 101 custom headers (exceeding CPPHTTPLIB_HEADER_MAX_COUNT=100)
  11535. std::stringstream body;
  11536. body << "--simpleboundary\r\n"
  11537. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  11538. for (int i = 0; i < 101; i++) {
  11539. body << "X-Custom-Header-" << i << ": value\r\n";
  11540. }
  11541. body << "\r\n"
  11542. << "value1\r\n"
  11543. << "--simpleboundary--\r\n";
  11544. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  11545. Client cli(HOST, PORT);
  11546. auto res = cli.Post("/post", body.str(), content_type.c_str());
  11547. ASSERT_TRUE(res);
  11548. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  11549. }
  11550. TEST(MakeFileBodyTest, Basic) {
  11551. const std::string file_content(4096, 'Z');
  11552. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  11553. {
  11554. std::ofstream ofs(tmp_path, std::ios::binary);
  11555. ofs.write(file_content.data(),
  11556. static_cast<std::streamsize>(file_content.size()));
  11557. }
  11558. auto handled = false;
  11559. Server svr;
  11560. svr.Post("/upload", [&](const Request &req, Response &res) {
  11561. EXPECT_EQ(file_content, req.body);
  11562. handled = true;
  11563. res.status = StatusCode::OK_200;
  11564. });
  11565. auto port = svr.bind_to_any_port(HOST);
  11566. auto t = thread([&] { svr.listen_after_bind(); });
  11567. auto se = detail::scope_exit([&] {
  11568. svr.stop();
  11569. t.join();
  11570. ASSERT_FALSE(svr.is_running());
  11571. ASSERT_TRUE(handled);
  11572. std::remove(tmp_path.c_str());
  11573. });
  11574. svr.wait_until_ready();
  11575. auto fb = make_file_body(tmp_path);
  11576. ASSERT_GT(fb.first, 0u);
  11577. Client cli(HOST, port);
  11578. auto res =
  11579. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  11580. ASSERT_TRUE(res);
  11581. EXPECT_EQ(StatusCode::OK_200, res->status);
  11582. }
  11583. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  11584. static constexpr unsigned int number_of_tasks{1000000};
  11585. std::atomic_uint count{0};
  11586. std::unique_ptr<TaskQueue> task_queue{
  11587. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  11588. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  11589. auto queued = task_queue->enqueue(
  11590. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  11591. EXPECT_TRUE(queued);
  11592. }
  11593. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  11594. task_queue->shutdown();
  11595. #else
  11596. EXPECT_NO_THROW(task_queue->shutdown());
  11597. #endif
  11598. EXPECT_EQ(number_of_tasks, count.load());
  11599. }
  11600. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  11601. static constexpr unsigned int number_of_tasks{1000000};
  11602. static constexpr unsigned int qlimit{2};
  11603. unsigned int queued_count{0};
  11604. std::atomic_uint count{0};
  11605. std::unique_ptr<TaskQueue> task_queue{
  11606. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  11607. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  11608. if (task_queue->enqueue(
  11609. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  11610. queued_count++;
  11611. }
  11612. }
  11613. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  11614. task_queue->shutdown();
  11615. #else
  11616. EXPECT_NO_THROW(task_queue->shutdown());
  11617. #endif
  11618. EXPECT_EQ(queued_count, count.load());
  11619. EXPECT_TRUE(queued_count <= number_of_tasks);
  11620. EXPECT_TRUE(queued_count >= qlimit);
  11621. }
  11622. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  11623. // Use a short idle timeout so a dynamic thread spawns, times out and
  11624. // exits during the test, and the pool keeps working afterwards.
  11625. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  11626. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  11627. /*idle_timeout_sec=*/1}};
  11628. std::atomic_uint count{0};
  11629. std::condition_variable cv;
  11630. std::mutex mtx;
  11631. bool release = false;
  11632. // Block the base thread so the second task spawns a dynamic thread.
  11633. EXPECT_TRUE(task_queue->enqueue([&] {
  11634. std::unique_lock<std::mutex> lock(mtx);
  11635. while (!release) {
  11636. cv.wait(lock);
  11637. }
  11638. count++;
  11639. }));
  11640. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  11641. // Let the dynamic thread finish its task and exceed the idle timeout.
  11642. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  11643. {
  11644. std::unique_lock<std::mutex> lock(mtx);
  11645. release = true;
  11646. }
  11647. cv.notify_all();
  11648. // The pool must still accept and run tasks after the dynamic thread exited.
  11649. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  11650. task_queue->shutdown();
  11651. EXPECT_EQ(3u, count.load());
  11652. }
  11653. TEST(TaskQueueTest, MaxQueuedRequests) {
  11654. static constexpr unsigned int qlimit{3};
  11655. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  11656. std::condition_variable sem_cv;
  11657. std::mutex sem_mtx;
  11658. int credits = 0;
  11659. bool queued;
  11660. /* Fill up the queue with tasks that will block until we give them credits to
  11661. * complete. */
  11662. for (unsigned int n = 0; n <= qlimit;) {
  11663. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  11664. std::unique_lock<std::mutex> lock(sem_mtx);
  11665. while (credits <= 0) {
  11666. sem_cv.wait(lock);
  11667. }
  11668. /* Consume the credit and signal the test code if they are all gone. */
  11669. if (--credits == 0) { sem_cv.notify_one(); }
  11670. });
  11671. if (n < qlimit) {
  11672. /* The first qlimit enqueues must succeed. */
  11673. EXPECT_TRUE(queued);
  11674. } else {
  11675. /* The last one will succeed only when the worker thread
  11676. * starts and dequeues the first blocking task. Although
  11677. * not necessary for the correctness of this test, we sleep for
  11678. * a short while to avoid busy waiting. */
  11679. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  11680. }
  11681. if (queued) { n++; }
  11682. }
  11683. /* Further enqueues must fail since the queue is full. */
  11684. for (auto i = 0; i < 4; i++) {
  11685. queued = task_queue->enqueue([] {});
  11686. EXPECT_FALSE(queued);
  11687. }
  11688. /* Give the credits to allow the previous tasks to complete. */
  11689. {
  11690. std::unique_lock<std::mutex> lock(sem_mtx);
  11691. credits += qlimit + 1;
  11692. }
  11693. sem_cv.notify_all();
  11694. /* Wait for all the credits to be consumed. */
  11695. {
  11696. std::unique_lock<std::mutex> lock(sem_mtx);
  11697. while (credits > 0) {
  11698. sem_cv.wait(lock);
  11699. }
  11700. }
  11701. /* Check that we are able again to enqueue at least qlimit tasks. */
  11702. for (unsigned int i = 0; i < qlimit; i++) {
  11703. queued = task_queue->enqueue([] {});
  11704. EXPECT_TRUE(queued);
  11705. }
  11706. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  11707. task_queue->shutdown();
  11708. #else
  11709. EXPECT_NO_THROW(task_queue->shutdown());
  11710. #endif
  11711. }
  11712. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  11713. Server svr;
  11714. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11715. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  11716. });
  11717. svr.Get("/hello", [](const Request &req, Response &res) {
  11718. res.set_content(req.get_param_value("key"), "text/plain");
  11719. });
  11720. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11721. auto se = detail::scope_exit([&] {
  11722. svr.stop();
  11723. thread.join();
  11724. ASSERT_FALSE(svr.is_running());
  11725. });
  11726. svr.wait_until_ready();
  11727. {
  11728. Client cli(HOST, PORT);
  11729. cli.set_follow_location(true);
  11730. auto res = cli.Get("/");
  11731. ASSERT_TRUE(res);
  11732. EXPECT_EQ(StatusCode::OK_200, res->status);
  11733. EXPECT_EQ("val&key2=val2", res->body);
  11734. }
  11735. }
  11736. #endif
  11737. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  11738. Server svr;
  11739. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11740. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  11741. });
  11742. svr.Get("/hello", [](const Request &req, Response &res) {
  11743. res.set_content(req.get_param_value("key"), "text/plain");
  11744. });
  11745. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11746. auto se = detail::scope_exit([&] {
  11747. svr.stop();
  11748. thread.join();
  11749. ASSERT_FALSE(svr.is_running());
  11750. });
  11751. svr.wait_until_ready();
  11752. {
  11753. Client cli(HOST, PORT);
  11754. cli.set_follow_location(true);
  11755. auto res = cli.Get("/");
  11756. ASSERT_TRUE(res);
  11757. EXPECT_EQ(StatusCode::OK_200, res->status);
  11758. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  11759. }
  11760. }
  11761. TEST(RedirectTest, RedirectWithPlusInPath) {
  11762. Server svr;
  11763. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11764. res.set_redirect("/a+b");
  11765. });
  11766. // Route pattern uses regex; escape + as \\+
  11767. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  11768. res.set_content(req.path, "text/plain");
  11769. });
  11770. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11771. auto se = detail::scope_exit([&] {
  11772. svr.stop();
  11773. thread.join();
  11774. ASSERT_FALSE(svr.is_running());
  11775. });
  11776. svr.wait_until_ready();
  11777. {
  11778. Client cli(HOST, PORT);
  11779. cli.set_follow_location(true);
  11780. auto res = cli.Get("/");
  11781. ASSERT_TRUE(res);
  11782. EXPECT_EQ(StatusCode::OK_200, res->status);
  11783. EXPECT_EQ("/a+b", res->body);
  11784. }
  11785. }
  11786. #ifdef CPPHTTPLIB_SSL_ENABLED
  11787. TEST(RedirectTest, Issue2185_Online) {
  11788. SSLClient client("github.com");
  11789. client.set_follow_location(true);
  11790. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  11791. "Coollab-Windows.zip");
  11792. ASSERT_TRUE(res);
  11793. EXPECT_EQ(StatusCode::OK_200, res->status);
  11794. EXPECT_EQ(9920427U, res->body.size());
  11795. }
  11796. #endif
  11797. TEST(VulnerabilityTest, CRLFInjection) {
  11798. Server svr;
  11799. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  11800. res.set_content("Hello 1", "text/plain");
  11801. });
  11802. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  11803. res.set_content("Hello 2", "text/plain");
  11804. });
  11805. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  11806. res.set_content("Hello 3", "text/plain");
  11807. });
  11808. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  11809. res.set_content("Hello 4", "text/plain");
  11810. });
  11811. svr.set_logger([](const Request &req, const Response & /*res*/) {
  11812. for (const auto &x : req.headers) {
  11813. auto key = x.first;
  11814. EXPECT_STRNE("evil", key.c_str());
  11815. }
  11816. });
  11817. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11818. auto se = detail::scope_exit([&] {
  11819. svr.stop();
  11820. thread.join();
  11821. ASSERT_FALSE(svr.is_running());
  11822. });
  11823. svr.wait_until_ready();
  11824. {
  11825. Client cli(HOST, PORT);
  11826. cli.Post("/test1", "A=B",
  11827. "application/x-www-form-urlencoded\r\nevil: hello1");
  11828. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  11829. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  11830. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  11831. }
  11832. }
  11833. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  11834. auto server_thread = std::thread([] {
  11835. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11836. default_socket_options(srv);
  11837. sockaddr_in addr{};
  11838. addr.sin_family = AF_INET;
  11839. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  11840. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11841. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11842. ::listen(srv, 1);
  11843. sockaddr_in cli_addr{};
  11844. socklen_t cli_len = sizeof(cli_addr);
  11845. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11846. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  11847. std::string buf_all;
  11848. char buf[2048];
  11849. ssize_t n;
  11850. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  11851. buf_all.append(buf, static_cast<size_t>(n));
  11852. size_t pos;
  11853. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  11854. auto request_block = buf_all.substr(0, pos + 4); // include separator
  11855. auto e = request_block.find("\r\n");
  11856. if (e != std::string::npos) {
  11857. auto request_line = request_block.substr(0, e);
  11858. std::string msg =
  11859. "CRLF injection detected in request line: '" + request_line + "'";
  11860. EXPECT_FALSE(true) << msg;
  11861. }
  11862. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  11863. ::send(cli,
  11864. #ifdef _WIN32
  11865. static_cast<const char *>(resp.c_str()),
  11866. static_cast<int>(resp.size()),
  11867. #else
  11868. resp.c_str(), resp.size(),
  11869. #endif
  11870. 0);
  11871. buf_all.erase(0, pos + 4);
  11872. }
  11873. }
  11874. detail::close_socket(cli);
  11875. detail::close_socket(srv);
  11876. });
  11877. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11878. auto cli = Client("127.0.0.1", PORT + 1);
  11879. auto headers = Headers{
  11880. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  11881. {"Connection", "keep-alive"}};
  11882. auto res = cli.Get("/hi", headers);
  11883. EXPECT_FALSE(res);
  11884. EXPECT_EQ(Error::InvalidHeaders, res.error());
  11885. server_thread.join();
  11886. }
  11887. TEST(PathParamsTest, StaticMatch) {
  11888. const auto pattern = "/users/all";
  11889. detail::PathParamsMatcher matcher(pattern);
  11890. Request request;
  11891. request.path = "/users/all";
  11892. ASSERT_TRUE(matcher.match(request));
  11893. std::unordered_map<std::string, std::string> expected_params = {};
  11894. EXPECT_EQ(request.path_params, expected_params);
  11895. }
  11896. TEST(PathParamsTest, StaticMismatch) {
  11897. const auto pattern = "/users/all";
  11898. detail::PathParamsMatcher matcher(pattern);
  11899. Request request;
  11900. request.path = "/users/1";
  11901. ASSERT_FALSE(matcher.match(request));
  11902. }
  11903. TEST(PathParamsTest, SingleParamInTheMiddle) {
  11904. const auto pattern = "/users/:id/subscriptions";
  11905. detail::PathParamsMatcher matcher(pattern);
  11906. Request request;
  11907. request.path = "/users/42/subscriptions";
  11908. ASSERT_TRUE(matcher.match(request));
  11909. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  11910. EXPECT_EQ(request.path_params, expected_params);
  11911. }
  11912. TEST(PathParamsTest, SingleParamInTheEnd) {
  11913. const auto pattern = "/users/:id";
  11914. detail::PathParamsMatcher matcher(pattern);
  11915. Request request;
  11916. request.path = "/users/24";
  11917. ASSERT_TRUE(matcher.match(request));
  11918. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  11919. EXPECT_EQ(request.path_params, expected_params);
  11920. }
  11921. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  11922. const auto pattern = "/users/:id/";
  11923. detail::PathParamsMatcher matcher(pattern);
  11924. Request request;
  11925. request.path = "/users/42/";
  11926. ASSERT_TRUE(matcher.match(request));
  11927. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  11928. EXPECT_EQ(request.path_params, expected_params);
  11929. }
  11930. TEST(PathParamsTest, EmptyParam) {
  11931. const auto pattern = "/users/:id/";
  11932. detail::PathParamsMatcher matcher(pattern);
  11933. Request request;
  11934. request.path = "/users//";
  11935. ASSERT_TRUE(matcher.match(request));
  11936. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  11937. EXPECT_EQ(request.path_params, expected_params);
  11938. }
  11939. TEST(PathParamsTest, FragmentMismatch) {
  11940. const auto pattern = "/users/:id/";
  11941. detail::PathParamsMatcher matcher(pattern);
  11942. Request request;
  11943. request.path = "/admins/24/";
  11944. ASSERT_FALSE(matcher.match(request));
  11945. }
  11946. TEST(PathParamsTest, ExtraFragments) {
  11947. const auto pattern = "/users/:id";
  11948. detail::PathParamsMatcher matcher(pattern);
  11949. Request request;
  11950. request.path = "/users/42/subscriptions";
  11951. ASSERT_FALSE(matcher.match(request));
  11952. }
  11953. TEST(PathParamsTest, MissingTrailingParam) {
  11954. const auto pattern = "/users/:id";
  11955. detail::PathParamsMatcher matcher(pattern);
  11956. Request request;
  11957. request.path = "/users";
  11958. ASSERT_FALSE(matcher.match(request));
  11959. }
  11960. TEST(PathParamsTest, MissingParamInTheMiddle) {
  11961. const auto pattern = "/users/:id/subscriptions";
  11962. detail::PathParamsMatcher matcher(pattern);
  11963. Request request;
  11964. request.path = "/users/subscriptions";
  11965. ASSERT_FALSE(matcher.match(request));
  11966. }
  11967. TEST(PathParamsTest, MultipleParams) {
  11968. const auto pattern = "/users/:userid/subscriptions/:subid";
  11969. detail::PathParamsMatcher matcher(pattern);
  11970. Request request;
  11971. request.path = "/users/42/subscriptions/2";
  11972. ASSERT_TRUE(matcher.match(request));
  11973. std::unordered_map<std::string, std::string> expected_params = {
  11974. {"userid", "42"}, {"subid", "2"}};
  11975. EXPECT_EQ(request.path_params, expected_params);
  11976. }
  11977. TEST(PathParamsTest, SequenceOfParams) {
  11978. const auto pattern = "/values/:x/:y/:z";
  11979. detail::PathParamsMatcher matcher(pattern);
  11980. Request request;
  11981. request.path = "/values/1/2/3";
  11982. ASSERT_TRUE(matcher.match(request));
  11983. std::unordered_map<std::string, std::string> expected_params = {
  11984. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  11985. EXPECT_EQ(request.path_params, expected_params);
  11986. }
  11987. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  11988. const auto pattern = "/prefix:suffix";
  11989. detail::PathParamsMatcher matcher(pattern);
  11990. Request request;
  11991. request.path = "/prefix:suffix";
  11992. ASSERT_TRUE(matcher.match(request));
  11993. const std::unordered_map<std::string, std::string> expected_params = {};
  11994. EXPECT_EQ(request.path_params, expected_params);
  11995. }
  11996. TEST(ParseUrlTest, VariousPatterns) {
  11997. {
  11998. detail::UrlComponents uc;
  11999. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  12000. EXPECT_EQ("http", uc.scheme);
  12001. EXPECT_EQ("example.com", uc.host);
  12002. EXPECT_EQ("8080", uc.port);
  12003. EXPECT_EQ("/path", uc.path);
  12004. EXPECT_EQ("?q=1", uc.query);
  12005. }
  12006. {
  12007. detail::UrlComponents uc;
  12008. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  12009. EXPECT_EQ("https", uc.scheme);
  12010. EXPECT_EQ("example.com", uc.host);
  12011. EXPECT_TRUE(uc.port.empty());
  12012. EXPECT_EQ("/path", uc.path);
  12013. }
  12014. {
  12015. detail::UrlComponents uc;
  12016. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  12017. EXPECT_EQ("::1", uc.host);
  12018. EXPECT_EQ("8080", uc.port);
  12019. EXPECT_EQ("/path", uc.path);
  12020. }
  12021. {
  12022. detail::UrlComponents uc;
  12023. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  12024. }
  12025. {
  12026. detail::UrlComponents uc;
  12027. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  12028. EXPECT_TRUE(uc.scheme.empty());
  12029. EXPECT_EQ("example.com", uc.host);
  12030. EXPECT_EQ("/path", uc.path);
  12031. EXPECT_EQ("?q=1", uc.query);
  12032. }
  12033. {
  12034. detail::UrlComponents uc;
  12035. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  12036. EXPECT_TRUE(uc.host.empty());
  12037. EXPECT_EQ("/path", uc.path);
  12038. EXPECT_EQ("?q=1", uc.query);
  12039. }
  12040. {
  12041. detail::UrlComponents uc;
  12042. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  12043. EXPECT_EQ("example.com", uc.host);
  12044. EXPECT_EQ("8080", uc.port);
  12045. }
  12046. {
  12047. // Unix socket path — must not be parsed as host
  12048. detail::UrlComponents uc;
  12049. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  12050. EXPECT_TRUE(uc.host.empty());
  12051. }
  12052. {
  12053. detail::UrlComponents uc;
  12054. ASSERT_TRUE(detail::parse_url("", uc));
  12055. EXPECT_TRUE(uc.host.empty());
  12056. EXPECT_TRUE(uc.path.empty());
  12057. }
  12058. {
  12059. detail::UrlComponents uc;
  12060. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  12061. }
  12062. {
  12063. detail::UrlComponents uc;
  12064. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  12065. }
  12066. {
  12067. // Accepted by parse_url; callers restrict to http/https
  12068. detail::UrlComponents uc;
  12069. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  12070. EXPECT_EQ("ftp", uc.scheme);
  12071. }
  12072. {
  12073. detail::UrlComponents uc;
  12074. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  12075. }
  12076. {
  12077. detail::UrlComponents uc;
  12078. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  12079. }
  12080. }
  12081. TEST(ParseUrlTest, FragmentHandling) {
  12082. {
  12083. detail::UrlComponents uc;
  12084. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  12085. EXPECT_EQ("/path", uc.path);
  12086. EXPECT_TRUE(uc.query.empty());
  12087. }
  12088. {
  12089. detail::UrlComponents uc;
  12090. ASSERT_TRUE(detail::parse_url("#frag", uc));
  12091. EXPECT_TRUE(uc.path.empty());
  12092. EXPECT_TRUE(uc.query.empty());
  12093. }
  12094. }
  12095. TEST(ParseUrlTest, UserinfoHandling) {
  12096. // Userinfo with @ but no colon — host includes @
  12097. detail::UrlComponents uc;
  12098. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  12099. EXPECT_EQ("user@host.com", uc.host);
  12100. EXPECT_EQ("/path", uc.path);
  12101. }
  12102. TEST(ParseUrlTest, IPv6EdgeCases) {
  12103. {
  12104. detail::UrlComponents uc;
  12105. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  12106. EXPECT_TRUE(uc.scheme.empty());
  12107. EXPECT_EQ("::1", uc.host);
  12108. EXPECT_EQ("8080", uc.port);
  12109. }
  12110. {
  12111. // Zone ID '%25' is not in [a-fA-F0-9:]
  12112. detail::UrlComponents uc;
  12113. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  12114. }
  12115. }
  12116. TEST(ParseUrlTest, SchemeEdgeCases) {
  12117. {
  12118. detail::UrlComponents uc;
  12119. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  12120. }
  12121. {
  12122. detail::UrlComponents uc;
  12123. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  12124. }
  12125. {
  12126. detail::UrlComponents uc;
  12127. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  12128. }
  12129. }
  12130. TEST(ParseUrlTest, PortEdgeCases) {
  12131. {
  12132. detail::UrlComponents uc;
  12133. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  12134. EXPECT_TRUE(uc.port.empty());
  12135. EXPECT_EQ("/path", uc.path);
  12136. }
  12137. {
  12138. // parse_url accepts any port string; validation is done by parse_port
  12139. detail::UrlComponents uc;
  12140. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  12141. EXPECT_EQ("abc", uc.port);
  12142. }
  12143. }
  12144. TEST(ParseUrlTest, WebSocketPatterns) {
  12145. {
  12146. detail::UrlComponents uc;
  12147. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  12148. EXPECT_EQ("ws", uc.scheme);
  12149. EXPECT_EQ("echo.example.com", uc.host);
  12150. EXPECT_EQ("8080", uc.port);
  12151. EXPECT_EQ("/ws", uc.path);
  12152. }
  12153. {
  12154. detail::UrlComponents uc;
  12155. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  12156. EXPECT_EQ("wss", uc.scheme);
  12157. EXPECT_EQ("echo.example.com", uc.host);
  12158. EXPECT_TRUE(uc.port.empty());
  12159. EXPECT_EQ("/ws", uc.path);
  12160. }
  12161. }
  12162. TEST(ParseUrlTest, QueryOnly) {
  12163. detail::UrlComponents uc;
  12164. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  12165. EXPECT_TRUE(uc.host.empty());
  12166. EXPECT_TRUE(uc.path.empty());
  12167. EXPECT_EQ("?q=1&r=2", uc.query);
  12168. }
  12169. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  12170. detail::UrlComponents uc;
  12171. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  12172. EXPECT_TRUE(uc.scheme.empty());
  12173. EXPECT_EQ("example.com", uc.host);
  12174. EXPECT_EQ("443", uc.port);
  12175. EXPECT_EQ("/path", uc.path);
  12176. }
  12177. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  12178. // If ipv6 regex working, regex match codepath is taken.
  12179. // else port will default to 80 in Client impl
  12180. int clientImplMagicPort = 80;
  12181. int port = 4321;
  12182. // above ports must be different to avoid false negative
  12183. EXPECT_NE(clientImplMagicPort, port);
  12184. std::string ipV6TestURL = "http://[ff06::c3]";
  12185. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  12186. CLIENT_PRIVATE_KEY_FILE);
  12187. EXPECT_EQ(cli.port(), port);
  12188. }
  12189. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  12190. auto file_path = "./www/dir/index.html";
  12191. auto dir_path = "./www/dir";
  12192. detail::FileStat stat_file(file_path);
  12193. EXPECT_TRUE(stat_file.is_file());
  12194. EXPECT_FALSE(stat_file.is_dir());
  12195. detail::FileStat stat_dir(dir_path);
  12196. EXPECT_FALSE(stat_dir.is_file());
  12197. EXPECT_TRUE(stat_dir.is_dir());
  12198. }
  12199. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  12200. // IPv4 with default HTTP port (80)
  12201. EXPECT_EQ("example.com",
  12202. detail::make_host_and_port_string("example.com", 80, false));
  12203. // IPv4 with default HTTPS port (443)
  12204. EXPECT_EQ("example.com",
  12205. detail::make_host_and_port_string("example.com", 443, true));
  12206. // IPv4 with non-default HTTP port
  12207. EXPECT_EQ("example.com:8080",
  12208. detail::make_host_and_port_string("example.com", 8080, false));
  12209. // IPv4 with non-default HTTPS port
  12210. EXPECT_EQ("example.com:8443",
  12211. detail::make_host_and_port_string("example.com", 8443, true));
  12212. // IPv6 with default HTTP port (80)
  12213. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  12214. // IPv6 with default HTTPS port (443)
  12215. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  12216. // IPv6 with non-default HTTP port
  12217. EXPECT_EQ("[::1]:8080",
  12218. detail::make_host_and_port_string("::1", 8080, false));
  12219. // IPv6 with non-default HTTPS port
  12220. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  12221. // IPv6 full address with default port
  12222. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  12223. detail::make_host_and_port_string(
  12224. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  12225. // IPv6 full address with non-default port
  12226. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  12227. detail::make_host_and_port_string(
  12228. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  12229. // IPv6 localhost with non-default port
  12230. EXPECT_EQ("[::1]:3000",
  12231. detail::make_host_and_port_string("::1", 3000, false));
  12232. // IPv6 with zone ID (link-local address) with default port
  12233. EXPECT_EQ("[fe80::1%eth0]",
  12234. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  12235. // IPv6 with zone ID (link-local address) with non-default port
  12236. EXPECT_EQ("[fe80::1%eth0]:8080",
  12237. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  12238. // Edge case: Port 443 with is_ssl=false (should add port)
  12239. EXPECT_EQ("example.com:443",
  12240. detail::make_host_and_port_string("example.com", 443, false));
  12241. // Edge case: Port 80 with is_ssl=true (should add port)
  12242. EXPECT_EQ("example.com:80",
  12243. detail::make_host_and_port_string("example.com", 80, true));
  12244. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  12245. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  12246. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  12247. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  12248. // Security fix: Already bracketed IPv6 should not get double brackets
  12249. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  12250. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  12251. EXPECT_EQ("[::1]:8080",
  12252. detail::make_host_and_port_string("[::1]", 8080, false));
  12253. EXPECT_EQ("[2001:db8::1]:8080",
  12254. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  12255. EXPECT_EQ("[fe80::1%eth0]",
  12256. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  12257. EXPECT_EQ("[fe80::1%eth0]:8080",
  12258. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  12259. // Edge case: Empty host (should return as-is)
  12260. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  12261. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  12262. // This is a known limitation but shouldn't crash
  12263. EXPECT_EQ("[host:name]",
  12264. detail::make_host_and_port_string("host:name", 80, false));
  12265. // Port number edge cases (no validation, but should not crash)
  12266. EXPECT_EQ("example.com:0",
  12267. detail::make_host_and_port_string("example.com", 0, false));
  12268. EXPECT_EQ("example.com:-1",
  12269. detail::make_host_and_port_string("example.com", -1, false));
  12270. EXPECT_EQ("example.com:65535",
  12271. detail::make_host_and_port_string("example.com", 65535, false));
  12272. EXPECT_EQ("example.com:65536",
  12273. detail::make_host_and_port_string("example.com", 65536, false));
  12274. }
  12275. #ifdef CPPHTTPLIB_SSL_ENABLED
  12276. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  12277. httplib::SSLClient cli("roblox.com", 443);
  12278. cli.set_follow_location(true);
  12279. auto res = cli.Get("/");
  12280. ASSERT_TRUE(res);
  12281. EXPECT_EQ(StatusCode::OK_200, res->status);
  12282. }
  12283. #endif
  12284. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  12285. Server svr;
  12286. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  12287. EXPECT_EQ(res.status, 400);
  12288. });
  12289. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12290. auto se = detail::scope_exit([&] {
  12291. svr.stop();
  12292. thread.join();
  12293. ASSERT_FALSE(svr.is_running());
  12294. });
  12295. svr.wait_until_ready();
  12296. Client cli(HOST, PORT);
  12297. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  12298. }
  12299. TEST(InvalidHeaderCharsTest, is_field_name) {
  12300. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  12301. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  12302. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  12303. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  12304. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  12305. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  12306. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  12307. EXPECT_FALSE(detail::fields::is_field_name(""));
  12308. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  12309. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  12310. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  12311. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  12312. }
  12313. TEST(InvalidHeaderCharsTest, is_field_value) {
  12314. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  12315. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  12316. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  12317. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  12318. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  12319. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  12320. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  12321. EXPECT_TRUE(detail::fields::is_field_value(""));
  12322. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  12323. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  12324. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  12325. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  12326. EXPECT_TRUE(detail::fields::is_field_value("0"));
  12327. }
  12328. TEST(InvalidHeaderCharsTest, OnServer) {
  12329. Server svr;
  12330. svr.Get("/test_name", [&](const Request &req, Response &res) {
  12331. std::string header = "Not Set";
  12332. if (req.has_param("header")) { header = req.get_param_value("header"); }
  12333. res.set_header(header, "value");
  12334. res.set_content("Page Content Page Content", "text/plain");
  12335. });
  12336. svr.Get("/test_value", [&](const Request &req, Response &res) {
  12337. std::string header = "Not Set";
  12338. if (req.has_param("header")) { header = req.get_param_value("header"); }
  12339. res.set_header("X-Test", header);
  12340. res.set_content("Page Content Page Content", "text/plain");
  12341. });
  12342. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12343. auto se = detail::scope_exit([&] {
  12344. svr.stop();
  12345. thread.join();
  12346. ASSERT_FALSE(svr.is_running());
  12347. });
  12348. svr.wait_until_ready();
  12349. Client cli(HOST, PORT);
  12350. {
  12351. auto res = cli.Get(
  12352. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  12353. ASSERT_TRUE(res);
  12354. EXPECT_EQ("Page Content Page Content", res->body);
  12355. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  12356. }
  12357. {
  12358. auto res = cli.Get(
  12359. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  12360. ASSERT_TRUE(res);
  12361. EXPECT_EQ("Page Content Page Content", res->body);
  12362. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  12363. }
  12364. }
  12365. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  12366. auto handled = false;
  12367. Server svr;
  12368. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  12369. thread t = thread([&] { svr.listen(HOST, PORT); });
  12370. auto se = detail::scope_exit([&] {
  12371. svr.stop();
  12372. t.join();
  12373. ASSERT_FALSE(svr.is_running());
  12374. ASSERT_FALSE(handled);
  12375. });
  12376. svr.wait_until_ready();
  12377. auto req = "POST /test HTTP/1.1\r\n"
  12378. "Content-Length: x\r\n"
  12379. "\r\n";
  12380. std::string response;
  12381. ASSERT_TRUE(send_request(1, req, &response));
  12382. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  12383. response.substr(0, response.find("\r\n")));
  12384. }
  12385. #ifndef _WIN32
  12386. TEST(Expect100ContinueTest, ServerClosesConnection) {
  12387. static constexpr char reject[] = "Unauthorized";
  12388. static constexpr char accept[] = "Upload accepted";
  12389. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  12390. Server svr;
  12391. svr.set_expect_100_continue_handler(
  12392. [](const Request & /*req*/, Response &res) {
  12393. res.status = StatusCode::Unauthorized_401;
  12394. res.set_content(reject, "text/plain");
  12395. return res.status;
  12396. });
  12397. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  12398. res.set_content(accept, "text/plain");
  12399. });
  12400. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12401. auto se = detail::scope_exit([&] {
  12402. svr.stop();
  12403. thread.join();
  12404. ASSERT_FALSE(svr.is_running());
  12405. });
  12406. svr.wait_until_ready();
  12407. {
  12408. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  12409. curl_easy_init(), &curl_easy_cleanup};
  12410. ASSERT_NE(curl, nullptr);
  12411. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  12412. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  12413. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  12414. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  12415. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  12416. &curl_slist_free_all};
  12417. ASSERT_NE(list, nullptr);
  12418. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  12419. struct read_data {
  12420. size_t read_size;
  12421. size_t total_size;
  12422. } data = {0, total_size};
  12423. using read_callback_t =
  12424. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  12425. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  12426. void *userdata) -> size_t {
  12427. read_data *d = (read_data *)userdata;
  12428. if (!userdata || d->read_size >= d->total_size) { return 0; }
  12429. std::fill_n(ptr, size * nmemb, 'A');
  12430. d->read_size += size * nmemb;
  12431. return size * nmemb;
  12432. };
  12433. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  12434. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  12435. std::vector<char> buffer;
  12436. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  12437. using write_callback_t =
  12438. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  12439. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  12440. void *userdata) -> size_t {
  12441. std::vector<char> *buf = (std::vector<char> *)userdata;
  12442. buf->reserve(buf->size() + size * nmemb + 1);
  12443. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  12444. return size * nmemb;
  12445. };
  12446. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  12447. {
  12448. const auto res = curl_easy_perform(curl.get());
  12449. ASSERT_EQ(res, CURLE_OK);
  12450. }
  12451. {
  12452. auto response_code = long{};
  12453. const auto res =
  12454. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  12455. ASSERT_EQ(res, CURLE_OK);
  12456. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  12457. }
  12458. {
  12459. auto dl = curl_off_t{};
  12460. const auto res =
  12461. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  12462. ASSERT_EQ(res, CURLE_OK);
  12463. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  12464. }
  12465. {
  12466. buffer.push_back('\0');
  12467. ASSERT_STRCASEEQ(buffer.data(), reject);
  12468. }
  12469. }
  12470. }
  12471. #endif
  12472. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  12473. // Regression test for #2458.
  12474. //
  12475. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  12476. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  12477. // ticket can make the client socket spuriously readable during the
  12478. // 100-continue wait. If the readiness is mistaken for an incoming response,
  12479. // the client withholds the body and then blocks reading a response that never
  12480. // comes, failing with `Failed to read connection`.
  12481. //
  12482. // A correct client (like curl) sends the body once no `100 Continue` arrives
  12483. // within the timeout. This raw OpenSSL server deliberately never sends
  12484. // `100 Continue`; the client must still deliver the body and receive 200.
  12485. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  12486. signal(SIGPIPE, SIG_IGN);
  12487. const auto port = PORT + 4;
  12488. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12489. ASSERT_NE(srv, INVALID_SOCKET);
  12490. int opt = 1;
  12491. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  12492. sockaddr_in addr{};
  12493. addr.sin_family = AF_INET;
  12494. addr.sin_port = htons(static_cast<uint16_t>(port));
  12495. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12496. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  12497. ASSERT_EQ(0, ::listen(srv, 1));
  12498. std::atomic<size_t> server_body_bytes{0};
  12499. auto server_thread = std::thread([&] {
  12500. sockaddr_in cli_addr{};
  12501. socklen_t cli_len = sizeof(cli_addr);
  12502. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12503. if (cli == INVALID_SOCKET) { return; }
  12504. // Bound the lifetime of the server side so a buggy client (which never
  12505. // sends the body) cannot make this thread block forever on join.
  12506. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  12507. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  12508. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  12509. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  12510. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  12511. SSL *ssl = SSL_new(ctx);
  12512. SSL_set_fd(ssl, static_cast<int>(cli));
  12513. if (SSL_accept(ssl) > 0) {
  12514. // Read the request headers. Reading here also flushes the TLS 1.3
  12515. // session tickets to the client. Deliberately do NOT send
  12516. // `100 Continue`.
  12517. std::string buf;
  12518. char tmp[1024];
  12519. while (buf.find("\r\n\r\n") == std::string::npos) {
  12520. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  12521. if (n <= 0) { break; }
  12522. buf.append(tmp, static_cast<size_t>(n));
  12523. }
  12524. // A correct client sends the body now; count what arrives.
  12525. auto pos = buf.find("\r\n\r\n");
  12526. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  12527. while (body < 4096) {
  12528. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  12529. if (n <= 0) { break; }
  12530. body += static_cast<size_t>(n);
  12531. }
  12532. server_body_bytes = body;
  12533. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  12534. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  12535. SSL_shutdown(ssl);
  12536. }
  12537. SSL_free(ssl);
  12538. detail::close_socket(cli);
  12539. SSL_CTX_free(ctx);
  12540. });
  12541. auto se = detail::scope_exit([&] {
  12542. server_thread.join();
  12543. detail::close_socket(srv);
  12544. });
  12545. SSLClient cli("127.0.0.1", port);
  12546. cli.enable_server_certificate_verification(false);
  12547. cli.set_connection_timeout(5, 0);
  12548. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  12549. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  12550. std::string body(4096, 'A');
  12551. auto res = cli.Put("/api/test", body, "application/json");
  12552. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  12553. EXPECT_EQ(StatusCode::OK_200, res->status);
  12554. EXPECT_EQ(body.size(), server_body_bytes.load());
  12555. }
  12556. #endif
  12557. template <typename S, typename C>
  12558. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  12559. svr.Get("/stream", [&](const Request &, Response &res) {
  12560. auto data = new std::string("01234567890123456789");
  12561. res.set_content_provider(
  12562. data->size(), "text/plain",
  12563. [&, data](size_t offset, size_t length, DataSink &sink) {
  12564. const size_t DATA_CHUNK_SIZE = 4;
  12565. const auto &d = *data;
  12566. std::this_thread::sleep_for(std::chrono::seconds(1));
  12567. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  12568. return true;
  12569. },
  12570. [data](bool success) {
  12571. EXPECT_FALSE(success);
  12572. delete data;
  12573. });
  12574. });
  12575. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  12576. auto i = new size_t(0);
  12577. res.set_content_provider(
  12578. "text/plain",
  12579. [i](size_t, DataSink &sink) {
  12580. if (*i < 5) {
  12581. std::this_thread::sleep_for(std::chrono::seconds(1));
  12582. sink.write("abcd", 4);
  12583. (*i)++;
  12584. } else {
  12585. sink.done();
  12586. }
  12587. return true;
  12588. },
  12589. [i](bool success) {
  12590. EXPECT_FALSE(success);
  12591. delete i;
  12592. });
  12593. });
  12594. svr.Get("/chunked", [&](const Request &, Response &res) {
  12595. auto i = new size_t(0);
  12596. res.set_chunked_content_provider(
  12597. "text/plain",
  12598. [i](size_t, DataSink &sink) {
  12599. if (*i < 5) {
  12600. std::this_thread::sleep_for(std::chrono::seconds(1));
  12601. sink.os << "abcd";
  12602. (*i)++;
  12603. } else {
  12604. sink.done();
  12605. }
  12606. return true;
  12607. },
  12608. [i](bool success) {
  12609. EXPECT_FALSE(success);
  12610. delete i;
  12611. });
  12612. });
  12613. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12614. auto se = detail::scope_exit([&] {
  12615. svr.stop();
  12616. listen_thread.join();
  12617. ASSERT_FALSE(svr.is_running());
  12618. });
  12619. svr.wait_until_ready();
  12620. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  12621. {
  12622. auto start = std::chrono::steady_clock::now();
  12623. auto res = cli.Get("/stream");
  12624. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12625. std::chrono::steady_clock::now() - start)
  12626. .count();
  12627. ASSERT_FALSE(res);
  12628. EXPECT_EQ(Error::Read, res.error());
  12629. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  12630. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  12631. }
  12632. {
  12633. auto start = std::chrono::steady_clock::now();
  12634. auto res = cli.Get("/stream_without_length");
  12635. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12636. std::chrono::steady_clock::now() - start)
  12637. .count();
  12638. ASSERT_FALSE(res);
  12639. EXPECT_EQ(Error::Read, res.error());
  12640. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  12641. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  12642. }
  12643. {
  12644. auto start = std::chrono::steady_clock::now();
  12645. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  12646. EXPECT_EQ("abcd", string(data, data_length));
  12647. return true;
  12648. });
  12649. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12650. std::chrono::steady_clock::now() - start)
  12651. .count();
  12652. ASSERT_FALSE(res);
  12653. EXPECT_EQ(Error::Read, res.error());
  12654. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  12655. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  12656. }
  12657. }
  12658. TEST(MaxTimeoutTest, ContentStream) {
  12659. time_t timeout = 2000;
  12660. time_t threshold = 200;
  12661. Server svr;
  12662. Client cli("localhost", PORT);
  12663. max_timeout_test(svr, cli, timeout, threshold);
  12664. }
  12665. #ifdef CPPHTTPLIB_SSL_ENABLED
  12666. TEST(MaxTimeoutTest, ContentStreamSSL) {
  12667. time_t timeout = 2000;
  12668. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  12669. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12670. SSLClient cli("localhost", PORT);
  12671. cli.enable_server_certificate_verification(false);
  12672. max_timeout_test(svr, cli, timeout, threshold);
  12673. }
  12674. #endif
  12675. class EventDispatcher {
  12676. public:
  12677. EventDispatcher() {}
  12678. bool wait_event(DataSink *sink) {
  12679. unique_lock<mutex> lk(m_);
  12680. int id = id_;
  12681. // Wait with timeout to prevent hanging if client disconnects
  12682. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  12683. [&] { return cid_ == id; })) {
  12684. return false; // Timeout occurred
  12685. }
  12686. sink->write(message_.data(), message_.size());
  12687. return true;
  12688. }
  12689. void send_event(const string &message) {
  12690. lock_guard<mutex> lk(m_);
  12691. cid_ = id_++;
  12692. message_ = message;
  12693. cv_.notify_all();
  12694. }
  12695. private:
  12696. mutex m_;
  12697. condition_variable cv_;
  12698. atomic_int id_{0};
  12699. atomic_int cid_{-1};
  12700. string message_;
  12701. };
  12702. TEST(ClientInThreadTest, Issue2068) {
  12703. EventDispatcher ed;
  12704. Server svr;
  12705. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  12706. res.set_chunked_content_provider("text/event-stream",
  12707. [&](size_t /*offset*/, DataSink &sink) {
  12708. return ed.wait_event(&sink);
  12709. });
  12710. });
  12711. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  12712. svr.wait_until_ready();
  12713. thread event_thread([&] {
  12714. int id = 0;
  12715. while (svr.is_running()) {
  12716. this_thread::sleep_for(chrono::milliseconds(500));
  12717. std::stringstream ss;
  12718. ss << "data: " << id << "\n\n";
  12719. ed.send_event(ss.str());
  12720. id++;
  12721. }
  12722. });
  12723. auto se = detail::scope_exit([&] {
  12724. svr.stop();
  12725. listen_thread.join();
  12726. event_thread.join();
  12727. ASSERT_FALSE(svr.is_running());
  12728. });
  12729. {
  12730. auto client = detail::make_unique<Client>(HOST, PORT);
  12731. client->set_read_timeout(std::chrono::minutes(10));
  12732. std::atomic<bool> stop{false};
  12733. std::thread t([&] {
  12734. client->Get("/event1",
  12735. [&](const char *, size_t) -> bool { return !stop; });
  12736. });
  12737. std::this_thread::sleep_for(std::chrono::seconds(2));
  12738. stop = true;
  12739. client->stop();
  12740. t.join();
  12741. // Reset client after thread has finished
  12742. client.reset();
  12743. }
  12744. }
  12745. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  12746. auto handled = false;
  12747. Server svr;
  12748. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  12749. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12750. auto se = detail::scope_exit([&] {
  12751. svr.stop();
  12752. t.join();
  12753. ASSERT_FALSE(svr.is_running());
  12754. ASSERT_FALSE(handled);
  12755. });
  12756. svr.wait_until_ready();
  12757. // Two Content-Length headers with different values — must be rejected
  12758. auto req = "POST /test HTTP/1.1\r\n"
  12759. "Content-Length: 5\r\n"
  12760. "Content-Length: 10\r\n"
  12761. "\r\n"
  12762. "hello";
  12763. std::string response;
  12764. ASSERT_TRUE(send_request(1, req, &response));
  12765. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  12766. response.substr(0, response.find("\r\n")));
  12767. }
  12768. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  12769. auto handled = false;
  12770. Server svr;
  12771. svr.Post("/test", [&](const Request &, Response &res) {
  12772. handled = true;
  12773. res.set_content("ok", "text/plain");
  12774. });
  12775. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12776. auto se = detail::scope_exit([&] {
  12777. svr.stop();
  12778. t.join();
  12779. ASSERT_FALSE(svr.is_running());
  12780. ASSERT_TRUE(handled);
  12781. });
  12782. svr.wait_until_ready();
  12783. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  12784. auto req = "POST /test HTTP/1.1\r\n"
  12785. "Content-Length: 5\r\n"
  12786. "Content-Length: 5\r\n"
  12787. "\r\n"
  12788. "hello";
  12789. std::string response;
  12790. ASSERT_TRUE(send_request(1, req, &response));
  12791. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  12792. }
  12793. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  12794. Server svr;
  12795. svr.Get("/", [](const Request &req, Response &res) {
  12796. EXPECT_EQ(2U, req.trailers.size());
  12797. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  12798. // Denied
  12799. EXPECT_FALSE(req.has_trailer("Content-Length"));
  12800. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  12801. // Accepted
  12802. EXPECT_TRUE(req.has_trailer("X-Hello"));
  12803. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  12804. EXPECT_TRUE(req.has_trailer("X-World"));
  12805. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  12806. res.set_content("ok", "text/plain");
  12807. });
  12808. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12809. auto se = detail::scope_exit([&] {
  12810. svr.stop();
  12811. t.join();
  12812. ASSERT_FALSE(svr.is_running());
  12813. });
  12814. svr.wait_until_ready();
  12815. const std::string req = "GET / HTTP/1.1\r\n"
  12816. "Transfer-Encoding: chunked\r\n"
  12817. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  12818. "\r\n"
  12819. "0\r\n"
  12820. "Content-Length: 10\r\n"
  12821. "Host: internal.local\r\n"
  12822. "Content-Type: malicious/content\r\n"
  12823. "Cookie: any\r\n"
  12824. "Set-Cookie: any\r\n"
  12825. "X-Forwarded-For: attacker.com\r\n"
  12826. "X-Real-Ip: 1.1.1.1\r\n"
  12827. "X-Hello: hello\r\n"
  12828. "X-World: world\r\n"
  12829. "\r\n";
  12830. std::string res;
  12831. ASSERT_TRUE(send_request(1, req, &res));
  12832. }
  12833. // A direct client that is not listed in trusted_proxies must not be able to
  12834. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  12835. // the peer address on the actual TCP connection determines whether the
  12836. // header is honored.
  12837. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  12838. Server svr;
  12839. // Deliberately does NOT include the loopback address the test client
  12840. // actually connects from, so the direct connection is not a trusted proxy.
  12841. svr.set_trusted_proxies({"203.0.113.66"});
  12842. std::string observed_remote_addr;
  12843. svr.Get("/ip", [&](const Request &req, Response &res) {
  12844. observed_remote_addr = req.remote_addr;
  12845. res.set_content("ok", "text/plain");
  12846. });
  12847. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12848. auto se = detail::scope_exit([&] {
  12849. svr.stop();
  12850. t.join();
  12851. ASSERT_FALSE(svr.is_running());
  12852. });
  12853. svr.wait_until_ready();
  12854. Client cli(HOST, PORT);
  12855. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  12856. ASSERT_TRUE(res);
  12857. EXPECT_EQ(StatusCode::OK_200, res->status);
  12858. // The connecting peer is not a trusted proxy, so the spoofed header must be
  12859. // ignored entirely and the real connection-level address retained.
  12860. EXPECT_TRUE(observed_remote_addr == "::1" ||
  12861. observed_remote_addr == "127.0.0.1");
  12862. }
  12863. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  12864. Server svr;
  12865. std::string observed_remote_addr;
  12866. std::string observed_xff;
  12867. svr.Get("/ip", [&](const Request &req, Response &res) {
  12868. observed_remote_addr = req.remote_addr;
  12869. observed_xff = req.get_header_value("X-Forwarded-For");
  12870. res.set_content("ok", "text/plain");
  12871. });
  12872. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12873. auto se = detail::scope_exit([&] {
  12874. svr.stop();
  12875. t.join();
  12876. ASSERT_FALSE(svr.is_running());
  12877. });
  12878. svr.wait_until_ready();
  12879. Client cli(HOST, PORT);
  12880. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  12881. ASSERT_TRUE(res);
  12882. EXPECT_EQ(StatusCode::OK_200, res->status);
  12883. EXPECT_EQ(observed_xff, "203.0.113.66");
  12884. EXPECT_TRUE(observed_remote_addr == "::1" ||
  12885. observed_remote_addr == "127.0.0.1");
  12886. }
  12887. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  12888. Server svr;
  12889. svr.set_trusted_proxies({"203.0.113.66"});
  12890. std::string observed_remote_addr;
  12891. std::string observed_xff;
  12892. svr.Get("/ip", [&](const Request &req, Response &res) {
  12893. observed_remote_addr = req.remote_addr;
  12894. observed_xff = req.get_header_value("X-Forwarded-For");
  12895. res.set_content("ok", "text/plain");
  12896. });
  12897. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12898. auto se = detail::scope_exit([&] {
  12899. svr.stop();
  12900. t.join();
  12901. ASSERT_FALSE(svr.is_running());
  12902. });
  12903. svr.wait_until_ready();
  12904. Client cli(HOST, PORT);
  12905. auto res = cli.Get("/ip");
  12906. ASSERT_TRUE(res);
  12907. EXPECT_EQ(StatusCode::OK_200, res->status);
  12908. EXPECT_EQ(observed_xff, "");
  12909. EXPECT_TRUE(observed_remote_addr == "::1" ||
  12910. observed_remote_addr == "127.0.0.1");
  12911. }
  12912. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  12913. Server svr;
  12914. // Include the loopback address the test client actually connects from, so
  12915. // the direct connection itself is recognized as the trusted proxy hop.
  12916. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  12917. std::string observed_remote_addr;
  12918. std::string observed_xff;
  12919. svr.Get("/ip", [&](const Request &req, Response &res) {
  12920. observed_remote_addr = req.remote_addr;
  12921. observed_xff = req.get_header_value("X-Forwarded-For");
  12922. res.set_content("ok", "text/plain");
  12923. });
  12924. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12925. auto se = detail::scope_exit([&] {
  12926. svr.stop();
  12927. t.join();
  12928. ASSERT_FALSE(svr.is_running());
  12929. });
  12930. svr.wait_until_ready();
  12931. Client cli(HOST, PORT);
  12932. auto res = cli.Get(
  12933. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  12934. ASSERT_TRUE(res);
  12935. EXPECT_EQ(StatusCode::OK_200, res->status);
  12936. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  12937. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  12938. }
  12939. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  12940. Server svr;
  12941. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  12942. std::string observed_remote_addr;
  12943. std::string observed_xff;
  12944. svr.Get("/ip", [&](const Request &req, Response &res) {
  12945. observed_remote_addr = req.remote_addr;
  12946. observed_xff = req.get_header_value("X-Forwarded-For");
  12947. res.set_content("ok", "text/plain");
  12948. });
  12949. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12950. auto se = detail::scope_exit([&] {
  12951. svr.stop();
  12952. t.join();
  12953. ASSERT_FALSE(svr.is_running());
  12954. });
  12955. svr.wait_until_ready();
  12956. Client cli(HOST, PORT);
  12957. auto res = cli.Get(
  12958. "/ip",
  12959. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  12960. ASSERT_TRUE(res);
  12961. EXPECT_EQ(StatusCode::OK_200, res->status);
  12962. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  12963. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  12964. }
  12965. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  12966. Server svr;
  12967. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  12968. std::string observed_remote_addr;
  12969. std::string observed_xff;
  12970. svr.Get("/ip", [&](const Request &req, Response &res) {
  12971. observed_remote_addr = req.remote_addr;
  12972. observed_xff = req.get_header_value("X-Forwarded-For");
  12973. res.set_content("ok", "text/plain");
  12974. });
  12975. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12976. auto se = detail::scope_exit([&] {
  12977. svr.stop();
  12978. t.join();
  12979. ASSERT_FALSE(svr.is_running());
  12980. });
  12981. svr.wait_until_ready();
  12982. Client cli(HOST, PORT);
  12983. auto res = cli.Get(
  12984. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  12985. ASSERT_TRUE(res);
  12986. EXPECT_EQ(StatusCode::OK_200, res->status);
  12987. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  12988. // by the closest hop) is used. The leftmost entry is fully client-controlled
  12989. // and must not be selected.
  12990. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  12991. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  12992. }
  12993. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  12994. Server svr;
  12995. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  12996. std::string observed_remote_addr;
  12997. svr.Get("/ip", [&](const Request &req, Response &res) {
  12998. observed_remote_addr = req.remote_addr;
  12999. res.set_content("ok", "text/plain");
  13000. });
  13001. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13002. auto se = detail::scope_exit([&] {
  13003. svr.stop();
  13004. t.join();
  13005. ASSERT_FALSE(svr.is_running());
  13006. });
  13007. svr.wait_until_ready();
  13008. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  13009. // a forged address and the trusted proxy's own address; the forged value must
  13010. // not win over the address the trusted proxy actually recorded.
  13011. Client cli(HOST, PORT);
  13012. auto res = cli.Get(
  13013. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  13014. ASSERT_TRUE(res);
  13015. EXPECT_EQ(StatusCode::OK_200, res->status);
  13016. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  13017. }
  13018. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  13019. Server svr;
  13020. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  13021. std::string observed_remote_addr;
  13022. std::string observed_xff;
  13023. svr.Get("/ip", [&](const Request &req, Response &res) {
  13024. observed_remote_addr = req.remote_addr;
  13025. observed_xff = req.get_header_value("X-Forwarded-For");
  13026. res.set_content("ok", "text/plain");
  13027. });
  13028. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13029. auto se = detail::scope_exit([&] {
  13030. svr.stop();
  13031. t.join();
  13032. ASSERT_FALSE(svr.is_running());
  13033. });
  13034. svr.wait_until_ready();
  13035. Client cli(HOST, PORT);
  13036. auto res = cli.Get(
  13037. "/ip",
  13038. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  13039. ASSERT_TRUE(res);
  13040. EXPECT_EQ(StatusCode::OK_200, res->status);
  13041. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  13042. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  13043. }
  13044. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  13045. Server svr;
  13046. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  13047. std::string observed_remote_addr;
  13048. std::string observed_xff;
  13049. svr.Get("/ip", [&](const Request &req, Response &res) {
  13050. observed_remote_addr = req.remote_addr;
  13051. observed_xff = req.get_header_value("X-Forwarded-For");
  13052. res.set_content("ok", "text/plain");
  13053. });
  13054. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13055. auto se = detail::scope_exit([&] {
  13056. svr.stop();
  13057. t.join();
  13058. ASSERT_FALSE(svr.is_running());
  13059. });
  13060. svr.wait_until_ready();
  13061. std::string raw_req =
  13062. "GET /ip HTTP/1.1\r\n"
  13063. "Host: localhost\r\n"
  13064. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  13065. "Connection: close\r\n"
  13066. "\r\n";
  13067. std::string out;
  13068. ASSERT_TRUE(send_request(5, raw_req, &out));
  13069. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  13070. // Header parser trims surrounding whitespace of the header value
  13071. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  13072. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  13073. }
  13074. // An X-Forwarded-For header whose value parses to zero IP segments must not
  13075. // crash the server (it used to call front() on an empty vector inside
  13076. // get_client_ip). The connection-level remote address must be retained instead.
  13077. static void run_malformed_xff_test(const std::string &xff_value) {
  13078. Server svr;
  13079. svr.set_trusted_proxies({"192.0.2.45"});
  13080. std::string observed_remote_addr;
  13081. svr.Get("/ip", [&](const Request &req, Response &res) {
  13082. observed_remote_addr = req.remote_addr;
  13083. res.set_content("ok", "text/plain");
  13084. });
  13085. int port = 0;
  13086. thread t = thread([&]() {
  13087. port = svr.bind_to_any_port(HOST);
  13088. svr.listen_after_bind();
  13089. });
  13090. auto se = detail::scope_exit([&] {
  13091. svr.stop();
  13092. t.join();
  13093. ASSERT_FALSE(svr.is_running());
  13094. });
  13095. svr.wait_until_ready();
  13096. Client cli(HOST, port);
  13097. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  13098. ASSERT_TRUE(res);
  13099. EXPECT_EQ(StatusCode::OK_200, res->status);
  13100. EXPECT_TRUE(observed_remote_addr == "::1" ||
  13101. observed_remote_addr == "127.0.0.1");
  13102. }
  13103. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  13104. run_malformed_xff_test("");
  13105. }
  13106. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  13107. run_malformed_xff_test(",");
  13108. }
  13109. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  13110. run_malformed_xff_test(", , ,");
  13111. }
  13112. #ifndef _WIN32
  13113. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  13114. Server svr;
  13115. svr.Post("/post", [&](const Request &req, Response &res) {
  13116. res.set_content(req.body, "text/plain");
  13117. });
  13118. svr.Put("/put", [&](const Request &req, Response &res) {
  13119. res.set_content(req.body, "text/plain");
  13120. });
  13121. svr.Patch("/patch", [&](const Request &req, Response &res) {
  13122. res.set_content(req.body, "text/plain");
  13123. });
  13124. svr.Delete("/delete", [&](const Request &req, Response &res) {
  13125. res.set_content(req.body, "text/plain");
  13126. });
  13127. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13128. auto se = detail::scope_exit([&] {
  13129. svr.stop();
  13130. t.join();
  13131. ASSERT_FALSE(svr.is_running());
  13132. });
  13133. svr.wait_until_ready();
  13134. std::string resp;
  13135. // POST without Content-Length
  13136. ASSERT_TRUE(send_request(5,
  13137. "POST /post HTTP/1.1\r\n"
  13138. "Host: localhost\r\n"
  13139. "Connection: close\r\n"
  13140. "\r\n",
  13141. &resp));
  13142. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  13143. // PUT without Content-Length
  13144. resp.clear();
  13145. ASSERT_TRUE(send_request(5,
  13146. "PUT /put HTTP/1.1\r\n"
  13147. "Host: localhost\r\n"
  13148. "Connection: close\r\n"
  13149. "\r\n",
  13150. &resp));
  13151. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  13152. // PATCH without Content-Length
  13153. resp.clear();
  13154. ASSERT_TRUE(send_request(5,
  13155. "PATCH /patch HTTP/1.1\r\n"
  13156. "Host: localhost\r\n"
  13157. "Connection: close\r\n"
  13158. "\r\n",
  13159. &resp));
  13160. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  13161. // DELETE without Content-Length
  13162. resp.clear();
  13163. ASSERT_TRUE(send_request(5,
  13164. "DELETE /delete HTTP/1.1\r\n"
  13165. "Host: localhost\r\n"
  13166. "Connection: close\r\n"
  13167. "\r\n",
  13168. &resp));
  13169. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  13170. }
  13171. #endif
  13172. //==============================================================================
  13173. // open_stream() Tests
  13174. //==============================================================================
  13175. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  13176. std::string result;
  13177. char buf[8192];
  13178. ssize_t n;
  13179. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13180. result.append(buf, static_cast<size_t>(n));
  13181. }
  13182. return result;
  13183. }
  13184. // Mock stream for unit tests
  13185. class MockStream : public Stream {
  13186. public:
  13187. std::string data;
  13188. size_t pos = 0;
  13189. ssize_t error_after = -1; // -1 = no error
  13190. explicit MockStream(const std::string &d, ssize_t err = -1)
  13191. : data(d), error_after(err) {}
  13192. bool is_readable() const override { return true; }
  13193. bool wait_readable() const override { return true; }
  13194. bool wait_writable() const override { return true; }
  13195. ssize_t read(char *ptr, size_t size) override {
  13196. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  13197. if (pos >= data.size()) return 0;
  13198. size_t limit =
  13199. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  13200. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  13201. std::memcpy(ptr, data.data() + pos, to_read);
  13202. pos += to_read;
  13203. return static_cast<ssize_t>(to_read);
  13204. }
  13205. ssize_t write(const char *, size_t) override { return -1; }
  13206. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  13207. ip = "127.0.0.1";
  13208. port = 0;
  13209. }
  13210. void get_local_ip_and_port(std::string &ip, int &port) const override {
  13211. ip = "127.0.0.1";
  13212. port = 0;
  13213. }
  13214. socket_t socket() const override { return INVALID_SOCKET; }
  13215. time_t duration() const override { return 0; }
  13216. };
  13217. TEST(StreamHandleTest, Basic) {
  13218. ClientImpl::StreamHandle handle;
  13219. EXPECT_FALSE(handle.is_valid());
  13220. handle.response = detail::make_unique<Response>();
  13221. handle.error = Error::Connection;
  13222. EXPECT_FALSE(handle.is_valid());
  13223. handle.error = Error::Success;
  13224. EXPECT_TRUE(handle.is_valid());
  13225. }
  13226. TEST(BodyReaderTest, Basic) {
  13227. MockStream stream("Hello, World!");
  13228. detail::BodyReader reader;
  13229. reader.stream = &stream;
  13230. reader.content_length = 13;
  13231. char buf[32];
  13232. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  13233. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  13234. EXPECT_TRUE(reader.eof);
  13235. }
  13236. TEST(BodyReaderTest, NoStream) {
  13237. detail::BodyReader reader;
  13238. char buf[32];
  13239. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  13240. EXPECT_EQ(Error::Connection, reader.last_error);
  13241. }
  13242. TEST(BodyReaderTest, Error) {
  13243. MockStream stream("Hello, World!", 5);
  13244. detail::BodyReader reader;
  13245. reader.stream = &stream;
  13246. reader.content_length = 13;
  13247. char buf[32];
  13248. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  13249. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  13250. EXPECT_EQ(Error::Read, reader.last_error);
  13251. }
  13252. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  13253. // Mock-based StreamHandle tests relying on private internals are removed.
  13254. class OpenStreamTest : public ::testing::Test {
  13255. protected:
  13256. void SetUp() override {
  13257. svr_.Get("/hello", [](const Request &, Response &res) {
  13258. res.set_content("Hello World!", "text/plain");
  13259. });
  13260. svr_.Get("/large", [](const Request &, Response &res) {
  13261. res.set_content(std::string(10000, 'X'), "text/plain");
  13262. });
  13263. svr_.Get("/chunked", [](const Request &, Response &res) {
  13264. res.set_chunked_content_provider("text/plain",
  13265. [](size_t offset, DataSink &sink) {
  13266. if (offset < 15) {
  13267. sink.write("chunk", 5);
  13268. return true;
  13269. }
  13270. sink.done();
  13271. return true;
  13272. });
  13273. });
  13274. svr_.Get("/compressible", [](const Request &, Response &res) {
  13275. res.set_chunked_content_provider("text/plain", [](size_t offset,
  13276. DataSink &sink) {
  13277. if (offset < 100 * 1024) {
  13278. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  13279. sink.write(chunk.data(), chunk.size());
  13280. return true;
  13281. }
  13282. sink.done();
  13283. return true;
  13284. });
  13285. });
  13286. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  13287. [](const Request & /*req*/, Response &res) {
  13288. auto i = new int(0);
  13289. res.set_header("Trailer", "Content-Length, X-Allowed");
  13290. res.set_chunked_content_provider(
  13291. "text/plain",
  13292. [i](size_t /*offset*/, DataSink &sink) {
  13293. switch (*i) {
  13294. case 0: sink.os << "123"; break;
  13295. case 1: sink.os << "456"; break;
  13296. case 2: sink.os << "789"; break;
  13297. case 3: {
  13298. sink.done_with_trailer(
  13299. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  13300. } break;
  13301. }
  13302. (*i)++;
  13303. return true;
  13304. },
  13305. [i](bool success) {
  13306. EXPECT_TRUE(success);
  13307. delete i;
  13308. });
  13309. });
  13310. // Echo headers endpoint for header-related tests
  13311. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  13312. std::string body;
  13313. for (const auto &h : req.headers) {
  13314. body.append(h.first);
  13315. body.push_back(':');
  13316. body.append(h.second);
  13317. body.push_back('\n');
  13318. }
  13319. res.set_content(body, "text/plain");
  13320. });
  13321. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  13322. std::string body;
  13323. for (const auto &h : req.headers) {
  13324. body.append(h.first);
  13325. body.push_back(':');
  13326. body.append(h.second);
  13327. body.push_back('\n');
  13328. }
  13329. res.set_content(body, "text/plain");
  13330. });
  13331. port_ = svr_.bind_to_any_port("127.0.0.1");
  13332. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  13333. svr_.wait_until_ready();
  13334. }
  13335. void TearDown() override {
  13336. svr_.stop();
  13337. if (thread_.joinable()) thread_.join();
  13338. }
  13339. Server svr_;
  13340. std::thread thread_;
  13341. int port_ = 0;
  13342. };
  13343. TEST_F(OpenStreamTest, Basic) {
  13344. Client cli("127.0.0.1", port_);
  13345. auto handle = cli.open_stream("GET", "/hello");
  13346. EXPECT_TRUE(handle.is_valid());
  13347. EXPECT_EQ("Hello World!", read_all(handle));
  13348. }
  13349. TEST_F(OpenStreamTest, SmallBuffer) {
  13350. Client cli("127.0.0.1", port_);
  13351. auto handle = cli.open_stream("GET", "/hello");
  13352. std::string result;
  13353. char buf[4];
  13354. ssize_t n;
  13355. while ((n = handle.read(buf, sizeof(buf))) > 0)
  13356. result.append(buf, static_cast<size_t>(n));
  13357. EXPECT_EQ("Hello World!", result);
  13358. }
  13359. TEST_F(OpenStreamTest, DefaultHeaders) {
  13360. Client cli("127.0.0.1", port_);
  13361. // open_stream GET should include Host, User-Agent and Accept-Encoding
  13362. {
  13363. auto handle = cli.open_stream("GET", "/echo-headers");
  13364. ASSERT_TRUE(handle.is_valid());
  13365. auto body = read_all(handle);
  13366. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  13367. std::string::npos);
  13368. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  13369. std::string::npos);
  13370. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  13371. }
  13372. // open_stream POST with body and no explicit content_type should NOT add
  13373. // text/plain Content-Type (behavior differs from non-streaming path), but
  13374. // should include Content-Length
  13375. {
  13376. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  13377. ASSERT_TRUE(handle.is_valid());
  13378. auto body = read_all(handle);
  13379. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  13380. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  13381. }
  13382. // open_stream POST with explicit Content-Type should preserve it
  13383. {
  13384. auto handle = cli.open_stream("POST", "/echo-headers", {},
  13385. {{"Content-Type", "application/custom"}},
  13386. "{}", "application/custom");
  13387. ASSERT_TRUE(handle.is_valid());
  13388. auto body = read_all(handle);
  13389. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  13390. }
  13391. // User-specified User-Agent must not be overwritten for stream API
  13392. {
  13393. auto handle = cli.open_stream("GET", "/echo-headers", {},
  13394. {{"User-Agent", "MyAgent/1.2"}});
  13395. ASSERT_TRUE(handle.is_valid());
  13396. auto body = read_all(handle);
  13397. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  13398. }
  13399. }
  13400. TEST_F(OpenStreamTest, Large) {
  13401. Client cli("127.0.0.1", port_);
  13402. auto handle = cli.open_stream("GET", "/large");
  13403. EXPECT_EQ(10000u, read_all(handle).size());
  13404. }
  13405. TEST_F(OpenStreamTest, ConnectionError) {
  13406. Client cli("127.0.0.1", 9999);
  13407. auto handle = cli.open_stream("GET", "/hello");
  13408. EXPECT_FALSE(handle.is_valid());
  13409. }
  13410. TEST_F(OpenStreamTest, Chunked) {
  13411. Client cli("127.0.0.1", port_);
  13412. auto handle = cli.open_stream("GET", "/chunked");
  13413. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  13414. "Transfer-Encoding") == "chunked");
  13415. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  13416. }
  13417. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  13418. Client cli("127.0.0.1", port_);
  13419. auto handle =
  13420. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  13421. ASSERT_TRUE(handle.is_valid());
  13422. // Consume body to allow trailers to be received/parsed
  13423. auto body = read_all(handle);
  13424. // Explicitly parse trailers (ensure trailers are available for assertion)
  13425. handle.parse_trailers_if_needed();
  13426. EXPECT_EQ(std::string("123456789"), body);
  13427. // The response should include a Trailer header declaring both names
  13428. ASSERT_TRUE(handle.response);
  13429. EXPECT_TRUE(handle.response->has_header("Trailer"));
  13430. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  13431. handle.response->get_header_value("Trailer"));
  13432. // Prohibited trailer must not be present
  13433. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  13434. // Allowed trailer should be present
  13435. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  13436. EXPECT_EQ(std::string("yes"),
  13437. handle.response->get_trailer_value("X-Allowed"));
  13438. // Verify trailers are NOT present as regular headers
  13439. EXPECT_EQ(std::string(""),
  13440. handle.response->get_header_value("Content-Length"));
  13441. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  13442. }
  13443. static std::thread serve_single_response(std::promise<int> &port_promise,
  13444. const std::string &response) {
  13445. return std::thread([&port_promise, response] {
  13446. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13447. default_socket_options(srv);
  13448. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13449. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13450. sockaddr_in addr{};
  13451. addr.sin_family = AF_INET;
  13452. addr.sin_port = htons(0); // Let OS assign a free port
  13453. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13454. int opt = 1;
  13455. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13456. #ifdef _WIN32
  13457. reinterpret_cast<const char *>(&opt),
  13458. #else
  13459. &opt,
  13460. #endif
  13461. sizeof(opt));
  13462. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  13463. ::listen(srv, 1) != 0) {
  13464. port_promise.set_value(-1);
  13465. detail::close_socket(srv);
  13466. return;
  13467. }
  13468. socklen_t addr_len = sizeof(addr);
  13469. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  13470. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  13471. sockaddr_in cli_addr{};
  13472. socklen_t cli_len = sizeof(cli_addr);
  13473. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13474. if (cli != INVALID_SOCKET) {
  13475. // Read the complete HTTP request (until the blank line that terminates
  13476. // headers) before sending the response. If the server closes the socket
  13477. // while the client's request data is still unread in the kernel receive
  13478. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  13479. // connection on both sides: it discards the client's receive buffer
  13480. // (which already holds our response) and causes any in-progress write on
  13481. // the client to fail with ECONNRESET. Reading all request data first
  13482. // ensures close() emits a graceful FIN.
  13483. {
  13484. char rbuf[256];
  13485. std::string req;
  13486. while (req.find("\r\n\r\n") == std::string::npos) {
  13487. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  13488. if (n <= 0) { break; }
  13489. req.append(rbuf, static_cast<size_t>(n));
  13490. }
  13491. }
  13492. ::send(cli,
  13493. #ifdef _WIN32
  13494. static_cast<const char *>(response.c_str()),
  13495. static_cast<int>(response.size()),
  13496. #else
  13497. response.c_str(), response.size(),
  13498. #endif
  13499. 0);
  13500. detail::close_socket(cli);
  13501. }
  13502. detail::close_socket(srv);
  13503. });
  13504. }
  13505. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  13506. #ifndef _WIN32
  13507. signal(SIGPIPE, SIG_IGN);
  13508. #endif
  13509. std::promise<int> port_promise;
  13510. auto port_future = port_promise.get_future();
  13511. auto server_thread =
  13512. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  13513. "Content-Type: text/plain\r\n"
  13514. "Content-Length: not-a-number\r\n"
  13515. "Connection: close\r\n"
  13516. "\r\n"
  13517. "hello");
  13518. auto port = port_future.get();
  13519. ASSERT_GT(port, 0);
  13520. Client cli("127.0.0.1", port);
  13521. auto handle = cli.open_stream("GET", "/");
  13522. EXPECT_FALSE(handle.is_valid());
  13523. server_thread.join();
  13524. }
  13525. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  13526. #ifndef _WIN32
  13527. signal(SIGPIPE, SIG_IGN);
  13528. #endif
  13529. std::promise<int> port_promise;
  13530. auto port_future = port_promise.get_future();
  13531. auto server_thread = serve_single_response(
  13532. port_promise, "HTTP/1.1 200 OK\r\n"
  13533. "Content-Type: text/plain\r\n"
  13534. "Content-Length: 99999999999999999999999999\r\n"
  13535. "Connection: close\r\n"
  13536. "\r\n"
  13537. "hello");
  13538. auto port = port_future.get();
  13539. ASSERT_GT(port, 0);
  13540. // Historically std::stoull would throw std::out_of_range here and crash
  13541. // the process, then parsing silently clamped to a bogus framing length and
  13542. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  13543. // so the stream fails to open, matching the not-a-number case above. The
  13544. // process still must NOT terminate.
  13545. Client cli("127.0.0.1", port);
  13546. auto handle = cli.open_stream("GET", "/");
  13547. EXPECT_FALSE(handle.is_valid());
  13548. server_thread.join();
  13549. }
  13550. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13551. TEST_F(OpenStreamTest, Gzip) {
  13552. Client cli("127.0.0.1", port_);
  13553. auto handle = cli.open_stream("GET", "/compressible", {},
  13554. {{"Accept-Encoding", "gzip"}});
  13555. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  13556. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  13557. }
  13558. #endif
  13559. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  13560. TEST_F(OpenStreamTest, Brotli) {
  13561. Client cli("127.0.0.1", port_);
  13562. auto handle =
  13563. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  13564. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  13565. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  13566. }
  13567. #endif
  13568. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  13569. TEST_F(OpenStreamTest, Zstd) {
  13570. Client cli("127.0.0.1", port_);
  13571. auto handle = cli.open_stream("GET", "/compressible", {},
  13572. {{"Accept-Encoding", "zstd"}});
  13573. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  13574. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  13575. }
  13576. #endif
  13577. #ifdef CPPHTTPLIB_SSL_ENABLED
  13578. class SSLOpenStreamTest : public ::testing::Test {
  13579. protected:
  13580. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  13581. void SetUp() override {
  13582. svr_.Get("/hello", [](const Request &, Response &res) {
  13583. res.set_content("Hello SSL World!", "text/plain");
  13584. });
  13585. svr_.Get("/chunked", [](const Request &, Response &res) {
  13586. res.set_chunked_content_provider("text/plain",
  13587. [](size_t offset, DataSink &sink) {
  13588. if (offset < 15) {
  13589. sink.write("chunk", 5);
  13590. return true;
  13591. }
  13592. sink.done();
  13593. return true;
  13594. });
  13595. });
  13596. svr_.Post("/echo", [](const Request &req, Response &res) {
  13597. res.set_content(req.body, req.get_header_value("Content-Type"));
  13598. });
  13599. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  13600. std::string body = req.body;
  13601. res.set_chunked_content_provider(
  13602. "text/plain", [body](size_t offset, DataSink &sink) {
  13603. if (offset < body.size()) {
  13604. sink.write(body.data() + offset, body.size() - offset);
  13605. }
  13606. sink.done();
  13607. return true;
  13608. });
  13609. });
  13610. port_ = svr_.bind_to_any_port("127.0.0.1");
  13611. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  13612. svr_.wait_until_ready();
  13613. }
  13614. void TearDown() override {
  13615. svr_.stop();
  13616. if (thread_.joinable()) thread_.join();
  13617. }
  13618. SSLServer svr_;
  13619. std::thread thread_;
  13620. int port_ = 0;
  13621. };
  13622. TEST_F(SSLOpenStreamTest, Basic) {
  13623. SSLClient cli("127.0.0.1", port_);
  13624. cli.enable_server_certificate_verification(false);
  13625. auto handle = cli.open_stream("GET", "/hello");
  13626. ASSERT_TRUE(handle.is_valid());
  13627. EXPECT_EQ("Hello SSL World!", read_all(handle));
  13628. }
  13629. TEST_F(SSLOpenStreamTest, Chunked) {
  13630. SSLClient cli("127.0.0.1", port_);
  13631. cli.enable_server_certificate_verification(false);
  13632. auto handle = cli.open_stream("GET", "/chunked");
  13633. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  13634. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  13635. "Transfer-Encoding") == "chunked");
  13636. auto body = read_all(handle);
  13637. EXPECT_EQ("chunkchunkchunk", body);
  13638. }
  13639. TEST_F(SSLOpenStreamTest, Post) {
  13640. SSLClient cli("127.0.0.1", port_);
  13641. cli.enable_server_certificate_verification(false);
  13642. auto handle =
  13643. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  13644. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  13645. EXPECT_EQ(200, handle.response->status);
  13646. auto body = read_all(handle);
  13647. EXPECT_EQ("Hello SSL POST", body);
  13648. }
  13649. TEST_F(SSLOpenStreamTest, PostChunked) {
  13650. SSLClient cli("127.0.0.1", port_);
  13651. cli.enable_server_certificate_verification(false);
  13652. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  13653. "Chunked SSL Data", "text/plain");
  13654. ASSERT_TRUE(handle.is_valid());
  13655. EXPECT_EQ(200, handle.response->status);
  13656. auto body = read_all(handle);
  13657. EXPECT_EQ("Chunked SSL Data", body);
  13658. }
  13659. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  13660. // Content-Length is terminated by the server closing the connection. When the
  13661. // SSL peer sends a close_notify after the body, the client must treat it as a
  13662. // clean EOF and return a successful response rather than an error.
  13663. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  13664. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13665. ASSERT_TRUE(svr.is_valid());
  13666. svr.set_keep_alive_max_count(1);
  13667. const std::string expected_body = "Hello from connection-close response!";
  13668. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  13669. res.set_content_provider("text/plain",
  13670. [&](size_t offset, DataSink &sink) -> bool {
  13671. if (offset < expected_body.size()) {
  13672. sink.write(expected_body.data() + offset,
  13673. expected_body.size() - offset);
  13674. }
  13675. sink.done();
  13676. return true;
  13677. });
  13678. });
  13679. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  13680. auto se = detail::scope_exit([&] {
  13681. svr.stop();
  13682. listen_thread.join();
  13683. ASSERT_FALSE(svr.is_running());
  13684. });
  13685. svr.wait_until_ready();
  13686. SSLClient cli(HOST, PORT);
  13687. cli.enable_server_certificate_verification(false);
  13688. auto res = cli.Get("/no-content-length");
  13689. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  13690. EXPECT_EQ(StatusCode::OK_200, res->status);
  13691. EXPECT_EQ(expected_body, res->body);
  13692. }
  13693. #endif // CPPHTTPLIB_SSL_ENABLED
  13694. //==============================================================================
  13695. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  13696. // results for various scenarios.
  13697. //==============================================================================
  13698. TEST(ParityTest, GetVsOpenStream) {
  13699. Server svr;
  13700. const std::string path = "/parity";
  13701. const std::string content = "Parity test content: hello world";
  13702. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  13703. res.set_content(content, "text/plain");
  13704. });
  13705. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13706. auto se = detail::scope_exit([&] {
  13707. svr.stop();
  13708. t.join();
  13709. ASSERT_FALSE(svr.is_running());
  13710. });
  13711. svr.wait_until_ready();
  13712. Client cli(HOST, PORT);
  13713. // Non-stream path
  13714. auto r1 = cli.Get(path);
  13715. ASSERT_TRUE(r1);
  13716. EXPECT_EQ(StatusCode::OK_200, r1->status);
  13717. // Stream path
  13718. auto h = cli.open_stream("GET", path);
  13719. ASSERT_TRUE(h.is_valid());
  13720. EXPECT_EQ(r1->body, read_all(h));
  13721. }
  13722. // Helper to compress data with provided compressor type T
  13723. template <typename Compressor>
  13724. static std::string compress_payload_for_parity(const std::string &in) {
  13725. std::string out;
  13726. Compressor compressor;
  13727. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  13728. [&](const char *data, size_t n) {
  13729. out.append(data, n);
  13730. return true;
  13731. });
  13732. EXPECT_TRUE(ok);
  13733. return out;
  13734. }
  13735. // Helper function for compression parity tests
  13736. template <typename Compressor>
  13737. static void test_compression_parity(const std::string &original,
  13738. const std::string &path,
  13739. const std::string &encoding) {
  13740. const std::string compressed =
  13741. compress_payload_for_parity<Compressor>(original);
  13742. Server svr;
  13743. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  13744. res.set_content(compressed, "application/octet-stream");
  13745. res.set_header("Content-Encoding", encoding);
  13746. });
  13747. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  13748. auto se = detail::scope_exit([&] {
  13749. svr.stop();
  13750. t.join();
  13751. ASSERT_FALSE(svr.is_running());
  13752. });
  13753. svr.wait_until_ready();
  13754. Client cli(HOST, PORT);
  13755. // Non-streaming
  13756. {
  13757. auto res = cli.Get(path);
  13758. ASSERT_TRUE(res);
  13759. EXPECT_EQ(StatusCode::OK_200, res->status);
  13760. EXPECT_EQ(original, res->body);
  13761. }
  13762. // Streaming
  13763. {
  13764. auto h = cli.open_stream("GET", path);
  13765. ASSERT_TRUE(h.is_valid());
  13766. EXPECT_EQ(original, read_all(h));
  13767. }
  13768. }
  13769. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13770. TEST(ParityTest, Gzip) {
  13771. test_compression_parity<detail::gzip_compressor>(
  13772. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  13773. }
  13774. #endif
  13775. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  13776. TEST(ParityTest, Brotli) {
  13777. test_compression_parity<detail::brotli_compressor>(
  13778. "Hello, brotli parity test payload", "/parity-br", "br");
  13779. }
  13780. #endif
  13781. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  13782. TEST(ParityTest, Zstd) {
  13783. test_compression_parity<detail::zstd_compressor>(
  13784. "Zstandard parity test payload", "/parity-zstd", "zstd");
  13785. }
  13786. #endif
  13787. //==============================================================================
  13788. // New Stream API Tests
  13789. //==============================================================================
  13790. inline std::string read_body(httplib::stream::Result &result) {
  13791. std::string body;
  13792. while (result.next()) {
  13793. body.append(result.data(), result.size());
  13794. }
  13795. return body;
  13796. }
  13797. TEST(ClientConnectionTest, Basic) {
  13798. httplib::ClientConnection conn;
  13799. EXPECT_FALSE(conn.is_open());
  13800. conn.sock = 1;
  13801. EXPECT_TRUE(conn.is_open());
  13802. httplib::ClientConnection conn2(std::move(conn));
  13803. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  13804. conn2.sock = INVALID_SOCKET;
  13805. }
  13806. // Unified test server for all stream::* tests
  13807. class StreamApiTest : public ::testing::Test {
  13808. protected:
  13809. void SetUp() override {
  13810. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  13811. res.set_content("Hello World!", "text/plain");
  13812. });
  13813. svr_.Get("/echo-params",
  13814. [](const httplib::Request &req, httplib::Response &res) {
  13815. std::string r;
  13816. for (const auto &p : req.params) {
  13817. if (!r.empty()) r += "&";
  13818. r += p.first + "=" + p.second;
  13819. }
  13820. res.set_content(r, "text/plain");
  13821. });
  13822. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  13823. res.set_content(req.body, req.get_header_value("Content-Type"));
  13824. });
  13825. svr_.Post("/echo-headers",
  13826. [](const httplib::Request &req, httplib::Response &res) {
  13827. std::string r;
  13828. for (const auto &h : req.headers)
  13829. r += h.first + ": " + h.second + "\n";
  13830. res.set_content(r, "text/plain");
  13831. });
  13832. svr_.Post("/echo-params",
  13833. [](const httplib::Request &req, httplib::Response &res) {
  13834. std::string r = "params:";
  13835. for (const auto &p : req.params)
  13836. r += p.first + "=" + p.second + ";";
  13837. res.set_content(r + " body:" + req.body, "text/plain");
  13838. });
  13839. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  13840. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  13841. });
  13842. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  13843. res.set_content("PUT:" + req.body, "text/plain");
  13844. });
  13845. svr_.Patch("/echo",
  13846. [](const httplib::Request &req, httplib::Response &res) {
  13847. res.set_content("PATCH:" + req.body, "text/plain");
  13848. });
  13849. svr_.Delete(
  13850. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  13851. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  13852. "text/plain");
  13853. });
  13854. svr_.Get("/head-test",
  13855. [](const httplib::Request &, httplib::Response &res) {
  13856. res.set_content("body for HEAD", "text/plain");
  13857. });
  13858. svr_.Options("/options",
  13859. [](const httplib::Request &, httplib::Response &res) {
  13860. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  13861. });
  13862. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  13863. svr_.wait_until_ready();
  13864. }
  13865. void TearDown() override {
  13866. svr_.stop();
  13867. if (thread_.joinable()) thread_.join();
  13868. }
  13869. httplib::Server svr_;
  13870. std::thread thread_;
  13871. };
  13872. // stream::Get tests
  13873. TEST_F(StreamApiTest, GetBasic) {
  13874. httplib::Client cli(HOST, PORT);
  13875. auto result = httplib::stream::Get(cli, "/hello");
  13876. ASSERT_TRUE(result.is_valid());
  13877. EXPECT_EQ(200, result.status());
  13878. EXPECT_EQ("Hello World!", read_body(result));
  13879. }
  13880. TEST_F(StreamApiTest, GetWithParams) {
  13881. httplib::Client cli(HOST, PORT);
  13882. httplib::Params params{{"foo", "bar"}};
  13883. auto result = httplib::stream::Get(cli, "/echo-params", params);
  13884. ASSERT_TRUE(result.is_valid());
  13885. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  13886. }
  13887. TEST_F(StreamApiTest, GetConnectionError) {
  13888. httplib::Client cli(HOST, 9999);
  13889. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  13890. }
  13891. TEST_F(StreamApiTest, Get404) {
  13892. httplib::Client cli(HOST, PORT);
  13893. auto result = httplib::stream::Get(cli, "/nonexistent");
  13894. EXPECT_TRUE(result.is_valid());
  13895. EXPECT_EQ(404, result.status());
  13896. }
  13897. // stream::Post tests
  13898. TEST_F(StreamApiTest, PostBasic) {
  13899. httplib::Client cli(HOST, PORT);
  13900. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  13901. "application/json");
  13902. ASSERT_TRUE(result.is_valid());
  13903. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  13904. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  13905. }
  13906. TEST_F(StreamApiTest, PostWithHeaders) {
  13907. httplib::Client cli(HOST, PORT);
  13908. httplib::Headers headers{{"X-Custom", "value"}};
  13909. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  13910. "text/plain");
  13911. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  13912. }
  13913. TEST_F(StreamApiTest, PostWithParams) {
  13914. httplib::Client cli(HOST, PORT);
  13915. httplib::Params params{{"k", "v"}};
  13916. auto result =
  13917. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  13918. auto body = read_body(result);
  13919. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  13920. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  13921. }
  13922. TEST_F(StreamApiTest, PostLarge) {
  13923. httplib::Client cli(HOST, PORT);
  13924. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  13925. size_t total = 0;
  13926. while (result.next()) {
  13927. total += result.size();
  13928. }
  13929. EXPECT_EQ(100u * 1024u, total);
  13930. }
  13931. // stream::Put/Patch tests
  13932. TEST_F(StreamApiTest, PutAndPatch) {
  13933. httplib::Client cli(HOST, PORT);
  13934. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  13935. EXPECT_EQ("PUT:test", read_body(put));
  13936. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  13937. EXPECT_EQ("PATCH:test", read_body(patch));
  13938. }
  13939. // stream::Delete tests
  13940. TEST_F(StreamApiTest, Delete) {
  13941. httplib::Client cli(HOST, PORT);
  13942. auto del1 = httplib::stream::Delete(cli, "/resource");
  13943. EXPECT_EQ("Deleted", read_body(del1));
  13944. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  13945. EXPECT_EQ("Deleted:data", read_body(del2));
  13946. }
  13947. // stream::Head/Options tests
  13948. TEST_F(StreamApiTest, HeadAndOptions) {
  13949. httplib::Client cli(HOST, PORT);
  13950. auto head = httplib::stream::Head(cli, "/head-test");
  13951. EXPECT_TRUE(head.is_valid());
  13952. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  13953. auto opts = httplib::stream::Options(cli, "/options");
  13954. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  13955. }
  13956. // SSL stream::* tests
  13957. #ifdef CPPHTTPLIB_SSL_ENABLED
  13958. class SSLStreamApiTest : public ::testing::Test {
  13959. protected:
  13960. void SetUp() override {
  13961. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  13962. res.set_content("Hello SSL!", "text/plain");
  13963. });
  13964. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  13965. res.set_content(req.body, "text/plain");
  13966. });
  13967. port_ = svr_.bind_to_any_port("127.0.0.1");
  13968. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  13969. svr_.wait_until_ready();
  13970. }
  13971. void TearDown() override {
  13972. svr_.stop();
  13973. if (thread_.joinable()) thread_.join();
  13974. }
  13975. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  13976. std::thread thread_;
  13977. int port_ = 0;
  13978. };
  13979. TEST_F(SSLStreamApiTest, GetAndPost) {
  13980. httplib::SSLClient cli("127.0.0.1", port_);
  13981. cli.enable_server_certificate_verification(false);
  13982. auto get = httplib::stream::Get(cli, "/hello");
  13983. EXPECT_EQ("Hello SSL!", read_body(get));
  13984. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  13985. EXPECT_EQ("test", read_body(post));
  13986. }
  13987. #endif
  13988. // Tests for Error::Timeout and Error::ConnectionClosed error types
  13989. // These errors are set in SocketStream/SSLSocketStream and propagated through
  13990. // BodyReader
  13991. TEST(ErrorHandlingTest, StreamReadTimeout) {
  13992. // Test that read timeout during streaming is detected
  13993. // Use a large content-length response where server delays mid-stream
  13994. Server svr;
  13995. svr.Get("/slow-stream", [](const Request &, Response &res) {
  13996. // Send a large response with delay in the middle
  13997. res.set_content_provider(
  13998. 1000, // content_length
  13999. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  14000. if (offset < 100) {
  14001. // Send first 100 bytes immediately
  14002. std::string data(100, 'A');
  14003. sink.write(data.c_str(), data.size());
  14004. return true;
  14005. }
  14006. // Then delay longer than client timeout
  14007. std::this_thread::sleep_for(std::chrono::seconds(3));
  14008. std::string data(900, 'B');
  14009. sink.write(data.c_str(), data.size());
  14010. return true;
  14011. });
  14012. });
  14013. auto port = 8091;
  14014. std::thread t([&]() { svr.listen("localhost", port); });
  14015. svr.wait_until_ready();
  14016. Client cli("localhost", port);
  14017. cli.set_read_timeout(1, 0); // 1 second timeout
  14018. auto handle = cli.open_stream("GET", "/slow-stream");
  14019. ASSERT_TRUE(handle.is_valid());
  14020. char buf[256];
  14021. ssize_t total = 0;
  14022. ssize_t n;
  14023. bool got_error = false;
  14024. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  14025. total += n;
  14026. }
  14027. if (n < 0) {
  14028. got_error = true;
  14029. // Should be timeout or read error
  14030. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  14031. handle.get_read_error() == Error::Read)
  14032. << "Actual error: " << to_string(handle.get_read_error());
  14033. }
  14034. // Either we got an error, or we got less data than expected
  14035. EXPECT_TRUE(got_error || total < 1000)
  14036. << "Expected timeout but got all " << total << " bytes";
  14037. svr.stop();
  14038. t.join();
  14039. }
  14040. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  14041. // Test connection closed detection via BodyReader
  14042. Server svr;
  14043. std::atomic<bool> close_now{false};
  14044. svr.Get("/will-close", [&](const Request &, Response &res) {
  14045. res.set_content_provider(
  14046. 10000, // Large content_length that we won't fully send
  14047. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  14048. if (offset < 100) {
  14049. std::string data(100, 'X');
  14050. sink.write(data.c_str(), data.size());
  14051. return true;
  14052. }
  14053. // Wait for signal then abort
  14054. while (!close_now) {
  14055. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  14056. }
  14057. return false; // Abort - server will close connection
  14058. });
  14059. });
  14060. auto port = 8092;
  14061. std::thread t([&]() { svr.listen("localhost", port); });
  14062. svr.wait_until_ready();
  14063. Client cli("localhost", port);
  14064. auto handle = cli.open_stream("GET", "/will-close");
  14065. ASSERT_TRUE(handle.is_valid());
  14066. char buf[256];
  14067. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  14068. EXPECT_GT(n, 0) << "First read should succeed";
  14069. // Signal server to close
  14070. close_now = true;
  14071. // Keep reading until error or EOF
  14072. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  14073. // Keep reading
  14074. }
  14075. // Should get an error since content_length wasn't satisfied
  14076. if (n < 0) {
  14077. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  14078. handle.get_read_error() == Error::Read)
  14079. << "Actual error: " << to_string(handle.get_read_error());
  14080. }
  14081. svr.stop();
  14082. t.join();
  14083. }
  14084. #ifdef CPPHTTPLIB_SSL_ENABLED
  14085. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  14086. // Test that read timeout during SSL streaming is detected
  14087. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14088. svr.Get("/slow-stream", [](const Request &, Response &res) {
  14089. res.set_content_provider(
  14090. 1000, "text/plain",
  14091. [](size_t offset, size_t /*length*/, DataSink &sink) {
  14092. if (offset < 100) {
  14093. std::string data(100, 'A');
  14094. sink.write(data.c_str(), data.size());
  14095. return true;
  14096. }
  14097. std::this_thread::sleep_for(std::chrono::seconds(3));
  14098. std::string data(900, 'B');
  14099. sink.write(data.c_str(), data.size());
  14100. return true;
  14101. });
  14102. });
  14103. auto port = 8093;
  14104. std::thread t([&]() { svr.listen("localhost", port); });
  14105. svr.wait_until_ready();
  14106. SSLClient cli("localhost", port);
  14107. cli.enable_server_certificate_verification(false);
  14108. cli.set_read_timeout(1, 0); // 1 second timeout
  14109. auto handle = cli.open_stream("GET", "/slow-stream");
  14110. ASSERT_TRUE(handle.is_valid());
  14111. char buf[256];
  14112. ssize_t total = 0;
  14113. ssize_t n;
  14114. bool got_error = false;
  14115. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  14116. total += n;
  14117. }
  14118. if (n < 0) {
  14119. got_error = true;
  14120. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  14121. handle.get_read_error() == Error::Read)
  14122. << "Actual error: " << to_string(handle.get_read_error());
  14123. }
  14124. EXPECT_TRUE(got_error || total < 1000)
  14125. << "Expected timeout but got all " << total << " bytes";
  14126. svr.stop();
  14127. t.join();
  14128. }
  14129. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  14130. // Test SSL connection closed detection
  14131. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14132. std::atomic<bool> close_now{false};
  14133. svr.Get("/will-close", [&](const Request &, Response &res) {
  14134. res.set_content_provider(
  14135. 10000, "text/plain",
  14136. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  14137. if (offset < 100) {
  14138. std::string data(100, 'X');
  14139. sink.write(data.c_str(), data.size());
  14140. return true;
  14141. }
  14142. while (!close_now) {
  14143. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  14144. }
  14145. return false;
  14146. });
  14147. });
  14148. auto port = 8094;
  14149. std::thread t([&]() { svr.listen("localhost", port); });
  14150. svr.wait_until_ready();
  14151. SSLClient cli("localhost", port);
  14152. cli.enable_server_certificate_verification(false);
  14153. auto handle = cli.open_stream("GET", "/will-close");
  14154. ASSERT_TRUE(handle.is_valid());
  14155. char buf[256];
  14156. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  14157. EXPECT_GT(n, 0);
  14158. // Signal server to close
  14159. close_now = true;
  14160. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  14161. // Keep reading
  14162. }
  14163. if (n < 0) {
  14164. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  14165. handle.get_read_error() == Error::Read)
  14166. << "Actual error: " << to_string(handle.get_read_error());
  14167. }
  14168. svr.stop();
  14169. t.join();
  14170. }
  14171. #endif
  14172. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  14173. using namespace httplib;
  14174. // Create a test file
  14175. const char *fname = "etag_testfile.txt";
  14176. const char *content = "etag-content";
  14177. {
  14178. std::ofstream ofs(fname);
  14179. ofs << content;
  14180. ASSERT_TRUE(ofs.good());
  14181. }
  14182. Server svr;
  14183. svr.set_mount_point("/static", ".");
  14184. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  14185. svr.wait_until_ready();
  14186. Client cli(HOST, PORT);
  14187. // First request: should get 200 with ETag header
  14188. auto res1 = cli.Get("/static/etag_testfile.txt");
  14189. ASSERT_TRUE(res1);
  14190. ASSERT_EQ(200, res1->status);
  14191. ASSERT_TRUE(res1->has_header("ETag"));
  14192. std::string etag = res1->get_header_value("ETag");
  14193. EXPECT_FALSE(etag.empty());
  14194. // Verify ETag format: W/"hex-hex"
  14195. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  14196. EXPECT_EQ('W', etag[0]);
  14197. EXPECT_EQ('/', etag[1]);
  14198. EXPECT_EQ('"', etag[2]);
  14199. EXPECT_EQ('"', etag.back());
  14200. // Exact match: expect 304 Not Modified
  14201. Headers h2 = {{"If-None-Match", etag}};
  14202. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  14203. ASSERT_TRUE(res2);
  14204. EXPECT_EQ(304, res2->status);
  14205. // Wildcard match: expect 304 Not Modified
  14206. Headers h3 = {{"If-None-Match", "*"}};
  14207. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  14208. ASSERT_TRUE(res3);
  14209. EXPECT_EQ(304, res3->status);
  14210. // Non-matching ETag: expect 200
  14211. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  14212. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  14213. ASSERT_TRUE(res4);
  14214. EXPECT_EQ(200, res4->status);
  14215. // Multiple ETags with one matching: expect 304
  14216. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  14217. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  14218. ASSERT_TRUE(res5);
  14219. EXPECT_EQ(304, res5->status);
  14220. svr.stop();
  14221. t.join();
  14222. std::remove(fname);
  14223. }
  14224. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  14225. using namespace httplib;
  14226. Server svr;
  14227. svr.set_mount_point("/static", ".");
  14228. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14229. svr.wait_until_ready();
  14230. Client cli(HOST, PORT);
  14231. // Send If-None-Match: * to a non-existent file
  14232. Headers h = {{"If-None-Match", "*"}};
  14233. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  14234. ASSERT_TRUE(res);
  14235. EXPECT_EQ(404, res->status);
  14236. svr.stop();
  14237. t.join();
  14238. }
  14239. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  14240. using namespace httplib;
  14241. // Create a test file
  14242. const char *fname = "etag_boundary_testfile.txt";
  14243. const char *content = "boundary-test";
  14244. {
  14245. std::ofstream ofs(fname);
  14246. ofs << content;
  14247. ASSERT_TRUE(ofs.good());
  14248. }
  14249. Server svr;
  14250. svr.set_mount_point("/static", ".");
  14251. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  14252. svr.wait_until_ready();
  14253. Client cli(HOST, PORT);
  14254. // Get the actual ETag
  14255. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  14256. ASSERT_TRUE(res1);
  14257. ASSERT_EQ(200, res1->status);
  14258. ASSERT_TRUE(res1->has_header("ETag"));
  14259. std::string etag = res1->get_header_value("ETag");
  14260. // Test 1: Very long ETag value (longer than actual ETag)
  14261. // Should NOT match and return 200 (not trigger out-of-bounds read)
  14262. Headers h1 = {{"If-None-Match", "W/"
  14263. "\"very-long-etag-value-that-is-much-longer-"
  14264. "than-the-actual-etag-value\""}};
  14265. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  14266. ASSERT_TRUE(res2);
  14267. EXPECT_EQ(200, res2->status); // Should not match
  14268. // Test 2: Long string followed by wildcard
  14269. // Should match on "*" and return 304 (without out-of-bounds read on the long
  14270. // string)
  14271. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  14272. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  14273. ASSERT_TRUE(res3);
  14274. EXPECT_EQ(304, res3->status); // Should match on "*"
  14275. // Test 3: Wildcard followed by long string
  14276. // Should match on "*" immediately and return 304
  14277. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  14278. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  14279. ASSERT_TRUE(res4);
  14280. EXPECT_EQ(304, res4->status); // Should match on "*"
  14281. // Test 4: Multiple long non-matching values
  14282. // Should NOT match and return 200 (test that all comparisons are safe)
  14283. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  14284. "W/\"second-long-non-matching-value\", "
  14285. "W/\"third-long-non-matching-value\""}};
  14286. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  14287. ASSERT_TRUE(res5);
  14288. EXPECT_EQ(200, res5->status); // Should not match
  14289. // Test 5: Single character that is not "*" (edge case)
  14290. Headers h5 = {{"If-None-Match", "X"}};
  14291. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  14292. ASSERT_TRUE(res6);
  14293. EXPECT_EQ(200, res6->status); // Should not match
  14294. svr.stop();
  14295. t.join();
  14296. std::remove(fname);
  14297. }
  14298. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  14299. using namespace httplib;
  14300. // Create a test file
  14301. const char *fname = "ims_testfile.txt";
  14302. const char *content = "if-modified-since-test";
  14303. {
  14304. std::ofstream ofs(fname);
  14305. ofs << content;
  14306. ASSERT_TRUE(ofs.good());
  14307. }
  14308. Server svr;
  14309. svr.set_mount_point("/static", ".");
  14310. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14311. svr.wait_until_ready();
  14312. Client cli(HOST, PORT);
  14313. // First request: should get 200 with Last-Modified header
  14314. auto res1 = cli.Get("/static/ims_testfile.txt");
  14315. ASSERT_TRUE(res1);
  14316. ASSERT_EQ(200, res1->status);
  14317. ASSERT_TRUE(res1->has_header("Last-Modified"));
  14318. std::string last_modified = res1->get_header_value("Last-Modified");
  14319. EXPECT_FALSE(last_modified.empty());
  14320. // If-Modified-Since with same time: expect 304
  14321. Headers h2 = {{"If-Modified-Since", last_modified}};
  14322. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  14323. ASSERT_TRUE(res2);
  14324. EXPECT_EQ(304, res2->status);
  14325. // If-Modified-Since with future time: expect 304
  14326. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  14327. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  14328. ASSERT_TRUE(res3);
  14329. EXPECT_EQ(304, res3->status);
  14330. // If-Modified-Since with past time: expect 200
  14331. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  14332. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  14333. ASSERT_TRUE(res4);
  14334. EXPECT_EQ(200, res4->status);
  14335. // If-None-Match takes precedence over If-Modified-Since
  14336. // (send matching ETag with old If-Modified-Since -> should still be 304)
  14337. ASSERT_TRUE(res1->has_header("ETag"));
  14338. std::string etag = res1->get_header_value("ETag");
  14339. Headers h5 = {{"If-None-Match", etag},
  14340. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  14341. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  14342. ASSERT_TRUE(res5);
  14343. EXPECT_EQ(304, res5->status);
  14344. svr.stop();
  14345. t.join();
  14346. std::remove(fname);
  14347. }
  14348. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  14349. using namespace httplib;
  14350. Server svr;
  14351. // Endpoint that returns compressible content
  14352. svr.Get("/compressible", [](const Request &, Response &res) {
  14353. // Return a large enough body to trigger compression
  14354. std::string body(1000, 'a');
  14355. res.set_content(body, "text/plain");
  14356. });
  14357. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14358. svr.wait_until_ready();
  14359. Client cli(HOST, PORT);
  14360. // Request with gzip support: should get Vary header when compressed
  14361. cli.set_compress(true);
  14362. auto res1 = cli.Get("/compressible");
  14363. ASSERT_TRUE(res1);
  14364. EXPECT_EQ(200, res1->status);
  14365. // If Content-Encoding is set, Vary should also be set
  14366. if (res1->has_header("Content-Encoding")) {
  14367. EXPECT_TRUE(res1->has_header("Vary"));
  14368. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  14369. }
  14370. // Request without Accept-Encoding header: should not have compression
  14371. Headers h_no_compress;
  14372. auto res2 = cli.Get("/compressible", h_no_compress);
  14373. ASSERT_TRUE(res2);
  14374. EXPECT_EQ(200, res2->status);
  14375. // Verify Vary header is present when compression is applied
  14376. // (the exact behavior depends on server configuration)
  14377. svr.stop();
  14378. t.join();
  14379. }
  14380. TEST(ETagTest, IfRangeWithETag) {
  14381. using namespace httplib;
  14382. // Create a test file with known content
  14383. const char *fname = "if_range_testfile.txt";
  14384. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  14385. {
  14386. std::ofstream ofs(fname);
  14387. ofs << content;
  14388. ASSERT_TRUE(ofs.good());
  14389. }
  14390. Server svr;
  14391. svr.set_mount_point("/static", ".");
  14392. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14393. svr.wait_until_ready();
  14394. Client cli(HOST, PORT);
  14395. // First request: get ETag
  14396. auto res1 = cli.Get("/static/if_range_testfile.txt");
  14397. ASSERT_TRUE(res1);
  14398. ASSERT_EQ(200, res1->status);
  14399. ASSERT_TRUE(res1->has_header("ETag"));
  14400. std::string etag = res1->get_header_value("ETag");
  14401. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  14402. // Since our server generates weak ETags (W/"..."), If-Range with our
  14403. // ETag should NOT result in partial content - it should return full content.
  14404. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  14405. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  14406. ASSERT_TRUE(res2);
  14407. // Weak ETag in If-Range -> full content (200), not partial (206)
  14408. EXPECT_EQ(200, res2->status);
  14409. EXPECT_EQ(content, res2->body);
  14410. EXPECT_FALSE(res2->has_header("Content-Range"));
  14411. // Range request with non-matching If-Range (ETag): should get 200 (full
  14412. // content)
  14413. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  14414. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  14415. ASSERT_TRUE(res3);
  14416. EXPECT_EQ(200, res3->status);
  14417. EXPECT_EQ(content, res3->body);
  14418. EXPECT_FALSE(res3->has_header("Content-Range"));
  14419. // Range request with strong ETag (hypothetical - our server doesn't generate
  14420. // strong ETags, but if client sends a strong ETag that doesn't match, it
  14421. // should return full content)
  14422. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  14423. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  14424. ASSERT_TRUE(res4);
  14425. EXPECT_EQ(200, res4->status);
  14426. EXPECT_EQ(content, res4->body);
  14427. EXPECT_FALSE(res4->has_header("Content-Range"));
  14428. svr.stop();
  14429. t.join();
  14430. std::remove(fname);
  14431. }
  14432. TEST(ETagTest, IfRangeWithDate) {
  14433. using namespace httplib;
  14434. // Create a test file
  14435. const char *fname = "if_range_date_testfile.txt";
  14436. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  14437. {
  14438. std::ofstream ofs(fname);
  14439. ofs << content;
  14440. ASSERT_TRUE(ofs.good());
  14441. }
  14442. Server svr;
  14443. svr.set_mount_point("/static", ".");
  14444. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14445. svr.wait_until_ready();
  14446. Client cli(HOST, PORT);
  14447. // First request: get Last-Modified
  14448. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  14449. ASSERT_TRUE(res1);
  14450. ASSERT_EQ(200, res1->status);
  14451. ASSERT_TRUE(res1->has_header("Last-Modified"));
  14452. std::string last_modified = res1->get_header_value("Last-Modified");
  14453. // Range request with matching If-Range (date): should get 206
  14454. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  14455. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  14456. ASSERT_TRUE(res2);
  14457. EXPECT_EQ(206, res2->status);
  14458. EXPECT_EQ("FGHIJ", res2->body);
  14459. // Range request with old If-Range date: should get 200 (full content)
  14460. Headers h3 = {{"Range", "bytes=5-9"},
  14461. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  14462. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  14463. ASSERT_TRUE(res3);
  14464. EXPECT_EQ(200, res3->status);
  14465. EXPECT_EQ(content, res3->body);
  14466. // Range request with future If-Range date: should get 206
  14467. Headers h4 = {{"Range", "bytes=0-4"},
  14468. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  14469. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  14470. ASSERT_TRUE(res4);
  14471. EXPECT_EQ(206, res4->status);
  14472. EXPECT_EQ("ABCDE", res4->body);
  14473. svr.stop();
  14474. t.join();
  14475. std::remove(fname);
  14476. }
  14477. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  14478. using namespace httplib;
  14479. const char *fname = "etag_malformed.txt";
  14480. const char *content = "malformed-etag";
  14481. {
  14482. std::ofstream ofs(fname);
  14483. ofs << content;
  14484. ASSERT_TRUE(ofs.good());
  14485. }
  14486. Server svr;
  14487. svr.set_mount_point("/static", ".");
  14488. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14489. svr.wait_until_ready();
  14490. Client cli(HOST, PORT);
  14491. // baseline: should get 200 and an ETag
  14492. auto res1 = cli.Get("/static/etag_malformed.txt");
  14493. ASSERT_TRUE(res1);
  14494. ASSERT_EQ(200, res1->status);
  14495. ASSERT_TRUE(res1->has_header("ETag"));
  14496. // Malformed ETag value (missing quotes) should be treated as non-matching
  14497. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  14498. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  14499. ASSERT_TRUE(res_bad);
  14500. EXPECT_EQ(200, res_bad->status);
  14501. // Whitespace-only header value should be considered invalid / non-matching
  14502. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  14503. "Host: localhost\r\n"
  14504. "If-None-Match: \r\n"
  14505. "Connection: close\r\n"
  14506. "\r\n";
  14507. std::string out;
  14508. ASSERT_TRUE(send_request(5, raw_req, &out));
  14509. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  14510. svr.stop();
  14511. t.join();
  14512. std::remove(fname);
  14513. }
  14514. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  14515. using namespace httplib;
  14516. const char *fname = "ims_invalid_format.txt";
  14517. const char *content = "ims-bad-format";
  14518. {
  14519. std::ofstream ofs(fname);
  14520. ofs << content;
  14521. ASSERT_TRUE(ofs.good());
  14522. }
  14523. Server svr;
  14524. svr.set_mount_point("/static", ".");
  14525. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14526. svr.wait_until_ready();
  14527. Client cli(HOST, PORT);
  14528. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  14529. ASSERT_TRUE(res1);
  14530. ASSERT_EQ(200, res1->status);
  14531. ASSERT_TRUE(res1->has_header("Last-Modified"));
  14532. // If-Modified-Since with invalid format should not result in 304
  14533. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  14534. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  14535. ASSERT_TRUE(res_bad);
  14536. EXPECT_EQ(200, res_bad->status);
  14537. // If-Range with invalid date format should be treated as mismatch -> full
  14538. // content (200)
  14539. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  14540. {"If-Range", "invalid-date"}};
  14541. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  14542. ASSERT_TRUE(res_ifrange);
  14543. EXPECT_EQ(200, res_ifrange->status);
  14544. svr.stop();
  14545. t.join();
  14546. std::remove(fname);
  14547. }
  14548. TEST(ETagTest, IfRangeWithMalformedETag) {
  14549. using namespace httplib;
  14550. const char *fname = "ifrange_malformed.txt";
  14551. const std::string content = "0123456789";
  14552. {
  14553. std::ofstream ofs(fname);
  14554. ofs << content;
  14555. ASSERT_TRUE(ofs.good());
  14556. }
  14557. Server svr;
  14558. svr.set_mount_point("/static", ".");
  14559. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14560. svr.wait_until_ready();
  14561. Client cli(HOST, PORT);
  14562. // First request: get ETag
  14563. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  14564. ASSERT_TRUE(res1);
  14565. ASSERT_EQ(200, res1->status);
  14566. ASSERT_TRUE(res1->has_header("ETag"));
  14567. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  14568. // full content (200)
  14569. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  14570. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  14571. ASSERT_TRUE(res2);
  14572. EXPECT_EQ(200, res2->status);
  14573. EXPECT_EQ(content, res2->body);
  14574. svr.stop();
  14575. t.join();
  14576. std::remove(fname);
  14577. }
  14578. TEST(ETagTest, ExtremeLargeDateValues) {
  14579. using namespace httplib;
  14580. const char *fname = "ims_extreme_date.txt";
  14581. const char *content = "ims-extreme-date";
  14582. {
  14583. std::ofstream ofs(fname);
  14584. ofs << content;
  14585. ASSERT_TRUE(ofs.good());
  14586. }
  14587. Server svr;
  14588. svr.set_mount_point("/static", ".");
  14589. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14590. svr.wait_until_ready();
  14591. Client cli(HOST, PORT);
  14592. auto res1 = cli.Get(std::string("/static/") + fname);
  14593. ASSERT_TRUE(res1);
  14594. ASSERT_EQ(200, res1->status);
  14595. ASSERT_TRUE(res1->has_header("Last-Modified"));
  14596. // Extremely large year that may overflow date parsing routines.
  14597. Headers h_large_date = {
  14598. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  14599. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  14600. ASSERT_TRUE(res_bad);
  14601. // Expect server to treat this as invalid/mismatch and return full content
  14602. EXPECT_EQ(200, res_bad->status);
  14603. // If-Range with extremely large date should be treated as mismatch -> full
  14604. // content (200)
  14605. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  14606. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  14607. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  14608. ASSERT_TRUE(res_ifrange);
  14609. EXPECT_EQ(200, res_ifrange->status);
  14610. svr.stop();
  14611. t.join();
  14612. std::remove(fname);
  14613. }
  14614. TEST(ETagTest, NegativeFileModificationTime) {
  14615. using namespace httplib;
  14616. const char *fname = "ims_negative_mtime.txt";
  14617. const std::string content = "negative-mtime";
  14618. {
  14619. std::ofstream ofs(fname);
  14620. ofs << content;
  14621. ASSERT_TRUE(ofs.good());
  14622. }
  14623. // Try to set file mtime to a negative value. This may fail on some
  14624. // platforms/filesystems; if it fails, the test will still verify server
  14625. // behaves safely by performing a regular conditional request.
  14626. #if defined(__APPLE__) || defined(__linux__)
  14627. bool set_negative = false;
  14628. do {
  14629. struct timeval times[2];
  14630. // access time: now
  14631. times[0].tv_sec = time(nullptr);
  14632. times[0].tv_usec = 0;
  14633. // modification time: negative (e.g., -1)
  14634. times[1].tv_sec = -1;
  14635. times[1].tv_usec = 0;
  14636. if (utimes(fname, times) == 0) { set_negative = true; }
  14637. } while (0);
  14638. #else
  14639. bool set_negative = false;
  14640. #endif
  14641. Server svr;
  14642. svr.set_mount_point("/static", ".");
  14643. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14644. svr.wait_until_ready();
  14645. Client cli(HOST, PORT);
  14646. auto res1 = cli.Get(std::string("/static/") + fname);
  14647. ASSERT_TRUE(res1);
  14648. ASSERT_EQ(200, res1->status);
  14649. bool has_last_modified = res1->has_header("Last-Modified");
  14650. std::string last_modified;
  14651. if (has_last_modified) {
  14652. last_modified = res1->get_header_value("Last-Modified");
  14653. }
  14654. if (set_negative) {
  14655. // If we successfully set a negative mtime, ensure server returns a
  14656. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  14657. // with an old date and ensure server handles it without crash.
  14658. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  14659. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  14660. ASSERT_TRUE(res2);
  14661. // Behavior may vary; at minimum ensure server responds (200 or 304).
  14662. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  14663. } else {
  14664. // Could not set negative mtime on this platform; fall back to verifying
  14665. // that normal invalid/malformed dates are treated safely (non-304).
  14666. Headers h_bad_date = {
  14667. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  14668. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  14669. ASSERT_TRUE(res_bad);
  14670. EXPECT_EQ(200, res_bad->status);
  14671. }
  14672. svr.stop();
  14673. t.join();
  14674. std::remove(fname);
  14675. }
  14676. //==============================================================================
  14677. // SSE Parsing Tests
  14678. //==============================================================================
  14679. class SSEParsingTest : public ::testing::Test {
  14680. protected:
  14681. // Test helper that mimics SSE parsing behavior
  14682. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  14683. int &retry_ms) {
  14684. // Blank line signals end of event
  14685. if (line.empty() || line == "\r") { return true; }
  14686. // Lines starting with ':' are comments (ignored)
  14687. if (!line.empty() && line[0] == ':') { return false; }
  14688. // Find the colon separator
  14689. auto colon_pos = line.find(':');
  14690. if (colon_pos == std::string::npos) {
  14691. // Line with no colon is treated as field name with empty value
  14692. return false;
  14693. }
  14694. std::string field = line.substr(0, colon_pos);
  14695. std::string value;
  14696. // Value starts after colon, skip optional single space
  14697. if (colon_pos + 1 < line.size()) {
  14698. size_t value_start = colon_pos + 1;
  14699. if (line[value_start] == ' ') { value_start++; }
  14700. value = line.substr(value_start);
  14701. // Remove trailing \r if present
  14702. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  14703. }
  14704. // Handle known fields
  14705. if (field == "event") {
  14706. msg.event = value;
  14707. } else if (field == "data") {
  14708. // Multiple data lines are concatenated with newlines
  14709. if (!msg.data.empty()) { msg.data += "\n"; }
  14710. msg.data += value;
  14711. } else if (field == "id") {
  14712. // Empty id is valid (clears the last event ID)
  14713. msg.id = value;
  14714. } else if (field == "retry") {
  14715. // Parse retry interval in milliseconds
  14716. {
  14717. int v = 0;
  14718. auto res =
  14719. detail::from_chars(value.data(), value.data() + value.size(), v);
  14720. if (res.ec == std::errc{}) { retry_ms = v; }
  14721. }
  14722. }
  14723. // Unknown fields are ignored per SSE spec
  14724. return false;
  14725. }
  14726. };
  14727. // Test: Single-line data
  14728. TEST_F(SSEParsingTest, SingleLineData) {
  14729. sse::SSEMessage msg;
  14730. int retry_ms = 3000;
  14731. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  14732. EXPECT_EQ(msg.data, "hello");
  14733. EXPECT_EQ(msg.event, "message");
  14734. // Blank line ends event
  14735. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  14736. }
  14737. // Test: Multi-line data
  14738. TEST_F(SSEParsingTest, MultiLineData) {
  14739. sse::SSEMessage msg;
  14740. int retry_ms = 3000;
  14741. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  14742. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  14743. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  14744. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  14745. }
  14746. // Test: Custom event types
  14747. TEST_F(SSEParsingTest, CustomEventType) {
  14748. sse::SSEMessage msg;
  14749. int retry_ms = 3000;
  14750. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  14751. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  14752. EXPECT_EQ(msg.event, "update");
  14753. EXPECT_EQ(msg.data, "payload");
  14754. }
  14755. // Test: Event ID handling
  14756. TEST_F(SSEParsingTest, EventIdHandling) {
  14757. sse::SSEMessage msg;
  14758. int retry_ms = 3000;
  14759. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  14760. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  14761. EXPECT_EQ(msg.id, "12345");
  14762. }
  14763. // Test: Empty event ID (clears last event ID)
  14764. TEST_F(SSEParsingTest, EmptyEventId) {
  14765. sse::SSEMessage msg;
  14766. msg.id = "previous";
  14767. int retry_ms = 3000;
  14768. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  14769. EXPECT_EQ(msg.id, "");
  14770. }
  14771. // Test: Retry field parsing
  14772. TEST_F(SSEParsingTest, RetryFieldParsing) {
  14773. sse::SSEMessage msg;
  14774. int retry_ms = 3000;
  14775. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  14776. EXPECT_EQ(retry_ms, 5000);
  14777. }
  14778. // Test: Invalid retry value
  14779. TEST_F(SSEParsingTest, InvalidRetryValue) {
  14780. sse::SSEMessage msg;
  14781. int retry_ms = 3000;
  14782. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  14783. EXPECT_EQ(retry_ms, 3000); // Unchanged
  14784. }
  14785. // Test: Comments (lines starting with :)
  14786. TEST_F(SSEParsingTest, CommentsIgnored) {
  14787. sse::SSEMessage msg;
  14788. int retry_ms = 3000;
  14789. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  14790. EXPECT_EQ(msg.data, "");
  14791. EXPECT_EQ(msg.event, "message");
  14792. }
  14793. // Test: Colon in value
  14794. TEST_F(SSEParsingTest, ColonInValue) {
  14795. sse::SSEMessage msg;
  14796. int retry_ms = 3000;
  14797. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  14798. EXPECT_EQ(msg.data, "hello:world:test");
  14799. }
  14800. // Test: Line with no colon (field name only)
  14801. TEST_F(SSEParsingTest, FieldNameOnly) {
  14802. sse::SSEMessage msg;
  14803. int retry_ms = 3000;
  14804. // According to SSE spec, this is treated as field name with empty value
  14805. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  14806. // Since we don't recognize "data" without colon, data should be empty
  14807. EXPECT_EQ(msg.data, "");
  14808. }
  14809. // Test: Trailing \r handling
  14810. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  14811. sse::SSEMessage msg;
  14812. int retry_ms = 3000;
  14813. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  14814. EXPECT_EQ(msg.data, "hello");
  14815. }
  14816. // Test: Unknown fields ignored
  14817. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  14818. sse::SSEMessage msg;
  14819. int retry_ms = 3000;
  14820. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  14821. EXPECT_EQ(msg.data, "");
  14822. EXPECT_EQ(msg.event, "message");
  14823. }
  14824. // Test: Space after colon is optional
  14825. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  14826. sse::SSEMessage msg1, msg2;
  14827. int retry_ms = 3000;
  14828. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  14829. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  14830. EXPECT_EQ(msg1.data, "hello");
  14831. EXPECT_EQ(msg2.data, "hello");
  14832. }
  14833. // Test: SSEMessage clear
  14834. TEST_F(SSEParsingTest, MessageClear) {
  14835. sse::SSEMessage msg;
  14836. msg.event = "custom";
  14837. msg.data = "some data";
  14838. msg.id = "123";
  14839. msg.clear();
  14840. EXPECT_EQ(msg.event, "message");
  14841. EXPECT_EQ(msg.data, "");
  14842. EXPECT_EQ(msg.id, "");
  14843. }
  14844. // Test: Complete event parsing
  14845. TEST_F(SSEParsingTest, CompleteEventParsing) {
  14846. sse::SSEMessage msg;
  14847. int retry_ms = 3000;
  14848. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  14849. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  14850. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  14851. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  14852. // Blank line ends event
  14853. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  14854. EXPECT_EQ(msg.event, "notification");
  14855. EXPECT_EQ(msg.id, "evt-42");
  14856. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  14857. EXPECT_EQ(retry_ms, 1000);
  14858. }
  14859. //==============================================================================
  14860. // Integration Tests with Server
  14861. //==============================================================================
  14862. class SSEIntegrationTest : public ::testing::Test {
  14863. protected:
  14864. void SetUp() override {
  14865. stop_server_.store(false);
  14866. events_.clear();
  14867. server_ = httplib::detail::make_unique<Server>();
  14868. setup_server();
  14869. start_server();
  14870. }
  14871. void TearDown() override {
  14872. stop_server_.store(true);
  14873. event_cv_.notify_all();
  14874. server_->stop();
  14875. if (server_thread_.joinable()) { server_thread_.join(); }
  14876. }
  14877. void setup_server() {
  14878. // Simple SSE endpoint
  14879. server_->Get("/events", [this](const Request &req, Response &res) {
  14880. auto last_id = req.get_header_value("Last-Event-ID");
  14881. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  14882. res.set_chunked_content_provider(
  14883. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  14884. std::unique_lock<std::mutex> lock(event_mutex_);
  14885. if (event_cv_.wait_for(
  14886. lock, std::chrono::milliseconds(200), [this] {
  14887. return !events_.empty() || stop_server_.load();
  14888. })) {
  14889. if (stop_server_.load()) { return false; }
  14890. if (!events_.empty()) {
  14891. std::string event = events_.front();
  14892. events_.erase(events_.begin());
  14893. sink.write(event.data(), event.size());
  14894. return true;
  14895. }
  14896. }
  14897. return !stop_server_.load();
  14898. });
  14899. });
  14900. // Endpoint that returns error
  14901. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  14902. res.status = 500;
  14903. res.set_content("Internal Server Error", "text/plain");
  14904. });
  14905. // Endpoint for custom event types
  14906. server_->Get("/custom-events", [](const Request &, Response &res) {
  14907. res.set_chunked_content_provider(
  14908. "text/event-stream", [](size_t offset, DataSink &sink) {
  14909. if (offset == 0) {
  14910. std::string event = "event: update\ndata: updated\n\n"
  14911. "event: delete\ndata: deleted\n\n";
  14912. sink.write(event.data(), event.size());
  14913. }
  14914. return false; // End stream after sending
  14915. });
  14916. });
  14917. }
  14918. void start_server() {
  14919. port_ = server_->bind_to_any_port(HOST);
  14920. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  14921. // Wait for server to start
  14922. while (!server_->is_running()) {
  14923. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  14924. }
  14925. }
  14926. int get_port() const { return port_; }
  14927. void send_event(const std::string &event) {
  14928. std::lock_guard<std::mutex> lock(event_mutex_);
  14929. events_.push_back(event);
  14930. event_cv_.notify_all();
  14931. }
  14932. std::unique_ptr<Server> server_;
  14933. std::thread server_thread_;
  14934. std::mutex event_mutex_;
  14935. std::condition_variable event_cv_;
  14936. std::vector<std::string> events_;
  14937. std::atomic<bool> stop_server_{false};
  14938. std::string last_received_event_id_;
  14939. int port_ = 0;
  14940. };
  14941. // Test: Successful connection and on_open callback
  14942. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  14943. // Add a simple endpoint that sends one event and closes
  14944. server_->Get("/simple-event", [](const Request &, Response &res) {
  14945. res.set_chunked_content_provider(
  14946. "text/event-stream", [](size_t offset, DataSink &sink) {
  14947. if (offset == 0) {
  14948. std::string event = "data: hello\n\n";
  14949. sink.write(event.data(), event.size());
  14950. }
  14951. return false; // Close stream after sending
  14952. });
  14953. });
  14954. Client client("localhost", get_port());
  14955. sse::SSEClient sse(client, "/simple-event");
  14956. std::atomic<bool> open_called{false};
  14957. std::atomic<bool> message_received{false};
  14958. sse.on_open([&open_called]() { open_called.store(true); });
  14959. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  14960. if (msg.data == "hello") { message_received.store(true); }
  14961. });
  14962. sse.set_reconnect_interval(100);
  14963. sse.set_max_reconnect_attempts(1);
  14964. // Start async
  14965. sse.start_async();
  14966. // Wait for message to be processed
  14967. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  14968. sse.stop();
  14969. EXPECT_TRUE(open_called.load());
  14970. EXPECT_TRUE(message_received.load());
  14971. }
  14972. // Test: on_message callback
  14973. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  14974. // Endpoint that sends multiple events then closes
  14975. server_->Get("/multi-event", [](const Request &, Response &res) {
  14976. res.set_chunked_content_provider(
  14977. "text/event-stream", [](size_t offset, DataSink &sink) {
  14978. if (offset == 0) {
  14979. std::string events = "data: message1\n\ndata: message2\n\n";
  14980. sink.write(events.data(), events.size());
  14981. }
  14982. return false;
  14983. });
  14984. });
  14985. Client client("localhost", get_port());
  14986. sse::SSEClient sse(client, "/multi-event");
  14987. std::vector<std::string> received_messages;
  14988. std::mutex messages_mutex;
  14989. sse.on_message([&](const sse::SSEMessage &msg) {
  14990. std::lock_guard<std::mutex> lock(messages_mutex);
  14991. received_messages.push_back(msg.data);
  14992. });
  14993. sse.set_reconnect_interval(100);
  14994. sse.set_max_reconnect_attempts(1);
  14995. sse.start_async();
  14996. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  14997. sse.stop();
  14998. std::lock_guard<std::mutex> lock(messages_mutex);
  14999. EXPECT_GE(received_messages.size(), 2u);
  15000. if (received_messages.size() >= 2) {
  15001. EXPECT_EQ(received_messages[0], "message1");
  15002. EXPECT_EQ(received_messages[1], "message2");
  15003. }
  15004. }
  15005. // Test: on_event for specific types
  15006. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  15007. Client client("localhost", get_port());
  15008. sse::SSEClient sse(client, "/custom-events");
  15009. std::atomic<bool> update_received{false};
  15010. std::atomic<bool> delete_received{false};
  15011. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  15012. if (msg.data == "updated") { update_received.store(true); }
  15013. });
  15014. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  15015. if (msg.data == "deleted") { delete_received.store(true); }
  15016. });
  15017. sse.set_max_reconnect_attempts(1);
  15018. sse.start_async();
  15019. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  15020. sse.stop();
  15021. EXPECT_TRUE(update_received.load());
  15022. EXPECT_TRUE(delete_received.load());
  15023. }
  15024. // Test: on_error callback on connection failure
  15025. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  15026. // Connect to a non-existent port
  15027. Client client("localhost", 59999);
  15028. sse::SSEClient sse(client, "/events");
  15029. std::atomic<bool> error_called{false};
  15030. Error received_error = Error::Success;
  15031. sse.on_error([&](Error err) {
  15032. error_called.store(true);
  15033. received_error = err;
  15034. });
  15035. sse.set_reconnect_interval(50);
  15036. sse.set_max_reconnect_attempts(1);
  15037. sse.start_async();
  15038. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  15039. sse.stop();
  15040. EXPECT_TRUE(error_called.load());
  15041. EXPECT_NE(received_error, Error::Success);
  15042. }
  15043. // Test: Last-Event-ID header sent on reconnect
  15044. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  15045. // Endpoint that sends event with ID
  15046. server_->Get("/event-with-id", [](const Request &, Response &res) {
  15047. res.set_chunked_content_provider(
  15048. "text/event-stream", [](size_t offset, DataSink &sink) {
  15049. if (offset == 0) {
  15050. std::string event = "id: evt-123\ndata: test\n\n";
  15051. sink.write(event.data(), event.size());
  15052. }
  15053. return false;
  15054. });
  15055. });
  15056. Client client("localhost", get_port());
  15057. sse::SSEClient sse(client, "/event-with-id");
  15058. std::atomic<bool> id_received{false};
  15059. sse.on_message([&](const sse::SSEMessage &msg) {
  15060. if (!msg.id.empty()) { id_received.store(true); }
  15061. });
  15062. sse.set_reconnect_interval(100);
  15063. sse.set_max_reconnect_attempts(1);
  15064. sse.start_async();
  15065. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  15066. sse.stop();
  15067. EXPECT_TRUE(id_received.load());
  15068. EXPECT_EQ(sse.last_event_id(), "evt-123");
  15069. }
  15070. // Test: Manual stop
  15071. TEST_F(SSEIntegrationTest, ManualStop) {
  15072. // Endpoint that sends one event and stays open briefly
  15073. std::atomic<bool> handler_running{true};
  15074. server_->Get("/stay-open", [&handler_running](const Request &,
  15075. Response &res) {
  15076. res.set_chunked_content_provider(
  15077. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  15078. if (offset == 0) {
  15079. std::string event = "data: connected\n\n";
  15080. sink.write(event.data(), event.size());
  15081. }
  15082. // Keep connection open while handler_running is true
  15083. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  15084. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  15085. }
  15086. return false;
  15087. });
  15088. });
  15089. Client client("localhost", get_port());
  15090. sse::SSEClient sse(client, "/stay-open");
  15091. std::atomic<bool> connected{false};
  15092. sse.on_open([&connected]() { connected.store(true); });
  15093. sse.set_reconnect_interval(100);
  15094. sse.set_max_reconnect_attempts(1);
  15095. sse.start_async();
  15096. // Wait for connection to establish
  15097. for (int i = 0; i < 20 && !connected.load(); ++i) {
  15098. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  15099. }
  15100. EXPECT_TRUE(connected.load());
  15101. EXPECT_TRUE(sse.is_connected());
  15102. // Signal handler to stop
  15103. handler_running.store(false);
  15104. // Stop SSE client
  15105. sse.stop();
  15106. EXPECT_FALSE(sse.is_connected());
  15107. }
  15108. // Test: SSEClient with custom headers
  15109. TEST_F(SSEIntegrationTest, CustomHeaders) {
  15110. // Setup a server endpoint that checks for custom header
  15111. std::atomic<bool> header_received{false};
  15112. server_->Get("/header-check", [&](const Request &req, Response &res) {
  15113. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  15114. header_received.store(true);
  15115. }
  15116. res.set_chunked_content_provider("text/event-stream",
  15117. [](size_t, DataSink &) { return false; });
  15118. });
  15119. Client client("localhost", get_port());
  15120. Headers headers = {{"X-Custom-Header", "custom-value"}};
  15121. sse::SSEClient sse(client, "/header-check", headers);
  15122. sse.set_max_reconnect_attempts(1);
  15123. sse.start_async();
  15124. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  15125. sse.stop();
  15126. EXPECT_TRUE(header_received.load());
  15127. }
  15128. // Test: Reconnect interval configuration
  15129. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  15130. Client client("localhost", get_port());
  15131. sse::SSEClient sse(client, "/events");
  15132. auto &result = sse.set_reconnect_interval(500);
  15133. // Builder pattern should return reference to self
  15134. EXPECT_EQ(&result, &sse);
  15135. }
  15136. // Test: Max reconnect attempts
  15137. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  15138. // Connect to non-existent port to force reconnects
  15139. Client client("localhost", 59998);
  15140. sse::SSEClient sse(client, "/events");
  15141. std::atomic<int> error_count{0};
  15142. sse.on_error([&](Error) { error_count.fetch_add(1); });
  15143. sse.set_reconnect_interval(50);
  15144. sse.set_max_reconnect_attempts(2);
  15145. auto start = std::chrono::steady_clock::now();
  15146. sse.start(); // Blocking call
  15147. auto end = std::chrono::steady_clock::now();
  15148. // Should have stopped after 2 failed attempts
  15149. EXPECT_GE(error_count.load(), 2);
  15150. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  15151. auto duration =
  15152. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  15153. #ifdef _WIN32
  15154. // Windows is much slower for socket connection failures
  15155. EXPECT_LT(duration.count(), 7000);
  15156. #else
  15157. EXPECT_LT(duration.count(), 1000);
  15158. #endif
  15159. }
  15160. // Test: Multi-line data in integration
  15161. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  15162. // Endpoint with multi-line data
  15163. server_->Get("/multiline-data", [](const Request &, Response &res) {
  15164. res.set_chunked_content_provider(
  15165. "text/event-stream", [](size_t offset, DataSink &sink) {
  15166. if (offset == 0) {
  15167. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  15168. sink.write(event.data(), event.size());
  15169. }
  15170. return false;
  15171. });
  15172. });
  15173. Client client("localhost", get_port());
  15174. sse::SSEClient sse(client, "/multiline-data");
  15175. std::string received_data;
  15176. std::mutex data_mutex;
  15177. sse.on_message([&](const sse::SSEMessage &msg) {
  15178. std::lock_guard<std::mutex> lock(data_mutex);
  15179. received_data = msg.data;
  15180. });
  15181. sse.set_reconnect_interval(100);
  15182. sse.set_max_reconnect_attempts(1);
  15183. sse.start_async();
  15184. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  15185. sse.stop();
  15186. std::lock_guard<std::mutex> lock(data_mutex);
  15187. EXPECT_EQ(received_data, "line1\nline2\nline3");
  15188. }
  15189. // Test: Auto-reconnect after server disconnection
  15190. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  15191. std::atomic<int> connection_count{0};
  15192. std::atomic<int> message_count{0};
  15193. // Endpoint that sends one event and closes, forcing reconnect
  15194. server_->Get("/reconnect-test",
  15195. [&connection_count](const Request &, Response &res) {
  15196. connection_count.fetch_add(1);
  15197. res.set_chunked_content_provider(
  15198. "text/event-stream", [](size_t offset, DataSink &sink) {
  15199. if (offset == 0) {
  15200. std::string event = "data: hello\n\n";
  15201. sink.write(event.data(), event.size());
  15202. }
  15203. return false; // Close connection after sending
  15204. });
  15205. });
  15206. Client client("localhost", get_port());
  15207. sse::SSEClient sse(client, "/reconnect-test");
  15208. sse.on_message([&message_count](const sse::SSEMessage &) {
  15209. message_count.fetch_add(1);
  15210. });
  15211. sse.set_reconnect_interval(100);
  15212. sse.set_max_reconnect_attempts(3);
  15213. sse.start_async();
  15214. // Wait long enough for multiple reconnects
  15215. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  15216. sse.stop();
  15217. // Should have connected multiple times (initial + reconnects)
  15218. EXPECT_GE(connection_count.load(), 2);
  15219. // Should have received messages from multiple connections
  15220. EXPECT_GE(message_count.load(), 2);
  15221. }
  15222. // Test: Last-Event-ID sent on reconnect
  15223. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  15224. std::atomic<int> connection_count{0};
  15225. std::vector<std::string> received_last_event_ids;
  15226. std::mutex id_mutex;
  15227. // Endpoint that checks Last-Event-ID header and sends event with ID
  15228. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  15229. int conn = connection_count.fetch_add(1);
  15230. // Capture the Last-Event-ID header from each connection
  15231. {
  15232. std::lock_guard<std::mutex> lock(id_mutex);
  15233. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  15234. }
  15235. res.set_chunked_content_provider(
  15236. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  15237. if (offset == 0) {
  15238. std::string event =
  15239. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  15240. sink.write(event.data(), event.size());
  15241. }
  15242. return false;
  15243. });
  15244. });
  15245. Client client("localhost", get_port());
  15246. sse::SSEClient sse(client, "/reconnect-with-id");
  15247. sse.set_reconnect_interval(100);
  15248. sse.set_max_reconnect_attempts(3);
  15249. sse.start_async();
  15250. // Wait for at least 2 connections
  15251. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  15252. sse.stop();
  15253. // Verify behavior
  15254. std::lock_guard<std::mutex> lock(id_mutex);
  15255. EXPECT_GE(received_last_event_ids.size(), 2u);
  15256. // First connection should have no Last-Event-ID
  15257. if (!received_last_event_ids.empty()) {
  15258. EXPECT_EQ(received_last_event_ids[0], "");
  15259. }
  15260. // Second connection should have Last-Event-ID from first connection
  15261. if (received_last_event_ids.size() >= 2) {
  15262. EXPECT_EQ(received_last_event_ids[1], "event-0");
  15263. }
  15264. }
  15265. // Test: set_headers updates headers used on reconnect
  15266. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  15267. std::vector<std::string> received_tokens;
  15268. std::mutex token_mutex;
  15269. // Endpoint that captures Authorization header
  15270. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  15271. {
  15272. std::lock_guard<std::mutex> lock(token_mutex);
  15273. received_tokens.push_back(req.get_header_value("Authorization"));
  15274. }
  15275. res.set_chunked_content_provider(
  15276. "text/event-stream", [](size_t offset, DataSink &sink) {
  15277. if (offset == 0) {
  15278. std::string event = "data: hello\n\n";
  15279. sink.write(event.data(), event.size());
  15280. }
  15281. return false; // Close connection to trigger reconnect
  15282. });
  15283. });
  15284. Client client("localhost", get_port());
  15285. Headers headers = {{"Authorization", "Bearer old-token"}};
  15286. sse::SSEClient sse(client, "/auth-check", headers);
  15287. // Update headers on each successful connection
  15288. sse.on_open(
  15289. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  15290. sse.set_reconnect_interval(100);
  15291. sse.set_max_reconnect_attempts(3);
  15292. sse.start_async();
  15293. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  15294. sse.stop();
  15295. std::lock_guard<std::mutex> lock(token_mutex);
  15296. ASSERT_GE(received_tokens.size(), 2u);
  15297. // First connection uses original header
  15298. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  15299. // Second connection uses updated header from set_headers
  15300. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  15301. }
  15302. // Test: 401 allows reconnection (so on_error can refresh headers)
  15303. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  15304. std::atomic<int> connection_count{0};
  15305. // Endpoint: returns 401 on first attempt, 200 on second
  15306. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  15307. int conn = connection_count.fetch_add(1);
  15308. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  15309. res.status = StatusCode::Unauthorized_401;
  15310. res.set_content("Unauthorized", "text/plain");
  15311. return;
  15312. }
  15313. res.set_chunked_content_provider(
  15314. "text/event-stream", [](size_t offset, DataSink &sink) {
  15315. if (offset == 0) {
  15316. std::string event = "data: authenticated\n\n";
  15317. sink.write(event.data(), event.size());
  15318. }
  15319. return false;
  15320. });
  15321. });
  15322. Client client("localhost", get_port());
  15323. Headers headers = {{"Authorization", "Bearer expired"}};
  15324. sse::SSEClient sse(client, "/auth-retry", headers);
  15325. std::atomic<bool> message_received{false};
  15326. // Refresh token on error
  15327. sse.on_error(
  15328. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  15329. sse.on_message([&](const sse::SSEMessage &msg) {
  15330. if (msg.data == "authenticated") { message_received.store(true); }
  15331. });
  15332. sse.set_reconnect_interval(100);
  15333. sse.set_max_reconnect_attempts(3);
  15334. sse.start_async();
  15335. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  15336. sse.stop();
  15337. // Should have reconnected after 401 and succeeded with new token
  15338. EXPECT_GE(connection_count.load(), 2);
  15339. EXPECT_TRUE(message_received.load());
  15340. }
  15341. TEST(Issue2318Test, EmptyHostString) {
  15342. {
  15343. httplib::Client cli_empty("", PORT);
  15344. auto res = cli_empty.Get("/");
  15345. ASSERT_FALSE(res);
  15346. EXPECT_EQ(httplib::Error::Connection, res.error());
  15347. }
  15348. {
  15349. httplib::Client cli(" ", PORT);
  15350. auto res = cli.Get("/");
  15351. ASSERT_FALSE(res);
  15352. EXPECT_EQ(httplib::Error::Connection, res.error());
  15353. }
  15354. }
  15355. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  15356. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  15357. Server svr;
  15358. // Set a small payload limit (1KB)
  15359. svr.set_payload_max_length(1024);
  15360. svr.Post("/test", [&](const Request &req, Response &res) {
  15361. res.set_content("Body size: " + std::to_string(req.body.size()),
  15362. "text/plain");
  15363. });
  15364. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15365. auto se = detail::scope_exit([&] {
  15366. svr.stop();
  15367. listen_thread.join();
  15368. });
  15369. svr.wait_until_ready();
  15370. // Create data that compresses well but exceeds limit when decompressed
  15371. // 8KB of repeated null bytes compresses to a very small size
  15372. std::string original_data(8 * 1024, '\0');
  15373. // Compress the data using gzip
  15374. std::string compressed_data;
  15375. detail::gzip_compressor compressor;
  15376. compressor.compress(original_data.data(), original_data.size(), true,
  15377. [&](const char *data, size_t size) {
  15378. compressed_data.append(data, size);
  15379. return true;
  15380. });
  15381. // Verify compression worked (compressed should be much smaller)
  15382. ASSERT_LT(compressed_data.size(), original_data.size());
  15383. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  15384. // Send compressed data with Content-Encoding: gzip
  15385. Client cli(HOST, PORT);
  15386. Headers headers = {{"Content-Encoding", "gzip"}};
  15387. auto res =
  15388. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  15389. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  15390. ASSERT_TRUE(res);
  15391. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  15392. }
  15393. #endif
  15394. // ============================================================================
  15395. // OpenSSL-Specific Tests
  15396. // ============================================================================
  15397. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  15398. X509 *readCertificate(const std::string &strFileName) {
  15399. std::ifstream inStream(strFileName);
  15400. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  15401. std::istreambuf_iterator<char>());
  15402. if (strCertPEM.empty()) return (nullptr);
  15403. BIO *pbCert = BIO_new(BIO_s_mem());
  15404. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  15405. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  15406. BIO_free(pbCert);
  15407. return (pCert);
  15408. }
  15409. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  15410. std::ifstream inStream(strFileName);
  15411. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  15412. std::istreambuf_iterator<char>());
  15413. if (strPrivateKeyPEM.empty()) return (nullptr);
  15414. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  15415. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  15416. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  15417. BIO_free(pbPrivKey);
  15418. return (pPrivateKey);
  15419. }
  15420. TEST(BindServerTest, UpdateCerts) {
  15421. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  15422. int port = svr.bind_to_any_port("0.0.0.0");
  15423. ASSERT_TRUE(svr.is_valid());
  15424. ASSERT_TRUE(port > 0);
  15425. X509 *cert = readCertificate(SERVER_CERT_FILE);
  15426. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  15427. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  15428. ASSERT_TRUE(cert != nullptr);
  15429. ASSERT_TRUE(ca_cert != nullptr);
  15430. ASSERT_TRUE(key != nullptr);
  15431. X509_STORE *cert_store = X509_STORE_new();
  15432. X509_STORE_add_cert(cert_store, ca_cert);
  15433. // svr.update_certs(cert, key, cert_store); // deprecated
  15434. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  15435. CLIENT_CA_CERT_FILE);
  15436. ASSERT_TRUE(svr.is_valid());
  15437. svr.stop();
  15438. X509_STORE_free(cert_store);
  15439. X509_free(cert);
  15440. X509_free(ca_cert);
  15441. EVP_PKEY_free(key);
  15442. }
  15443. // Test that update_certs() updates client CA list correctly
  15444. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  15445. // Start with file-based constructor
  15446. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15447. ASSERT_TRUE(svr.is_valid());
  15448. // Initially no client CA list should be set
  15449. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  15450. ASSERT_TRUE(ssl_ctx != nullptr);
  15451. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  15452. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  15453. EXPECT_EQ(0, count_before);
  15454. // Now update with client CA (PEM string)
  15455. std::string cert_pem, key_pem, ca_pem;
  15456. read_file(SERVER_CERT_FILE, cert_pem);
  15457. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  15458. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  15459. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  15460. ASSERT_TRUE(svr.is_valid());
  15461. // Now client CA list should be set
  15462. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  15463. ASSERT_TRUE(ca_list_after != nullptr);
  15464. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  15465. }
  15466. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  15467. // Test that the file-path SSLServer constructor properly sets the client CA
  15468. // list that is sent to clients during the TLS handshake (CertificateRequest)
  15469. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  15470. ASSERT_TRUE(svr.is_valid());
  15471. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  15472. ASSERT_TRUE(ssl_ctx != nullptr);
  15473. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  15474. ASSERT_TRUE(ca_list != nullptr);
  15475. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  15476. }
  15477. #endif
  15478. // ============================================================================
  15479. // MbedTLS-Specific Tests
  15480. // ============================================================================
  15481. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  15482. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  15483. using namespace httplib::tls;
  15484. // Track if callback was invoked
  15485. bool callback_invoked = false;
  15486. // The callback receives void* ctx which is actually MbedTlsContext*
  15487. // We can access the mbedtls_ssl_config via the context
  15488. auto setup_callback = [&callback_invoked](void *ctx) {
  15489. callback_invoked = true;
  15490. // Cast to MbedTlsContext* to access the ssl config
  15491. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  15492. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  15493. // Use static variables to hold certificate data (simplified for test)
  15494. static mbedtls_x509_crt own_cert;
  15495. static mbedtls_pk_context own_key;
  15496. static mbedtls_x509_crt ca_chain;
  15497. static bool initialized = false;
  15498. if (!initialized) {
  15499. mbedtls_x509_crt_init(&own_cert);
  15500. mbedtls_pk_init(&own_key);
  15501. mbedtls_x509_crt_init(&ca_chain);
  15502. // Load server certificate
  15503. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  15504. return false;
  15505. }
  15506. // Load server private key.
  15507. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  15508. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  15509. #if MBEDTLS_VERSION_MAJOR == 3
  15510. ,
  15511. mbedtls_ctr_drbg_random, nullptr
  15512. #endif
  15513. ) != 0) {
  15514. return false;
  15515. }
  15516. // Load CA chain for client verification
  15517. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  15518. return false;
  15519. }
  15520. initialized = true;
  15521. }
  15522. // Configure the SSL config
  15523. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  15524. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  15525. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  15526. // Set minimum TLS version using mbedTLS native API
  15527. #if MBEDTLS_VERSION_MAJOR >= 3
  15528. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  15529. #else
  15530. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  15531. MBEDTLS_SSL_MINOR_VERSION_3);
  15532. #endif
  15533. return true;
  15534. };
  15535. SSLServer svr(setup_callback);
  15536. ASSERT_TRUE(svr.is_valid());
  15537. ASSERT_TRUE(callback_invoked);
  15538. svr.Get("/test", [&](const Request &req, Response &res) {
  15539. res.set_content("test", "text/plain");
  15540. auto cert = req.peer_cert();
  15541. ASSERT_TRUE(static_cast<bool>(cert));
  15542. auto common_name = cert.subject_cn();
  15543. EXPECT_EQ("Common Name", common_name);
  15544. });
  15545. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15546. auto se = detail::scope_exit([&] {
  15547. svr.stop();
  15548. t.join();
  15549. ASSERT_FALSE(svr.is_running());
  15550. });
  15551. svr.wait_until_ready();
  15552. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15553. cli.enable_server_certificate_verification(false);
  15554. cli.set_connection_timeout(30);
  15555. auto res = cli.Get("/test");
  15556. ASSERT_TRUE(res);
  15557. ASSERT_EQ(StatusCode::OK_200, res->status);
  15558. }
  15559. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  15560. // context (owning mbedtls_ssl_config) before shutting down a still-open
  15561. // keep-alive SSL session, which reads through that config in
  15562. // mbedtls_ssl_close_notify.
  15563. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  15564. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15565. ASSERT_TRUE(svr.is_valid());
  15566. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  15567. res.set_content("test", "text/plain");
  15568. });
  15569. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15570. auto se = detail::scope_exit([&] {
  15571. svr.stop();
  15572. t.join();
  15573. ASSERT_FALSE(svr.is_running());
  15574. });
  15575. svr.wait_until_ready();
  15576. {
  15577. SSLClient cli(HOST, PORT);
  15578. cli.enable_server_certificate_verification(false);
  15579. cli.set_keep_alive(true);
  15580. auto res = cli.Get("/test");
  15581. ASSERT_TRUE(res);
  15582. ASSERT_EQ(StatusCode::OK_200, res->status);
  15583. // cli is destructed here with the keep-alive SSL session still open.
  15584. }
  15585. }
  15586. #endif
  15587. // WebSocket Tests
  15588. TEST(WebSocketTest, RSVBitsMustBeZero) {
  15589. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  15590. // defining the meaning of these bits has been negotiated.
  15591. auto make_frame = [](uint8_t first_byte) {
  15592. std::string frame;
  15593. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  15594. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  15595. frame += "Hello";
  15596. return frame;
  15597. };
  15598. // RSV1 set (0x40)
  15599. {
  15600. detail::BufferStream strm;
  15601. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  15602. ws::Opcode opcode;
  15603. std::string payload;
  15604. bool fin;
  15605. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15606. false, 1024));
  15607. }
  15608. // RSV2 set (0x20)
  15609. {
  15610. detail::BufferStream strm;
  15611. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  15612. ws::Opcode opcode;
  15613. std::string payload;
  15614. bool fin;
  15615. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15616. false, 1024));
  15617. }
  15618. // RSV3 set (0x10)
  15619. {
  15620. detail::BufferStream strm;
  15621. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  15622. ws::Opcode opcode;
  15623. std::string payload;
  15624. bool fin;
  15625. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15626. false, 1024));
  15627. }
  15628. // No RSV bits set - should succeed
  15629. {
  15630. detail::BufferStream strm;
  15631. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  15632. ws::Opcode opcode;
  15633. std::string payload;
  15634. bool fin;
  15635. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15636. false, 1024));
  15637. EXPECT_EQ(ws::Opcode::Text, opcode);
  15638. EXPECT_EQ("Hello", payload);
  15639. EXPECT_TRUE(fin);
  15640. }
  15641. }
  15642. TEST(WebSocketTest, ControlFrameValidation) {
  15643. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  15644. // payload length <= 125.
  15645. // Ping with FIN=0 - must be rejected
  15646. {
  15647. detail::BufferStream strm;
  15648. std::string frame;
  15649. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  15650. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  15651. strm.write(frame.data(), frame.size());
  15652. ws::Opcode opcode;
  15653. std::string payload;
  15654. bool fin;
  15655. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15656. false, 1024));
  15657. }
  15658. // Close with FIN=0 - must be rejected
  15659. {
  15660. detail::BufferStream strm;
  15661. std::string frame;
  15662. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  15663. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  15664. strm.write(frame.data(), frame.size());
  15665. ws::Opcode opcode;
  15666. std::string payload;
  15667. bool fin;
  15668. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15669. false, 1024));
  15670. }
  15671. // Ping with payload_len=126 (extended length) - must be rejected
  15672. {
  15673. detail::BufferStream strm;
  15674. std::string frame;
  15675. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  15676. frame += static_cast<char>(126); // payload_len=126 (>125)
  15677. frame += static_cast<char>(0x00); // extended length high byte
  15678. frame += static_cast<char>(126); // extended length low byte
  15679. frame += std::string(126, 'x');
  15680. strm.write(frame.data(), frame.size());
  15681. ws::Opcode opcode;
  15682. std::string payload;
  15683. bool fin;
  15684. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15685. false, 1024));
  15686. }
  15687. // Ping with FIN=1 and payload_len=125 - should succeed
  15688. {
  15689. detail::BufferStream strm;
  15690. std::string frame;
  15691. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  15692. frame += static_cast<char>(125); // payload_len=125
  15693. frame += std::string(125, 'x');
  15694. strm.write(frame.data(), frame.size());
  15695. ws::Opcode opcode;
  15696. std::string payload;
  15697. bool fin;
  15698. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15699. false, 1024));
  15700. EXPECT_EQ(ws::Opcode::Ping, opcode);
  15701. EXPECT_EQ(125u, payload.size());
  15702. EXPECT_TRUE(fin);
  15703. }
  15704. }
  15705. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  15706. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  15707. // length MUST be 0.
  15708. // MSB set - must be rejected
  15709. {
  15710. detail::BufferStream strm;
  15711. std::string frame;
  15712. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  15713. frame += static_cast<char>(127); // 64-bit extended length
  15714. frame += static_cast<char>(0x80); // MSB set (invalid)
  15715. frame += std::string(7, '\0'); // remaining 7 bytes of length
  15716. strm.write(frame.data(), frame.size());
  15717. ws::Opcode opcode;
  15718. std::string payload;
  15719. bool fin;
  15720. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15721. false, 1024));
  15722. }
  15723. // MSB clear - should pass length parsing (will be rejected by max_len,
  15724. // but that's a different check; use a small length to verify)
  15725. {
  15726. detail::BufferStream strm;
  15727. std::string frame;
  15728. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  15729. frame += static_cast<char>(127); // 64-bit extended length
  15730. frame += std::string(7, '\0'); // high bytes = 0
  15731. frame += static_cast<char>(0x03); // length = 3
  15732. frame += "abc";
  15733. strm.write(frame.data(), frame.size());
  15734. ws::Opcode opcode;
  15735. std::string payload;
  15736. bool fin;
  15737. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15738. false, 1024));
  15739. EXPECT_EQ(ws::Opcode::Text, opcode);
  15740. EXPECT_EQ("abc", payload);
  15741. }
  15742. }
  15743. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  15744. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  15745. // Valid UTF-8
  15746. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  15747. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  15748. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  15749. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  15750. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  15751. // Invalid UTF-8
  15752. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  15753. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  15754. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  15755. EXPECT_FALSE(
  15756. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  15757. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  15758. }
  15759. TEST(WebSocketTest, ConnectAndDisconnect) {
  15760. Server svr;
  15761. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  15762. std::string msg;
  15763. while (ws.read(msg)) {}
  15764. });
  15765. auto port = svr.bind_to_any_port(HOST);
  15766. std::thread t([&]() { svr.listen_after_bind(); });
  15767. svr.wait_until_ready();
  15768. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  15769. ASSERT_TRUE(client.connect());
  15770. EXPECT_TRUE(client.is_open());
  15771. client.close();
  15772. EXPECT_FALSE(client.is_open());
  15773. svr.stop();
  15774. t.join();
  15775. }
  15776. TEST(WebSocketTest, ValidURL) {
  15777. ws::WebSocketClient ws1("ws://localhost:8080/path");
  15778. EXPECT_TRUE(ws1.is_valid());
  15779. ws::WebSocketClient ws2("ws://example.com/path");
  15780. EXPECT_TRUE(ws2.is_valid());
  15781. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  15782. EXPECT_TRUE(ws3.is_valid());
  15783. #ifdef CPPHTTPLIB_SSL_ENABLED
  15784. ws::WebSocketClient wss1("wss://example.com/path");
  15785. EXPECT_TRUE(wss1.is_valid());
  15786. ws::WebSocketClient wss2("wss://example.com:443/path");
  15787. EXPECT_TRUE(wss2.is_valid());
  15788. #endif
  15789. }
  15790. TEST(WebSocketTest, InvalidURL) {
  15791. // No scheme
  15792. ws::WebSocketClient ws1("localhost:8080/path");
  15793. EXPECT_FALSE(ws1.is_valid());
  15794. // No path
  15795. ws::WebSocketClient ws2("ws://localhost:8080");
  15796. EXPECT_FALSE(ws2.is_valid());
  15797. // Empty string
  15798. ws::WebSocketClient ws3("");
  15799. EXPECT_FALSE(ws3.is_valid());
  15800. // Missing host
  15801. ws::WebSocketClient ws4("ws://:8080/path");
  15802. EXPECT_FALSE(ws4.is_valid());
  15803. // Port number overflow — should not crash
  15804. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  15805. EXPECT_FALSE(ws5.is_valid());
  15806. // Port out of range
  15807. ws::WebSocketClient ws6("ws://localhost:99999/path");
  15808. EXPECT_FALSE(ws6.is_valid());
  15809. }
  15810. TEST(WebSocketTest, UnsupportedScheme) {
  15811. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15812. ws::WebSocketClient ws1("http://localhost:8080/path");
  15813. EXPECT_FALSE(ws1.is_valid());
  15814. ws::WebSocketClient ws2("https://localhost:8080/path");
  15815. EXPECT_FALSE(ws2.is_valid());
  15816. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  15817. EXPECT_FALSE(ws3.is_valid());
  15818. #else
  15819. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  15820. std::invalid_argument);
  15821. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  15822. std::invalid_argument);
  15823. #endif
  15824. }
  15825. TEST(WebSocketTest, ConnectWhenInvalid) {
  15826. ws::WebSocketClient ws("not a valid url");
  15827. EXPECT_FALSE(ws.is_valid());
  15828. EXPECT_FALSE(ws.connect());
  15829. }
  15830. TEST(WebSocketTest, DefaultPort) {
  15831. ws::WebSocketClient ws1("ws://example.com/path");
  15832. EXPECT_TRUE(ws1.is_valid());
  15833. // ws:// defaults to port 80 (verified by successful parse)
  15834. #ifdef CPPHTTPLIB_SSL_ENABLED
  15835. ws::WebSocketClient ws2("wss://example.com/path");
  15836. EXPECT_TRUE(ws2.is_valid());
  15837. // wss:// defaults to port 443 (verified by successful parse)
  15838. #endif
  15839. }
  15840. TEST(WebSocketTest, IPv6LiteralAddress) {
  15841. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  15842. EXPECT_TRUE(ws1.is_valid());
  15843. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  15844. EXPECT_TRUE(ws2.is_valid());
  15845. }
  15846. TEST(WebSocketTest, ComplexPath) {
  15847. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  15848. EXPECT_TRUE(ws1.is_valid());
  15849. ws::WebSocketClient ws2("ws://localhost:8080/");
  15850. EXPECT_TRUE(ws2.is_valid());
  15851. }
  15852. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  15853. Server svr;
  15854. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  15855. std::string msg;
  15856. while (ws.read(msg)) {}
  15857. });
  15858. auto port = svr.bind_to_any_port(HOST);
  15859. std::thread t([&]() { svr.listen_after_bind(); });
  15860. svr.wait_until_ready();
  15861. auto another_host = "example.com";
  15862. auto wrong_ip = "192.0.2.1";
  15863. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  15864. client.set_hostname_addr_map({{another_host, wrong_ip}});
  15865. ASSERT_TRUE(client.connect());
  15866. EXPECT_TRUE(client.is_open());
  15867. client.close();
  15868. svr.stop();
  15869. t.join();
  15870. }
  15871. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  15872. Server svr;
  15873. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  15874. std::string msg;
  15875. while (ws.read(msg)) {}
  15876. });
  15877. auto port = svr.bind_to_any_port(HOST);
  15878. std::thread t([&]() { svr.listen_after_bind(); });
  15879. svr.wait_until_ready();
  15880. auto wrong_ip = "192.0.2.1";
  15881. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  15882. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  15883. client.set_connection_timeout(1);
  15884. client.set_read_timeout(1);
  15885. client.set_write_timeout(1);
  15886. EXPECT_FALSE(client.connect());
  15887. EXPECT_FALSE(client.is_open());
  15888. svr.stop();
  15889. t.join();
  15890. }
  15891. class WebSocketIntegrationTest : public ::testing::Test {
  15892. protected:
  15893. void SetUp() override {
  15894. server_ = httplib::detail::make_unique<Server>();
  15895. setup_server();
  15896. start_server();
  15897. }
  15898. void TearDown() override {
  15899. server_->stop();
  15900. if (server_thread_.joinable()) { server_thread_.join(); }
  15901. }
  15902. void setup_server() {
  15903. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  15904. std::string msg;
  15905. ws::ReadResult ret;
  15906. while ((ret = ws.read(msg))) {
  15907. if (ret == ws::Binary) {
  15908. ws.send(msg.data(), msg.size());
  15909. } else {
  15910. ws.send(msg);
  15911. }
  15912. }
  15913. });
  15914. server_->WebSocket("/ws-echo-string",
  15915. [](const Request &, ws::WebSocket &ws) {
  15916. std::string msg;
  15917. while (ws.read(msg)) {
  15918. ws.send("echo: " + msg);
  15919. }
  15920. });
  15921. server_->WebSocket(
  15922. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  15923. // Echo back request metadata
  15924. ws.send("path:" + req.path);
  15925. ws.send("header:" + req.get_header_value("X-Test-Header"));
  15926. std::string msg;
  15927. while (ws.read(msg)) {}
  15928. });
  15929. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  15930. std::string msg;
  15931. ws.read(msg); // wait for a message
  15932. ws.close();
  15933. });
  15934. server_->WebSocket("/ws-close-status",
  15935. [](const Request &, ws::WebSocket &ws) {
  15936. std::string msg;
  15937. ws.read(msg); // wait for a message
  15938. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  15939. });
  15940. server_->WebSocket(
  15941. "/ws-subprotocol",
  15942. [](const Request &, ws::WebSocket &ws) {
  15943. std::string msg;
  15944. while (ws.read(msg)) {
  15945. ws.send(msg);
  15946. }
  15947. },
  15948. [](const std::vector<std::string> &protocols) -> std::string {
  15949. for (const auto &p : protocols) {
  15950. if (p == "graphql-ws") { return p; }
  15951. }
  15952. return "";
  15953. });
  15954. }
  15955. void start_server() {
  15956. port_ = server_->bind_to_any_port(HOST);
  15957. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  15958. server_->wait_until_ready();
  15959. }
  15960. std::unique_ptr<Server> server_;
  15961. std::thread server_thread_;
  15962. int port_ = 0;
  15963. };
  15964. TEST_F(WebSocketIntegrationTest, TextEcho) {
  15965. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15966. "/ws-echo");
  15967. ASSERT_TRUE(client.connect());
  15968. ASSERT_TRUE(client.is_open());
  15969. ASSERT_TRUE(client.send("Hello WebSocket"));
  15970. std::string msg;
  15971. EXPECT_EQ(ws::Text, client.read(msg));
  15972. EXPECT_EQ("Hello WebSocket", msg);
  15973. client.close();
  15974. }
  15975. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  15976. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15977. "/ws-echo");
  15978. ASSERT_TRUE(client.connect());
  15979. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  15980. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  15981. std::string msg;
  15982. EXPECT_EQ(ws::Binary, client.read(msg));
  15983. EXPECT_EQ(binary_data, msg);
  15984. client.close();
  15985. }
  15986. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  15987. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15988. "/ws-echo");
  15989. ASSERT_TRUE(client.connect());
  15990. for (int i = 0; i < 10; i++) {
  15991. auto text = "message " + std::to_string(i);
  15992. ASSERT_TRUE(client.send(text));
  15993. std::string msg;
  15994. ASSERT_TRUE(client.read(msg));
  15995. EXPECT_EQ(text, msg);
  15996. }
  15997. client.close();
  15998. }
  15999. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  16000. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16001. "/ws-close");
  16002. ASSERT_TRUE(client.connect());
  16003. // Send a message to trigger the server to close
  16004. ASSERT_TRUE(client.send("trigger close"));
  16005. // The server will close, so read should return false
  16006. std::string msg;
  16007. EXPECT_FALSE(client.read(msg));
  16008. EXPECT_FALSE(client.is_open());
  16009. }
  16010. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  16011. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16012. "/ws-echo");
  16013. ASSERT_TRUE(client.connect());
  16014. // 128KB message
  16015. std::string large_data(128 * 1024, 'X');
  16016. ASSERT_TRUE(client.send(large_data));
  16017. std::string msg;
  16018. ASSERT_TRUE(client.read(msg));
  16019. EXPECT_EQ(large_data, msg);
  16020. client.close();
  16021. }
  16022. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  16023. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16024. "/ws-echo");
  16025. ASSERT_TRUE(client.connect());
  16026. const int num_threads = 4;
  16027. std::vector<std::thread> threads;
  16028. std::atomic<int> send_count{0};
  16029. for (int t = 0; t < num_threads; t++) {
  16030. threads.emplace_back([&client, &send_count, t]() {
  16031. for (int i = 0; i < 5; i++) {
  16032. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  16033. if (client.send(text)) { send_count++; }
  16034. }
  16035. });
  16036. }
  16037. for (auto &th : threads) {
  16038. th.join();
  16039. }
  16040. int received = 0;
  16041. std::string msg;
  16042. while (received < send_count.load()) {
  16043. if (!client.read(msg)) { break; }
  16044. received++;
  16045. }
  16046. EXPECT_EQ(send_count.load(), received);
  16047. client.close();
  16048. }
  16049. TEST_F(WebSocketIntegrationTest, ReadString) {
  16050. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16051. "/ws-echo-string");
  16052. ASSERT_TRUE(client.connect());
  16053. ASSERT_TRUE(client.send("hello"));
  16054. std::string msg;
  16055. ASSERT_TRUE(client.read(msg));
  16056. EXPECT_EQ("echo: hello", msg);
  16057. ASSERT_TRUE(client.send("world"));
  16058. ASSERT_TRUE(client.read(msg));
  16059. EXPECT_EQ("echo: world", msg);
  16060. client.close();
  16061. }
  16062. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  16063. Headers headers = {{"X-Test-Header", "test-value"}};
  16064. ws::WebSocketClient client(
  16065. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  16066. ASSERT_TRUE(client.connect());
  16067. std::string msg;
  16068. ASSERT_TRUE(client.read(msg));
  16069. EXPECT_EQ("path:/ws-request-info", msg);
  16070. ASSERT_TRUE(client.read(msg));
  16071. EXPECT_EQ("header:test-value", msg);
  16072. client.close();
  16073. }
  16074. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  16075. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16076. "/ws-echo");
  16077. client.set_read_timeout(1, 0); // 1 second
  16078. ASSERT_TRUE(client.connect());
  16079. // Don't send anything — server echo handler waits for a message,
  16080. // so read() should time out and return false.
  16081. std::string msg;
  16082. EXPECT_FALSE(client.read(msg));
  16083. }
  16084. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  16085. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16086. "/ws-echo");
  16087. client.set_read_timeout(5, 0);
  16088. ASSERT_TRUE(client.connect());
  16089. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  16090. // The server should reject it and close the connection.
  16091. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  16092. client.send(oversized);
  16093. // The server's read() should have failed due to payload limit,
  16094. // so our read() should return false (connection closed).
  16095. std::string msg;
  16096. EXPECT_FALSE(client.read(msg));
  16097. }
  16098. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  16099. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16100. "/ws-echo");
  16101. client.set_read_timeout(10, 0);
  16102. ASSERT_TRUE(client.connect());
  16103. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  16104. // This should succeed.
  16105. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  16106. ASSERT_TRUE(client.send(at_limit));
  16107. std::string msg;
  16108. ASSERT_TRUE(client.read(msg));
  16109. EXPECT_EQ(at_limit.size(), msg.size());
  16110. client.close();
  16111. }
  16112. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  16113. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16114. "/nonexistent");
  16115. EXPECT_FALSE(client.connect());
  16116. EXPECT_FALSE(client.is_open());
  16117. }
  16118. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  16119. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16120. "/ws-echo");
  16121. ASSERT_TRUE(client.connect());
  16122. ASSERT_TRUE(client.send(""));
  16123. std::string msg;
  16124. EXPECT_EQ(ws::Text, client.read(msg));
  16125. EXPECT_EQ("", msg);
  16126. client.close();
  16127. }
  16128. TEST_F(WebSocketIntegrationTest, Reconnect) {
  16129. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16130. "/ws-echo");
  16131. // First connection
  16132. ASSERT_TRUE(client.connect());
  16133. ASSERT_TRUE(client.send("first"));
  16134. std::string msg;
  16135. ASSERT_TRUE(client.read(msg));
  16136. EXPECT_EQ("first", msg);
  16137. client.close();
  16138. EXPECT_FALSE(client.is_open());
  16139. // Reconnect using the same client object
  16140. ASSERT_TRUE(client.connect());
  16141. ASSERT_TRUE(client.is_open());
  16142. ASSERT_TRUE(client.send("second"));
  16143. ASSERT_TRUE(client.read(msg));
  16144. EXPECT_EQ("second", msg);
  16145. client.close();
  16146. }
  16147. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  16148. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16149. "/ws-close-status");
  16150. ASSERT_TRUE(client.connect());
  16151. // Trigger the server to close with GoingAway status
  16152. ASSERT_TRUE(client.send("trigger"));
  16153. // read() should return false after receiving the close frame
  16154. std::string msg;
  16155. EXPECT_FALSE(client.read(msg));
  16156. EXPECT_FALSE(client.is_open());
  16157. }
  16158. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  16159. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16160. "/ws-echo");
  16161. ASSERT_TRUE(client.connect());
  16162. client.close(ws::CloseStatus::GoingAway, "client leaving");
  16163. EXPECT_FALSE(client.is_open());
  16164. }
  16165. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  16166. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  16167. ws::WebSocketClient client(
  16168. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  16169. ASSERT_TRUE(client.connect());
  16170. // Server should have selected graphql-ws
  16171. EXPECT_EQ("graphql-ws", client.subprotocol());
  16172. client.close();
  16173. }
  16174. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  16175. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  16176. ws::WebSocketClient client(
  16177. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  16178. ASSERT_TRUE(client.connect());
  16179. // Server should not have selected any subprotocol
  16180. EXPECT_TRUE(client.subprotocol().empty());
  16181. client.close();
  16182. }
  16183. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  16184. // Connect without requesting any subprotocol
  16185. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16186. "/ws-subprotocol");
  16187. ASSERT_TRUE(client.connect());
  16188. EXPECT_TRUE(client.subprotocol().empty());
  16189. client.close();
  16190. }
  16191. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  16192. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16193. "/ws-echo");
  16194. client.set_tcp_nodelay(true);
  16195. client.set_connection_timeout(3, 0);
  16196. bool socket_options_called = false;
  16197. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  16198. ASSERT_TRUE(client.connect());
  16199. ASSERT_TRUE(client.is_open());
  16200. EXPECT_TRUE(socket_options_called);
  16201. ASSERT_TRUE(client.send("hello"));
  16202. std::string msg;
  16203. auto result = client.read(msg);
  16204. EXPECT_EQ(result, ws::ReadResult::Text);
  16205. EXPECT_EQ(msg, "hello");
  16206. client.close();
  16207. }
  16208. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  16209. Server svr;
  16210. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  16211. if (!req.has_header("Authorization")) {
  16212. res.status = StatusCode::Unauthorized_401;
  16213. res.set_content("Unauthorized", "text/plain");
  16214. return Server::HandlerResponse::Handled;
  16215. }
  16216. return Server::HandlerResponse::Unhandled;
  16217. });
  16218. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  16219. std::string msg;
  16220. while (ws.read(msg)) {
  16221. ws.send(msg);
  16222. }
  16223. });
  16224. auto port = svr.bind_to_any_port("localhost");
  16225. std::thread t([&]() { svr.listen_after_bind(); });
  16226. svr.wait_until_ready();
  16227. // Without Authorization header - should be rejected before upgrade
  16228. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  16229. EXPECT_FALSE(client1.connect());
  16230. // With Authorization header - should succeed
  16231. Headers headers = {{"Authorization", "Bearer token123"}};
  16232. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  16233. headers);
  16234. ASSERT_TRUE(client2.connect());
  16235. ASSERT_TRUE(client2.send("hello"));
  16236. std::string msg;
  16237. ASSERT_TRUE(client2.read(msg));
  16238. EXPECT_EQ("hello", msg);
  16239. client2.close();
  16240. svr.stop();
  16241. t.join();
  16242. }
  16243. TEST(WebSocketTest, QueryStringInHandshake) {
  16244. Server svr;
  16245. std::mutex mtx;
  16246. std::string received_target;
  16247. std::string received_token;
  16248. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  16249. {
  16250. std::lock_guard<std::mutex> lock(mtx);
  16251. received_target = req.target;
  16252. if (req.has_param("token")) {
  16253. received_token = req.get_param_value("token");
  16254. }
  16255. }
  16256. std::string msg;
  16257. while (ws.read(msg)) {
  16258. ws.send(msg);
  16259. }
  16260. });
  16261. auto port = svr.bind_to_any_port("localhost");
  16262. std::thread t([&]() { svr.listen_after_bind(); });
  16263. svr.wait_until_ready();
  16264. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  16265. "/ws?token=ABC&session=123");
  16266. ASSERT_TRUE(client.connect());
  16267. // Round-trip ensures the handler has run and captured the request.
  16268. ASSERT_TRUE(client.send("hello"));
  16269. std::string msg;
  16270. ASSERT_TRUE(client.read(msg));
  16271. EXPECT_EQ("hello", msg);
  16272. client.close();
  16273. {
  16274. std::lock_guard<std::mutex> lock(mtx);
  16275. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  16276. EXPECT_EQ("ABC", received_token);
  16277. }
  16278. svr.stop();
  16279. t.join();
  16280. }
  16281. TEST(WebSocketTest, HostHeaderInHandshake) {
  16282. Server svr;
  16283. std::mutex mtx;
  16284. std::string received_host;
  16285. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  16286. {
  16287. std::lock_guard<std::mutex> lock(mtx);
  16288. received_host = req.get_header_value("Host");
  16289. }
  16290. std::string msg;
  16291. while (ws.read(msg)) {
  16292. ws.send(msg);
  16293. }
  16294. });
  16295. auto port = svr.bind_to_any_port("localhost");
  16296. std::thread t([&]() { svr.listen_after_bind(); });
  16297. svr.wait_until_ready();
  16298. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  16299. ASSERT_TRUE(client.connect());
  16300. // Round-trip ensures the handler has run and captured the request.
  16301. ASSERT_TRUE(client.send("hello"));
  16302. std::string msg;
  16303. ASSERT_TRUE(client.read(msg));
  16304. client.close();
  16305. {
  16306. std::lock_guard<std::mutex> lock(mtx);
  16307. // Non-default port must be present in the Host header. Default ports
  16308. // (80/443) are omitted; that logic is covered by
  16309. // MakeHostAndPortStringTest.
  16310. EXPECT_EQ("localhost:" + std::to_string(port), received_host);
  16311. }
  16312. svr.stop();
  16313. t.join();
  16314. }
  16315. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  16316. class WebSocketSSLIntegrationTest : public ::testing::Test {
  16317. protected:
  16318. void SetUp() override {
  16319. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  16320. SERVER_PRIVATE_KEY_FILE);
  16321. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  16322. std::string msg;
  16323. ws::ReadResult ret;
  16324. while ((ret = ws.read(msg))) {
  16325. if (ret == ws::Binary) {
  16326. ws.send(msg.data(), msg.size());
  16327. } else {
  16328. ws.send(msg);
  16329. }
  16330. }
  16331. });
  16332. port_ = server_->bind_to_any_port(HOST);
  16333. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  16334. server_->wait_until_ready();
  16335. }
  16336. void TearDown() override {
  16337. server_->stop();
  16338. if (server_thread_.joinable()) { server_thread_.join(); }
  16339. }
  16340. std::unique_ptr<SSLServer> server_;
  16341. std::thread server_thread_;
  16342. int port_ = 0;
  16343. };
  16344. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  16345. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  16346. "/ws-echo");
  16347. client.enable_server_certificate_verification(false);
  16348. ASSERT_TRUE(client.connect());
  16349. ASSERT_TRUE(client.is_open());
  16350. ASSERT_TRUE(client.send("Hello WSS"));
  16351. std::string msg;
  16352. EXPECT_EQ(ws::Text, client.read(msg));
  16353. EXPECT_EQ("Hello WSS", msg);
  16354. client.close();
  16355. }
  16356. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  16357. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  16358. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  16359. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  16360. // client (without calling close() first) is the only path that runs
  16361. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  16362. // bug exactly.
  16363. //
  16364. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  16365. // when linked against an instrumented libssl; run under Valgrind to catch it
  16366. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  16367. // suite (the freed session otherwise stalls on the close handshake) — this test
  16368. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  16369. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  16370. {
  16371. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  16372. "/ws-echo");
  16373. client.enable_server_certificate_verification(false);
  16374. client.set_read_timeout(2, 0);
  16375. client.set_write_timeout(2, 0);
  16376. ASSERT_TRUE(client.connect());
  16377. ASSERT_TRUE(client.is_open());
  16378. ASSERT_TRUE(client.send("still open"));
  16379. // Intentionally do NOT call client.close(): leaving scope runs
  16380. // shutdown_and_close() with the WebSocket still open, which must send the
  16381. // close frame while the TLS session is still alive.
  16382. }
  16383. }
  16384. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  16385. // shutdown_and_close() at the start of connect(), reproducing the same
  16386. // use-after-free within the test body rather than at scope exit. The second
  16387. // connect must succeed and echo, proving the close handshake ran over a live
  16388. // session. See the note above about memory-tool requirements.
  16389. TEST_F(WebSocketSSLIntegrationTest,
  16390. ReconnectWhileOpenSendsCloseOverLiveSession) {
  16391. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  16392. "/ws-echo");
  16393. client.enable_server_certificate_verification(false);
  16394. client.set_read_timeout(2, 0);
  16395. client.set_write_timeout(2, 0);
  16396. ASSERT_TRUE(client.connect());
  16397. ASSERT_TRUE(client.is_open());
  16398. ASSERT_TRUE(client.send("still open"));
  16399. // Reconnect without closing first: connect() calls shutdown_and_close() on
  16400. // the still-open connection, which must not touch a freed TLS session.
  16401. ASSERT_TRUE(client.connect());
  16402. ASSERT_TRUE(client.is_open());
  16403. ASSERT_TRUE(client.send("after reconnect"));
  16404. std::string msg;
  16405. EXPECT_EQ(ws::Text, client.read(msg));
  16406. EXPECT_EQ("after reconnect", msg);
  16407. client.close();
  16408. }
  16409. #endif
  16410. #ifdef CPPHTTPLIB_SSL_ENABLED
  16411. class WebSocketSSLCATest : public ::testing::Test {
  16412. protected:
  16413. void SetUp() override {
  16414. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  16415. SERVER_PRIVATE_KEY_FILE);
  16416. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  16417. std::string msg;
  16418. while (ws.read(msg)) {
  16419. ws.send(msg);
  16420. }
  16421. });
  16422. port_ = server_->bind_to_any_port("127.0.0.1");
  16423. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  16424. server_->wait_until_ready();
  16425. }
  16426. void TearDown() override {
  16427. server_->stop();
  16428. if (server_thread_.joinable()) { server_thread_.join(); }
  16429. }
  16430. std::string url() const {
  16431. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  16432. }
  16433. std::unique_ptr<SSLServer> server_;
  16434. std::thread server_thread_;
  16435. int port_ = 0;
  16436. };
  16437. // A custom CA loaded as PEM verifies the server with full certificate
  16438. // verification enabled
  16439. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  16440. ws::WebSocketClient client(url());
  16441. std::string cert;
  16442. read_file(SERVER_CERT2_FILE, cert);
  16443. client.load_ca_cert_store(cert.c_str(), cert.size());
  16444. ASSERT_TRUE(client.connect());
  16445. ASSERT_TRUE(client.send("hello"));
  16446. std::string msg;
  16447. EXPECT_EQ(ws::Text, client.read(msg));
  16448. EXPECT_EQ("hello", msg);
  16449. client.close();
  16450. }
  16451. // A custom CA that does not cover the server must fail verification (the
  16452. // custom CA is exclusive; system certs are not loaded alongside it)
  16453. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  16454. ws::WebSocketClient client(url());
  16455. std::string cert;
  16456. read_file(CLIENT_CA_CERT_FILE, cert);
  16457. client.load_ca_cert_store(cert.c_str(), cert.size());
  16458. ASSERT_FALSE(client.connect());
  16459. }
  16460. // Regression test: reconnecting with a native custom CA store used to reuse
  16461. // a store handle the previous TLS context had already freed (use-after-free
  16462. // under the OpenSSL backend). The context now lives as long as the client.
  16463. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  16464. ws::WebSocketClient client(url());
  16465. std::string cert;
  16466. read_file(SERVER_CERT2_FILE, cert);
  16467. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  16468. ASSERT_TRUE(client.connect());
  16469. client.close();
  16470. ASSERT_TRUE(client.connect());
  16471. ASSERT_TRUE(client.send("again"));
  16472. std::string msg;
  16473. EXPECT_EQ(ws::Text, client.read(msg));
  16474. EXPECT_EQ("again", msg);
  16475. client.close();
  16476. }
  16477. // Regression test: a certificate with a trusted chain but no identity match
  16478. // for the server IP must be rejected. The Mbed TLS backend used to skip
  16479. // verification entirely for IP hosts, so this connection succeeded there.
  16480. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  16481. // chain verification while the identity check must still fail.
  16482. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  16483. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16484. ASSERT_TRUE(svr.is_valid());
  16485. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  16486. std::string msg;
  16487. while (ws.read(msg)) {
  16488. ws.send(msg);
  16489. }
  16490. });
  16491. auto port = svr.bind_to_any_port("127.0.0.1");
  16492. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16493. auto se = detail::scope_exit([&] {
  16494. svr.stop();
  16495. t.join();
  16496. });
  16497. svr.wait_until_ready();
  16498. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  16499. "/echo");
  16500. std::string cert;
  16501. read_file(SERVER_CERT_FILE, cert);
  16502. client.load_ca_cert_store(cert.c_str(), cert.size());
  16503. ASSERT_FALSE(client.connect());
  16504. }
  16505. #endif
  16506. #if !defined(_WIN32)
  16507. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  16508. auto secret_dir = std::string("./symlink_test_secret");
  16509. auto served_dir = std::string("./symlink_test_served");
  16510. auto secret_file = secret_dir + "/secret.txt";
  16511. auto symlink_path = served_dir + "/escape";
  16512. // Setup: create directories and files
  16513. mkdir(secret_dir.c_str(), 0755);
  16514. mkdir(served_dir.c_str(), 0755);
  16515. {
  16516. std::ofstream ofs(secret_file);
  16517. ofs << "SECRET_DATA";
  16518. }
  16519. // Create symlink using absolute path so it resolves correctly
  16520. #ifdef PATH_MAX
  16521. char abs_secret[PATH_MAX];
  16522. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  16523. #else
  16524. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  16525. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  16526. ASSERT_NE(nullptr, abs_secret);
  16527. #endif
  16528. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  16529. auto se = detail::scope_exit([&] {
  16530. unlink(symlink_path.c_str());
  16531. unlink(secret_file.c_str());
  16532. rmdir(served_dir.c_str());
  16533. rmdir(secret_dir.c_str());
  16534. });
  16535. Server svr;
  16536. svr.set_mount_point("/", served_dir);
  16537. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  16538. auto se2 = detail::scope_exit([&] {
  16539. svr.stop();
  16540. listen_thread.join();
  16541. });
  16542. svr.wait_until_ready();
  16543. Client cli("localhost", PORT);
  16544. // Symlink pointing outside base dir should be blocked
  16545. auto res = cli.Get("/escape/secret.txt");
  16546. ASSERT_TRUE(res);
  16547. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  16548. }
  16549. #endif
  16550. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  16551. // A GET request with Content-Length to a static file handler must have its
  16552. // body drained before the keep-alive connection is reused. Otherwise the
  16553. // unread body bytes are interpreted as the next HTTP request.
  16554. //
  16555. // The body is sent AFTER receiving the first response (as in the original
  16556. // PoC) so that the stream_line_reader cannot buffer it together with the
  16557. // headers of the first request.
  16558. Server svr;
  16559. svr.set_mount_point("/", "./www");
  16560. std::atomic<int> smuggled_count(0);
  16561. svr.Get("/smuggled", [&](const Request &, Response &res) {
  16562. smuggled_count++;
  16563. res.set_content("oops", "text/plain");
  16564. });
  16565. auto port = svr.bind_to_any_port("localhost");
  16566. thread t = thread([&] { svr.listen_after_bind(); });
  16567. auto se = detail::scope_exit([&] {
  16568. svr.stop();
  16569. t.join();
  16570. });
  16571. svr.wait_until_ready();
  16572. auto error = Error::Success;
  16573. auto sock = detail::create_client_socket(
  16574. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  16575. /*connection_timeout_sec=*/2, 0,
  16576. /*read_timeout_sec=*/2, 0,
  16577. /*write_timeout_sec=*/2, 0, std::string(), error);
  16578. ASSERT_NE(INVALID_SOCKET, sock);
  16579. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  16580. // The "smuggled" request will be sent as the body of the outer GET
  16581. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  16582. "Host: localhost\r\n"
  16583. "Connection: close\r\n"
  16584. "\r\n";
  16585. // Step 1: Send only the outer request headers (no body yet)
  16586. std::string outer_headers = "GET /file HTTP/1.1\r\n"
  16587. "Host: localhost\r\n"
  16588. "Content-Length: " +
  16589. std::to_string(smuggled.size()) +
  16590. "\r\n"
  16591. "\r\n";
  16592. auto sent = send(sock, outer_headers.data(), outer_headers.size(), 0);
  16593. ASSERT_EQ(static_cast<ssize_t>(outer_headers.size()), sent);
  16594. // Step 2: Read the first response (server serves file without reading body)
  16595. std::string first_response;
  16596. char buf[4096];
  16597. for (;;) {
  16598. auto n = recv(sock, buf, sizeof(buf), 0);
  16599. if (n <= 0) break;
  16600. first_response.append(buf, static_cast<size_t>(n));
  16601. // Stop once we have a complete response (headers + body)
  16602. auto hdr_end = first_response.find("\r\n\r\n");
  16603. if (hdr_end != std::string::npos) {
  16604. // Check for Content-Length to know when the body is complete
  16605. auto cl_pos = first_response.find("Content-Length:");
  16606. if (cl_pos != std::string::npos) {
  16607. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  16608. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  16609. auto cl = std::stoul(
  16610. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  16611. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  16612. } else {
  16613. break; // No Content-Length, assume headers-only response
  16614. }
  16615. }
  16616. }
  16617. ASSERT_TRUE(first_response.find("HTTP/1.1 200") != std::string::npos);
  16618. // Step 3: Now send the body, which looks like a new HTTP request.
  16619. // On a vulnerable server the keep-alive loop reads this as a second request.
  16620. sent = send(sock, smuggled.data(), smuggled.size(), 0);
  16621. ASSERT_EQ(static_cast<ssize_t>(smuggled.size()), sent);
  16622. // Step 4: Try to read a second response (should NOT exist after fix)
  16623. std::string second_response;
  16624. for (;;) {
  16625. auto n = recv(sock, buf, sizeof(buf), 0);
  16626. if (n <= 0) break;
  16627. second_response.append(buf, static_cast<size_t>(n));
  16628. }
  16629. // The smuggled request must NOT have been processed
  16630. EXPECT_EQ(0, smuggled_count.load());
  16631. }
  16632. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  16633. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  16634. // must be rejected with 400 Bad Request.
  16635. Server svr;
  16636. svr.Post("/test", [&](const Request &, Response &res) {
  16637. res.set_content("ok", "text/plain");
  16638. });
  16639. thread t = thread([&] { svr.listen(HOST, PORT); });
  16640. auto se = detail::scope_exit([&] {
  16641. svr.stop();
  16642. t.join();
  16643. ASSERT_FALSE(svr.is_running());
  16644. });
  16645. svr.wait_until_ready();
  16646. // Exact "chunked"
  16647. {
  16648. auto req = "POST /test HTTP/1.1\r\n"
  16649. "Host: localhost\r\n"
  16650. "Content-Length: 5\r\n"
  16651. "Transfer-Encoding: chunked\r\n"
  16652. "Connection: close\r\n"
  16653. "\r\n"
  16654. "hello";
  16655. std::string response;
  16656. ASSERT_TRUE(send_request(1, req, &response));
  16657. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  16658. response.substr(0, response.find("\r\n")));
  16659. }
  16660. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  16661. {
  16662. auto req = "POST /test HTTP/1.1\r\n"
  16663. "Host: localhost\r\n"
  16664. "Content-Length: 5\r\n"
  16665. "Transfer-Encoding: gzip, chunked\r\n"
  16666. "Connection: close\r\n"
  16667. "\r\n"
  16668. "hello";
  16669. std::string response;
  16670. ASSERT_TRUE(send_request(1, req, &response));
  16671. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  16672. response.substr(0, response.find("\r\n")));
  16673. }
  16674. }
  16675. // Regression for issue #2450: a DELETE without Content-Length on a
  16676. // keep-alive connection must not let the post-response drain consume the
  16677. // next request's bytes.
  16678. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  16679. Server svr;
  16680. std::atomic<int> delete_count(0);
  16681. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  16682. delete_count++;
  16683. res.status = StatusCode::NoContent_204;
  16684. });
  16685. auto port = svr.bind_to_any_port(HOST);
  16686. thread t = thread([&] { svr.listen_after_bind(); });
  16687. auto se = detail::scope_exit([&] {
  16688. svr.stop();
  16689. t.join();
  16690. });
  16691. svr.wait_until_ready();
  16692. auto error = Error::Success;
  16693. auto sock = detail::create_client_socket(
  16694. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  16695. /*connection_timeout_sec=*/2, 0,
  16696. /*read_timeout_sec=*/2, 0,
  16697. /*write_timeout_sec=*/2, 0, std::string(), error);
  16698. ASSERT_NE(INVALID_SOCKET, sock);
  16699. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  16700. auto send_request_and_read_response = [&](const std::string &req,
  16701. std::string &out) -> bool {
  16702. auto sent = send(sock, req.data(), req.size(), 0);
  16703. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  16704. char buf[4096];
  16705. for (;;) {
  16706. auto n = recv(sock, buf, sizeof(buf), 0);
  16707. if (n <= 0) { return !out.empty(); }
  16708. out.append(buf, static_cast<size_t>(n));
  16709. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  16710. }
  16711. };
  16712. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  16713. "Host: localhost\r\n"
  16714. "\r\n";
  16715. std::string resp1;
  16716. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  16717. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  16718. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  16719. "Host: localhost\r\n"
  16720. "Connection: close\r\n"
  16721. "\r\n";
  16722. std::string resp2;
  16723. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  16724. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  16725. EXPECT_EQ(2, delete_count.load());
  16726. }
  16727. namespace no_proxy_test {
  16728. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  16729. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  16730. // calling listen().
  16731. class ScopedServer {
  16732. public:
  16733. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  16734. ~ScopedServer() {
  16735. svr_.stop();
  16736. if (th_.joinable()) { th_.join(); }
  16737. }
  16738. Server &svr() { return svr_; }
  16739. int port() const { return port_; }
  16740. void listen() {
  16741. th_ = std::thread([this] { svr_.listen_after_bind(); });
  16742. svr_.wait_until_ready();
  16743. }
  16744. private:
  16745. Server svr_;
  16746. std::thread th_;
  16747. int port_ = 0;
  16748. };
  16749. class ProxyAndTargetServers {
  16750. public:
  16751. ProxyAndTargetServers() {
  16752. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  16753. proxy_hits_++;
  16754. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  16755. res.set_content("via-proxy", "text/plain");
  16756. });
  16757. target_.Get(".*", [this](const Request &req, Response &res) {
  16758. target_hits_++;
  16759. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  16760. res.set_content("direct", "text/plain");
  16761. });
  16762. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  16763. target_port_ = target_.bind_to_any_port("127.0.0.1");
  16764. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  16765. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  16766. proxy_mock_.wait_until_ready();
  16767. target_.wait_until_ready();
  16768. }
  16769. ~ProxyAndTargetServers() {
  16770. proxy_mock_.stop();
  16771. target_.stop();
  16772. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  16773. if (target_thread_.joinable()) { target_thread_.join(); }
  16774. }
  16775. Server &proxy_mock() { return proxy_mock_; }
  16776. Server &target() { return target_; }
  16777. int proxy_port() const { return proxy_port_; }
  16778. int target_port() const { return target_port_; }
  16779. int proxy_hits() const { return proxy_hits_.load(); }
  16780. int target_hits() const { return target_hits_.load(); }
  16781. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  16782. void reset_counters() {
  16783. proxy_hits_ = 0;
  16784. target_hits_ = 0;
  16785. last_had_proxy_authz_ = false;
  16786. }
  16787. private:
  16788. Server proxy_mock_;
  16789. Server target_;
  16790. std::thread proxy_thread_;
  16791. std::thread target_thread_;
  16792. int proxy_port_ = 0;
  16793. int target_port_ = 0;
  16794. std::atomic<int> proxy_hits_{0};
  16795. std::atomic<int> target_hits_{0};
  16796. std::atomic<bool> last_had_proxy_authz_{false};
  16797. };
  16798. inline std::unique_ptr<Client> make_client(const std::string &host,
  16799. ProxyAndTargetServers &s) {
  16800. auto cli = detail::make_unique<Client>(host, s.target_port());
  16801. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  16802. cli->set_proxy("127.0.0.1", s.proxy_port());
  16803. return cli;
  16804. }
  16805. } // namespace no_proxy_test
  16806. using no_proxy_test::make_client;
  16807. using no_proxy_test::ProxyAndTargetServers;
  16808. TEST(NoProxyTest, ExactHostnameBypasses) {
  16809. ProxyAndTargetServers s;
  16810. auto cli = make_client("example.com", s);
  16811. cli->set_no_proxy({"example.com"});
  16812. auto res = cli->Get("/");
  16813. ASSERT_TRUE(res);
  16814. EXPECT_EQ(0, s.proxy_hits());
  16815. EXPECT_EQ(1, s.target_hits());
  16816. }
  16817. TEST(NoProxyTest, SubdomainBypasses) {
  16818. ProxyAndTargetServers s;
  16819. auto cli = make_client("foo.example.com", s);
  16820. cli->set_no_proxy({"example.com"});
  16821. auto res = cli->Get("/");
  16822. ASSERT_TRUE(res);
  16823. EXPECT_EQ(0, s.proxy_hits());
  16824. EXPECT_EQ(1, s.target_hits());
  16825. }
  16826. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  16827. // Regression guard: "evilexample.com" must not be considered a subdomain
  16828. // of "example.com". Without the dot-boundary rule, a naive endsWith
  16829. // check would let traffic bypass the proxy and leak credentials direct
  16830. // to the attacker host.
  16831. ProxyAndTargetServers s;
  16832. auto cli = make_client("evilexample.com", s);
  16833. cli->set_no_proxy({"example.com"});
  16834. auto res = cli->Get("/");
  16835. ASSERT_TRUE(res);
  16836. EXPECT_GE(s.proxy_hits(), 1);
  16837. EXPECT_EQ(0, s.target_hits());
  16838. }
  16839. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  16840. ProxyAndTargetServers s;
  16841. auto cli = make_client("example.com.evil.com", s);
  16842. cli->set_no_proxy({"example.com"});
  16843. auto res = cli->Get("/");
  16844. ASSERT_TRUE(res);
  16845. EXPECT_GE(s.proxy_hits(), 1);
  16846. EXPECT_EQ(0, s.target_hits());
  16847. }
  16848. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  16849. ProxyAndTargetServers s;
  16850. auto cli = make_client("example.com", s);
  16851. cli->set_no_proxy({".example.com"});
  16852. auto res = cli->Get("/");
  16853. ASSERT_TRUE(res);
  16854. EXPECT_EQ(0, s.proxy_hits());
  16855. EXPECT_EQ(1, s.target_hits());
  16856. }
  16857. TEST(NoProxyTest, CaseInsensitiveHostname) {
  16858. ProxyAndTargetServers s;
  16859. auto cli = make_client("Example.COM", s);
  16860. cli->set_no_proxy({"EXAMPLE.com"});
  16861. auto res = cli->Get("/");
  16862. ASSERT_TRUE(res);
  16863. EXPECT_EQ(0, s.proxy_hits());
  16864. EXPECT_EQ(1, s.target_hits());
  16865. }
  16866. TEST(NoProxyTest, TrailingDotIsNormalized) {
  16867. ProxyAndTargetServers s;
  16868. auto cli = make_client("example.com.", s);
  16869. cli->set_no_proxy({"example.com"});
  16870. auto res = cli->Get("/");
  16871. ASSERT_TRUE(res);
  16872. EXPECT_EQ(0, s.proxy_hits());
  16873. EXPECT_EQ(1, s.target_hits());
  16874. }
  16875. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  16876. // Trailing dots must be normalized on BOTH sides — host and entry.
  16877. // An implementation that only strips the host-side trailing dot would
  16878. // fail to match host "example.com" against entry "example.com." because
  16879. // a literal substring search would compare 11 chars against 12.
  16880. ProxyAndTargetServers s;
  16881. auto cli = make_client("example.com", s);
  16882. cli->set_no_proxy({"example.com."});
  16883. auto res = cli->Get("/");
  16884. ASSERT_TRUE(res);
  16885. EXPECT_EQ(0, s.proxy_hits());
  16886. EXPECT_EQ(1, s.target_hits());
  16887. }
  16888. TEST(NoProxyTest, WildcardBypassesEverything) {
  16889. ProxyAndTargetServers s;
  16890. auto cli = make_client("anything.invalid.test", s);
  16891. cli->set_no_proxy({"*"});
  16892. auto res = cli->Get("/");
  16893. ASSERT_TRUE(res);
  16894. EXPECT_EQ(0, s.proxy_hits());
  16895. EXPECT_EQ(1, s.target_hits());
  16896. }
  16897. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  16898. ProxyAndTargetServers s;
  16899. Client cli("127.0.0.1", s.target_port());
  16900. cli.set_proxy("127.0.0.1", s.proxy_port());
  16901. cli.set_no_proxy({"127.0.0.1"});
  16902. auto res = cli.Get("/");
  16903. ASSERT_TRUE(res);
  16904. EXPECT_EQ(0, s.proxy_hits());
  16905. EXPECT_EQ(1, s.target_hits());
  16906. }
  16907. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  16908. ProxyAndTargetServers s;
  16909. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  16910. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  16911. cli.set_proxy("127.0.0.1", s.proxy_port());
  16912. cli.set_no_proxy({"::1"});
  16913. auto res = cli.Get("/");
  16914. ASSERT_TRUE(res);
  16915. EXPECT_EQ(0, s.proxy_hits());
  16916. EXPECT_EQ(1, s.target_hits());
  16917. }
  16918. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  16919. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  16920. // must still be recognized as IPv6 for CIDR matching. Implementations
  16921. // that detect IPv6 only when the host begins with '[' would parse the
  16922. // host as a hostname and miss the match.
  16923. ProxyAndTargetServers s;
  16924. Client cli("fe80::1", s.target_port());
  16925. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  16926. cli.set_proxy("127.0.0.1", s.proxy_port());
  16927. cli.set_no_proxy({"fe80::/10"});
  16928. auto res = cli.Get("/");
  16929. ASSERT_TRUE(res);
  16930. EXPECT_EQ(0, s.proxy_hits());
  16931. EXPECT_EQ(1, s.target_hits());
  16932. }
  16933. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  16934. ProxyAndTargetServers s;
  16935. Client cli("::1", s.target_port());
  16936. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  16937. cli.set_proxy("127.0.0.1", s.proxy_port());
  16938. cli.set_no_proxy({"[::1]"});
  16939. auto res = cli.Get("/");
  16940. ASSERT_TRUE(res);
  16941. EXPECT_EQ(0, s.proxy_hits());
  16942. EXPECT_EQ(1, s.target_hits());
  16943. }
  16944. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  16945. ProxyAndTargetServers s;
  16946. Client cli("fe80::1", s.target_port());
  16947. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  16948. cli.set_proxy("127.0.0.1", s.proxy_port());
  16949. cli.set_no_proxy({"[fe80::]/10"});
  16950. auto res = cli.Get("/");
  16951. ASSERT_TRUE(res);
  16952. EXPECT_EQ(0, s.proxy_hits());
  16953. EXPECT_EQ(1, s.target_hits());
  16954. }
  16955. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  16956. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  16957. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  16958. // tricks via address-family conversion.
  16959. ProxyAndTargetServers s;
  16960. Client cli("::ffff:127.0.0.1", s.target_port());
  16961. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  16962. cli.set_proxy("127.0.0.1", s.proxy_port());
  16963. cli.set_no_proxy({"127.0.0.1"});
  16964. auto res = cli.Get("/");
  16965. ASSERT_TRUE(res);
  16966. EXPECT_GE(s.proxy_hits(), 1);
  16967. EXPECT_EQ(0, s.target_hits());
  16968. }
  16969. TEST(NoProxyTest, IPv4CidrMatch) {
  16970. ProxyAndTargetServers s;
  16971. Client cli("127.0.0.1", s.target_port());
  16972. cli.set_proxy("127.0.0.1", s.proxy_port());
  16973. cli.set_no_proxy({"127.0.0.0/8"});
  16974. auto res = cli.Get("/");
  16975. ASSERT_TRUE(res);
  16976. EXPECT_EQ(0, s.proxy_hits());
  16977. EXPECT_EQ(1, s.target_hits());
  16978. }
  16979. TEST(NoProxyTest, IPv4CidrNonMatch) {
  16980. ProxyAndTargetServers s;
  16981. Client cli("127.0.0.1", s.target_port());
  16982. cli.set_proxy("127.0.0.1", s.proxy_port());
  16983. cli.set_no_proxy({"10.0.0.0/8"});
  16984. auto res = cli.Get("/");
  16985. ASSERT_TRUE(res);
  16986. EXPECT_GE(s.proxy_hits(), 1);
  16987. EXPECT_EQ(0, s.target_hits());
  16988. }
  16989. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  16990. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  16991. // IPv4 target matches.
  16992. ProxyAndTargetServers s;
  16993. Client cli("127.0.0.1", s.target_port());
  16994. cli.set_proxy("127.0.0.1", s.proxy_port());
  16995. cli.set_no_proxy({"0.0.0.0/0"});
  16996. auto res = cli.Get("/");
  16997. ASSERT_TRUE(res);
  16998. EXPECT_EQ(0, s.proxy_hits());
  16999. EXPECT_EQ(1, s.target_hits());
  17000. }
  17001. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  17002. ProxyAndTargetServers s;
  17003. Client cli("127.0.0.1", s.target_port());
  17004. cli.set_proxy("127.0.0.1", s.proxy_port());
  17005. cli.set_no_proxy({"127.0.0.1"});
  17006. auto res = cli.Get("/");
  17007. ASSERT_TRUE(res);
  17008. EXPECT_EQ(0, s.proxy_hits());
  17009. EXPECT_EQ(1, s.target_hits());
  17010. }
  17011. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  17012. ProxyAndTargetServers s;
  17013. Client cli("127.0.0.1", s.target_port());
  17014. cli.set_proxy("127.0.0.1", s.proxy_port());
  17015. cli.set_no_proxy({"127.0.0.0/33"});
  17016. auto res = cli.Get("/");
  17017. ASSERT_TRUE(res);
  17018. EXPECT_GE(s.proxy_hits(), 1);
  17019. EXPECT_EQ(0, s.target_hits());
  17020. }
  17021. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  17022. // Empty prefix after the slash must be rejected, not silently treated as /32.
  17023. ProxyAndTargetServers s;
  17024. Client cli("127.0.0.1", s.target_port());
  17025. cli.set_proxy("127.0.0.1", s.proxy_port());
  17026. cli.set_no_proxy({"127.0.0.1/"});
  17027. auto res = cli.Get("/");
  17028. ASSERT_TRUE(res);
  17029. EXPECT_GE(s.proxy_hits(), 1);
  17030. EXPECT_EQ(0, s.target_hits());
  17031. }
  17032. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  17033. ProxyAndTargetServers s;
  17034. auto cli = make_client("internal.corp", s);
  17035. cli->set_proxy_basic_auth("u", "p");
  17036. cli->set_no_proxy({"internal.corp"});
  17037. auto res = cli->Get("/");
  17038. ASSERT_TRUE(res);
  17039. EXPECT_EQ(1, s.target_hits());
  17040. EXPECT_EQ(0, s.proxy_hits());
  17041. EXPECT_FALSE(s.last_had_proxy_authz())
  17042. << "Proxy-Authorization must not be sent direct to the target";
  17043. }
  17044. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  17045. ProxyAndTargetServers s;
  17046. auto cli = make_client("public.example", s);
  17047. cli->set_proxy_basic_auth("u", "p");
  17048. cli->set_no_proxy({"internal.corp"}); // does not match
  17049. auto res = cli->Get("/");
  17050. ASSERT_TRUE(res);
  17051. EXPECT_GE(s.proxy_hits(), 1);
  17052. EXPECT_TRUE(s.last_had_proxy_authz());
  17053. }
  17054. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  17055. ProxyAndTargetServers s;
  17056. auto cli = make_client("anything.test", s);
  17057. auto res = cli->Get("/");
  17058. ASSERT_TRUE(res);
  17059. EXPECT_GE(s.proxy_hits(), 1);
  17060. EXPECT_EQ(0, s.target_hits());
  17061. }
  17062. TEST(NoProxyTest, PortSpecificEntryRejected) {
  17063. ProxyAndTargetServers s;
  17064. auto cli = make_client("example.com", s);
  17065. cli->set_no_proxy({"example.com:8080"});
  17066. auto res = cli->Get("/");
  17067. ASSERT_TRUE(res);
  17068. EXPECT_GE(s.proxy_hits(), 1);
  17069. EXPECT_EQ(0, s.target_hits());
  17070. }
  17071. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  17072. ProxyAndTargetServers s;
  17073. auto cli = make_client("anything.test", s);
  17074. cli->set_no_proxy({"", " ", "\t"});
  17075. auto res = cli->Get("/");
  17076. ASSERT_TRUE(res);
  17077. EXPECT_GE(s.proxy_hits(), 1);
  17078. EXPECT_EQ(0, s.target_hits());
  17079. }
  17080. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  17081. // An entry with leading/trailing whitespace must still match — env-style
  17082. // values are commonly pasted with stray spaces and an implementation
  17083. // that feeds the raw token directly to inet_pton would fail to match
  17084. // valid CIDRs because of the spaces.
  17085. ProxyAndTargetServers s;
  17086. Client cli("127.0.0.1", s.target_port());
  17087. cli.set_proxy("127.0.0.1", s.proxy_port());
  17088. cli.set_no_proxy({" 127.0.0.0/8 "});
  17089. auto res = cli.Get("/");
  17090. ASSERT_TRUE(res);
  17091. EXPECT_EQ(0, s.proxy_hits());
  17092. EXPECT_EQ(1, s.target_hits());
  17093. }
  17094. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  17095. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  17096. // go direct and must NOT carry Proxy-Authorization.
  17097. std::atomic<int> proxy_hits{0};
  17098. std::atomic<int> target_hits{0};
  17099. std::atomic<bool> target_saw_authz{false};
  17100. no_proxy_test::ScopedServer proxy_mock, target;
  17101. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  17102. proxy_hits++;
  17103. res.status = 302;
  17104. res.set_header("Location", "http://127.0.0.1:" +
  17105. std::to_string(target.port()) + "/landed");
  17106. });
  17107. target.svr().Get(".*", [&](const Request &req, Response &res) {
  17108. target_hits++;
  17109. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  17110. res.set_content("direct", "text/plain");
  17111. });
  17112. proxy_mock.listen();
  17113. target.listen();
  17114. Client cli("public.example", target.port());
  17115. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  17116. cli.set_proxy("127.0.0.1", proxy_mock.port());
  17117. cli.set_proxy_basic_auth("u", "p");
  17118. cli.set_no_proxy({"127.0.0.1"});
  17119. cli.set_follow_location(true);
  17120. auto res = cli.Get("/redir");
  17121. ASSERT_TRUE(res);
  17122. EXPECT_GE(proxy_hits.load(), 1);
  17123. EXPECT_GE(target_hits.load(), 1);
  17124. EXPECT_FALSE(target_saw_authz.load());
  17125. }
  17126. #ifdef CPPHTTPLIB_SSL_ENABLED
  17127. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  17128. // Direct origin replying 407 must not trigger the digest retry; otherwise
  17129. // proxy creds would be sent to the (possibly hostile) origin.
  17130. std::atomic<int> target_hits{0};
  17131. std::atomic<bool> target_saw_proxy_authz{false};
  17132. no_proxy_test::ScopedServer target;
  17133. target.svr().Get(".*", [&](const Request &req, Response &res) {
  17134. target_hits++;
  17135. if (req.has_header("Proxy-Authorization")) {
  17136. target_saw_proxy_authz = true;
  17137. }
  17138. res.status = StatusCode::ProxyAuthenticationRequired_407;
  17139. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  17140. "nonce=\"abc\", algorithm=MD5");
  17141. });
  17142. target.listen();
  17143. // The proxy address is set to the target's port: the bypass MUST kick in;
  17144. // if it doesn't, the test still routes "via proxy" to the same server and
  17145. // the Proxy-Authorization assertion below catches the leak.
  17146. Client cli("evil.example", target.port());
  17147. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  17148. cli.set_proxy("127.0.0.1", target.port());
  17149. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  17150. cli.set_no_proxy({"evil.example"});
  17151. auto res = cli.Get("/x");
  17152. ASSERT_TRUE(res);
  17153. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  17154. EXPECT_EQ(1, target_hits.load());
  17155. EXPECT_FALSE(target_saw_proxy_authz.load());
  17156. }
  17157. #endif
  17158. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  17159. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  17160. std::atomic<int> proxy_hits{0};
  17161. std::atomic<int> bypass_hits{0};
  17162. std::atomic<bool> proxy_saw_c_url{false};
  17163. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  17164. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  17165. proxy_hits++;
  17166. if (req.path.find("/start") != std::string::npos) {
  17167. res.status = 302;
  17168. res.set_header("Location", "http://127.0.0.1:" +
  17169. std::to_string(bypass_server.port()) +
  17170. "/middle");
  17171. return;
  17172. }
  17173. if (req.path.find("/end") != std::string::npos) {
  17174. proxy_saw_c_url = true;
  17175. res.set_content("c-via-proxy", "text/plain");
  17176. return;
  17177. }
  17178. res.set_content("unexpected", "text/plain");
  17179. });
  17180. // public.example's "advertised" port is arbitrary (the request never lands
  17181. // there — it goes through the proxy), but use a dynamic value to stay
  17182. // friendly with sharded parallel runs.
  17183. int public_port = bypass_server.port();
  17184. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  17185. bypass_hits++;
  17186. res.status = 302;
  17187. res.set_header("Location", "http://public.example:" +
  17188. std::to_string(public_port) + "/end");
  17189. });
  17190. proxy_mock.listen();
  17191. bypass_server.listen();
  17192. Client cli("public.example", public_port);
  17193. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  17194. cli.set_proxy("127.0.0.1", proxy_mock.port());
  17195. cli.set_no_proxy({"127.0.0.1"});
  17196. cli.set_follow_location(true);
  17197. auto res = cli.Get("/start");
  17198. ASSERT_TRUE(res);
  17199. EXPECT_EQ(StatusCode::OK_200, res->status);
  17200. EXPECT_EQ("c-via-proxy", res->body);
  17201. EXPECT_GE(proxy_hits.load(), 2);
  17202. EXPECT_GE(bypass_hits.load(), 1);
  17203. EXPECT_TRUE(proxy_saw_c_url.load());
  17204. }
  17205. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  17206. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  17207. // request reconnects to the correct endpoint.
  17208. std::atomic<int> proxy_hits{0};
  17209. std::atomic<int> target_hits{0};
  17210. no_proxy_test::ScopedServer proxy_mock, target;
  17211. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  17212. proxy_hits++;
  17213. res.set_content("via-proxy", "text/plain");
  17214. });
  17215. target.svr().Get(".*", [&](const Request &, Response &res) {
  17216. target_hits++;
  17217. res.set_content("direct", "text/plain");
  17218. });
  17219. proxy_mock.listen();
  17220. target.listen();
  17221. Client cli("public.example", target.port());
  17222. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  17223. cli.set_proxy("127.0.0.1", proxy_mock.port());
  17224. cli.set_keep_alive(true);
  17225. auto res1 = cli.Get("/a");
  17226. ASSERT_TRUE(res1);
  17227. EXPECT_EQ("via-proxy", res1->body);
  17228. EXPECT_EQ(1, proxy_hits.load());
  17229. EXPECT_EQ(0, target_hits.load());
  17230. cli.set_no_proxy({"public.example"});
  17231. auto res2 = cli.Get("/b");
  17232. ASSERT_TRUE(res2);
  17233. EXPECT_EQ("direct", res2->body);
  17234. EXPECT_EQ(1, proxy_hits.load());
  17235. EXPECT_EQ(1, target_hits.load());
  17236. }
  17237. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  17238. namespace proxy_tunnel_test {
  17239. // SSLServer counterpart to no_proxy_test::ScopedServer.
  17240. class ScopedSSLServer {
  17241. public:
  17242. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  17243. port_ = svr_.bind_to_any_port("127.0.0.1");
  17244. }
  17245. ~ScopedSSLServer() {
  17246. svr_.stop();
  17247. if (th_.joinable()) { th_.join(); }
  17248. }
  17249. SSLServer &svr() { return svr_; }
  17250. int port() const { return port_; }
  17251. void listen() {
  17252. th_ = std::thread([this] { svr_.listen_after_bind(); });
  17253. svr_.wait_until_ready();
  17254. }
  17255. private:
  17256. SSLServer svr_;
  17257. std::thread th_;
  17258. int port_ = 0;
  17259. };
  17260. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  17261. class ScopedConnectProxy {
  17262. public:
  17263. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  17264. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  17265. if (listen_fd_ < 0) { return; }
  17266. int yes = 1;
  17267. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  17268. sockaddr_in a{};
  17269. a.sin_family = AF_INET;
  17270. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  17271. a.sin_port = 0;
  17272. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  17273. return;
  17274. }
  17275. socklen_t alen = sizeof(a);
  17276. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  17277. 0) {
  17278. return;
  17279. }
  17280. port_ = ntohs(a.sin_port);
  17281. if (::listen(listen_fd_, 1) != 0) { return; }
  17282. th_ = std::thread([this] { run(); });
  17283. }
  17284. ~ScopedConnectProxy() {
  17285. stop_ = true;
  17286. if (listen_fd_ >= 0) {
  17287. ::shutdown(listen_fd_, SHUT_RDWR);
  17288. ::close(listen_fd_);
  17289. }
  17290. if (th_.joinable()) { th_.join(); }
  17291. }
  17292. int port() const { return port_; }
  17293. int connect_hits() const { return connect_hits_.load(); }
  17294. private:
  17295. void run() {
  17296. while (!stop_.load()) {
  17297. fd_set rfds;
  17298. FD_ZERO(&rfds);
  17299. FD_SET(listen_fd_, &rfds);
  17300. timeval tv{0, 100 * 1000};
  17301. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  17302. if (sel <= 0) { continue; }
  17303. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  17304. if (client_fd < 0) { continue; }
  17305. std::string req;
  17306. char buf[2048];
  17307. while (req.find("\r\n\r\n") == std::string::npos) {
  17308. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  17309. if (n <= 0) { break; }
  17310. req.append(buf, static_cast<size_t>(n));
  17311. }
  17312. if (req.compare(0, 7, "CONNECT") != 0) {
  17313. ::close(client_fd);
  17314. continue;
  17315. }
  17316. connect_hits_++;
  17317. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  17318. ::send(client_fd, ok, std::strlen(ok), 0);
  17319. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  17320. sockaddr_in o{};
  17321. o.sin_family = AF_INET;
  17322. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  17323. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  17324. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  17325. 0) {
  17326. ::close(client_fd);
  17327. ::close(origin_fd);
  17328. continue;
  17329. }
  17330. auto forward = [](int from, int to) {
  17331. char b[8192];
  17332. for (;;) {
  17333. ssize_t n = ::recv(from, b, sizeof(b), 0);
  17334. if (n <= 0) { break; }
  17335. ssize_t off = 0;
  17336. while (off < n) {
  17337. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  17338. if (s <= 0) {
  17339. off = n;
  17340. break;
  17341. }
  17342. off += s;
  17343. }
  17344. }
  17345. ::shutdown(to, SHUT_WR);
  17346. };
  17347. std::thread t1([&] { forward(client_fd, origin_fd); });
  17348. std::thread t2([&] { forward(origin_fd, client_fd); });
  17349. t1.join();
  17350. t2.join();
  17351. ::close(client_fd);
  17352. ::close(origin_fd);
  17353. }
  17354. }
  17355. int forward_port_ = -1;
  17356. int listen_fd_ = -1;
  17357. int port_ = 0;
  17358. std::thread th_;
  17359. std::atomic<bool> stop_{false};
  17360. std::atomic<int> connect_hits_{0};
  17361. };
  17362. } // namespace proxy_tunnel_test
  17363. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  17364. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  17365. // retry; otherwise proxy creds would be sent to the origin.
  17366. std::atomic<int> origin_hits{0};
  17367. std::atomic<bool> origin_saw_proxy_authz{false};
  17368. proxy_tunnel_test::ScopedSSLServer origin;
  17369. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  17370. origin_hits++;
  17371. if (req.has_header("Proxy-Authorization")) {
  17372. origin_saw_proxy_authz = true;
  17373. }
  17374. res.status = StatusCode::ProxyAuthenticationRequired_407;
  17375. res.set_header("Proxy-Authenticate",
  17376. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  17377. "algorithm=MD5");
  17378. });
  17379. origin.listen();
  17380. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  17381. ASSERT_NE(0, proxy.port());
  17382. SSLClient cli(HOST, origin.port());
  17383. cli.enable_server_certificate_verification(false);
  17384. cli.set_proxy(HOST, proxy.port());
  17385. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  17386. auto res = cli.Get("/x");
  17387. ASSERT_TRUE(res);
  17388. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  17389. EXPECT_EQ(1, origin_hits.load());
  17390. EXPECT_FALSE(origin_saw_proxy_authz.load());
  17391. EXPECT_EQ(1, proxy.connect_hits());
  17392. }
  17393. #endif