test.cc 645 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814
  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
  11535. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  11536. std::stringstream body;
  11537. body << "--simpleboundary\r\n"
  11538. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  11539. for (int i = 0; i < 101; i++) {
  11540. body << "X-Custom-Header-" << i << ": value\r\n";
  11541. }
  11542. body << "\r\n"
  11543. << "value1\r\n"
  11544. << "--simpleboundary--\r\n";
  11545. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  11546. Client cli(HOST, PORT);
  11547. auto res = cli.Post("/post", body.str(), content_type.c_str());
  11548. ASSERT_TRUE(res);
  11549. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  11550. }
  11551. TEST(MakeFileBodyTest, Basic) {
  11552. const std::string file_content(4096, 'Z');
  11553. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  11554. {
  11555. std::ofstream ofs(tmp_path, std::ios::binary);
  11556. ofs.write(file_content.data(),
  11557. static_cast<std::streamsize>(file_content.size()));
  11558. }
  11559. auto handled = false;
  11560. Server svr;
  11561. svr.Post("/upload", [&](const Request &req, Response &res) {
  11562. EXPECT_EQ(file_content, req.body);
  11563. handled = true;
  11564. res.status = StatusCode::OK_200;
  11565. });
  11566. auto port = svr.bind_to_any_port(HOST);
  11567. auto t = thread([&] { svr.listen_after_bind(); });
  11568. auto se = detail::scope_exit([&] {
  11569. svr.stop();
  11570. t.join();
  11571. ASSERT_FALSE(svr.is_running());
  11572. ASSERT_TRUE(handled);
  11573. std::remove(tmp_path.c_str());
  11574. });
  11575. svr.wait_until_ready();
  11576. auto fb = make_file_body(tmp_path);
  11577. ASSERT_GT(fb.first, 0u);
  11578. Client cli(HOST, port);
  11579. auto res =
  11580. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  11581. ASSERT_TRUE(res);
  11582. EXPECT_EQ(StatusCode::OK_200, res->status);
  11583. }
  11584. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  11585. static constexpr unsigned int number_of_tasks{1000000};
  11586. std::atomic_uint count{0};
  11587. std::unique_ptr<TaskQueue> task_queue{
  11588. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  11589. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  11590. auto queued = task_queue->enqueue(
  11591. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  11592. EXPECT_TRUE(queued);
  11593. }
  11594. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  11595. task_queue->shutdown();
  11596. #else
  11597. EXPECT_NO_THROW(task_queue->shutdown());
  11598. #endif
  11599. EXPECT_EQ(number_of_tasks, count.load());
  11600. }
  11601. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  11602. static constexpr unsigned int number_of_tasks{1000000};
  11603. static constexpr unsigned int qlimit{2};
  11604. unsigned int queued_count{0};
  11605. std::atomic_uint count{0};
  11606. std::unique_ptr<TaskQueue> task_queue{
  11607. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  11608. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  11609. if (task_queue->enqueue(
  11610. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  11611. queued_count++;
  11612. }
  11613. }
  11614. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  11615. task_queue->shutdown();
  11616. #else
  11617. EXPECT_NO_THROW(task_queue->shutdown());
  11618. #endif
  11619. EXPECT_EQ(queued_count, count.load());
  11620. EXPECT_TRUE(queued_count <= number_of_tasks);
  11621. EXPECT_TRUE(queued_count >= qlimit);
  11622. }
  11623. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  11624. // Use a short idle timeout so a dynamic thread spawns, times out and
  11625. // exits during the test, and the pool keeps working afterwards.
  11626. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  11627. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  11628. /*idle_timeout_sec=*/1}};
  11629. std::atomic_uint count{0};
  11630. std::condition_variable cv;
  11631. std::mutex mtx;
  11632. bool release = false;
  11633. // Block the base thread so the second task spawns a dynamic thread.
  11634. EXPECT_TRUE(task_queue->enqueue([&] {
  11635. std::unique_lock<std::mutex> lock(mtx);
  11636. while (!release) {
  11637. cv.wait(lock);
  11638. }
  11639. count++;
  11640. }));
  11641. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  11642. // Let the dynamic thread finish its task and exceed the idle timeout.
  11643. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  11644. {
  11645. std::unique_lock<std::mutex> lock(mtx);
  11646. release = true;
  11647. }
  11648. cv.notify_all();
  11649. // The pool must still accept and run tasks after the dynamic thread exited.
  11650. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  11651. task_queue->shutdown();
  11652. EXPECT_EQ(3u, count.load());
  11653. }
  11654. TEST(TaskQueueTest, MaxQueuedRequests) {
  11655. static constexpr unsigned int qlimit{3};
  11656. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  11657. std::condition_variable sem_cv;
  11658. std::mutex sem_mtx;
  11659. int credits = 0;
  11660. bool queued;
  11661. /* Fill up the queue with tasks that will block until we give them credits to
  11662. * complete. */
  11663. for (unsigned int n = 0; n <= qlimit;) {
  11664. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  11665. std::unique_lock<std::mutex> lock(sem_mtx);
  11666. while (credits <= 0) {
  11667. sem_cv.wait(lock);
  11668. }
  11669. /* Consume the credit and signal the test code if they are all gone. */
  11670. if (--credits == 0) { sem_cv.notify_one(); }
  11671. });
  11672. if (n < qlimit) {
  11673. /* The first qlimit enqueues must succeed. */
  11674. EXPECT_TRUE(queued);
  11675. } else {
  11676. /* The last one will succeed only when the worker thread
  11677. * starts and dequeues the first blocking task. Although
  11678. * not necessary for the correctness of this test, we sleep for
  11679. * a short while to avoid busy waiting. */
  11680. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  11681. }
  11682. if (queued) { n++; }
  11683. }
  11684. /* Further enqueues must fail since the queue is full. */
  11685. for (auto i = 0; i < 4; i++) {
  11686. queued = task_queue->enqueue([] {});
  11687. EXPECT_FALSE(queued);
  11688. }
  11689. /* Give the credits to allow the previous tasks to complete. */
  11690. {
  11691. std::unique_lock<std::mutex> lock(sem_mtx);
  11692. credits += qlimit + 1;
  11693. }
  11694. sem_cv.notify_all();
  11695. /* Wait for all the credits to be consumed. */
  11696. {
  11697. std::unique_lock<std::mutex> lock(sem_mtx);
  11698. while (credits > 0) {
  11699. sem_cv.wait(lock);
  11700. }
  11701. }
  11702. /* Check that we are able again to enqueue at least qlimit tasks. */
  11703. for (unsigned int i = 0; i < qlimit; i++) {
  11704. queued = task_queue->enqueue([] {});
  11705. EXPECT_TRUE(queued);
  11706. }
  11707. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  11708. task_queue->shutdown();
  11709. #else
  11710. EXPECT_NO_THROW(task_queue->shutdown());
  11711. #endif
  11712. }
  11713. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  11714. Server svr;
  11715. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11716. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  11717. });
  11718. svr.Get("/hello", [](const Request &req, Response &res) {
  11719. res.set_content(req.get_param_value("key"), "text/plain");
  11720. });
  11721. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11722. auto se = detail::scope_exit([&] {
  11723. svr.stop();
  11724. thread.join();
  11725. ASSERT_FALSE(svr.is_running());
  11726. });
  11727. svr.wait_until_ready();
  11728. {
  11729. Client cli(HOST, PORT);
  11730. cli.set_follow_location(true);
  11731. auto res = cli.Get("/");
  11732. ASSERT_TRUE(res);
  11733. EXPECT_EQ(StatusCode::OK_200, res->status);
  11734. EXPECT_EQ("val&key2=val2", res->body);
  11735. }
  11736. }
  11737. #endif
  11738. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  11739. Server svr;
  11740. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11741. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  11742. });
  11743. svr.Get("/hello", [](const Request &req, Response &res) {
  11744. res.set_content(req.get_param_value("key"), "text/plain");
  11745. });
  11746. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11747. auto se = detail::scope_exit([&] {
  11748. svr.stop();
  11749. thread.join();
  11750. ASSERT_FALSE(svr.is_running());
  11751. });
  11752. svr.wait_until_ready();
  11753. {
  11754. Client cli(HOST, PORT);
  11755. cli.set_follow_location(true);
  11756. auto res = cli.Get("/");
  11757. ASSERT_TRUE(res);
  11758. EXPECT_EQ(StatusCode::OK_200, res->status);
  11759. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  11760. }
  11761. }
  11762. TEST(RedirectTest, RedirectWithPlusInPath) {
  11763. Server svr;
  11764. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11765. res.set_redirect("/a+b");
  11766. });
  11767. // Route pattern uses regex; escape + as \\+
  11768. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  11769. res.set_content(req.path, "text/plain");
  11770. });
  11771. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11772. auto se = detail::scope_exit([&] {
  11773. svr.stop();
  11774. thread.join();
  11775. ASSERT_FALSE(svr.is_running());
  11776. });
  11777. svr.wait_until_ready();
  11778. {
  11779. Client cli(HOST, PORT);
  11780. cli.set_follow_location(true);
  11781. auto res = cli.Get("/");
  11782. ASSERT_TRUE(res);
  11783. EXPECT_EQ(StatusCode::OK_200, res->status);
  11784. EXPECT_EQ("/a+b", res->body);
  11785. }
  11786. }
  11787. #ifdef CPPHTTPLIB_SSL_ENABLED
  11788. TEST(RedirectTest, Issue2185_Online) {
  11789. SSLClient client("github.com");
  11790. client.set_follow_location(true);
  11791. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  11792. "Coollab-Windows.zip");
  11793. ASSERT_TRUE(res);
  11794. EXPECT_EQ(StatusCode::OK_200, res->status);
  11795. EXPECT_EQ(9920427U, res->body.size());
  11796. }
  11797. #endif
  11798. TEST(VulnerabilityTest, CRLFInjection) {
  11799. Server svr;
  11800. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  11801. res.set_content("Hello 1", "text/plain");
  11802. });
  11803. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  11804. res.set_content("Hello 2", "text/plain");
  11805. });
  11806. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  11807. res.set_content("Hello 3", "text/plain");
  11808. });
  11809. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  11810. res.set_content("Hello 4", "text/plain");
  11811. });
  11812. svr.set_logger([](const Request &req, const Response & /*res*/) {
  11813. for (const auto &x : req.headers) {
  11814. auto key = x.first;
  11815. EXPECT_STRNE("evil", key.c_str());
  11816. }
  11817. });
  11818. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11819. auto se = detail::scope_exit([&] {
  11820. svr.stop();
  11821. thread.join();
  11822. ASSERT_FALSE(svr.is_running());
  11823. });
  11824. svr.wait_until_ready();
  11825. {
  11826. Client cli(HOST, PORT);
  11827. cli.Post("/test1", "A=B",
  11828. "application/x-www-form-urlencoded\r\nevil: hello1");
  11829. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  11830. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  11831. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  11832. }
  11833. }
  11834. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  11835. auto server_thread = std::thread([] {
  11836. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11837. default_socket_options(srv);
  11838. sockaddr_in addr{};
  11839. addr.sin_family = AF_INET;
  11840. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  11841. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11842. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11843. ::listen(srv, 1);
  11844. sockaddr_in cli_addr{};
  11845. socklen_t cli_len = sizeof(cli_addr);
  11846. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11847. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  11848. std::string buf_all;
  11849. char buf[2048];
  11850. ssize_t n;
  11851. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  11852. buf_all.append(buf, static_cast<size_t>(n));
  11853. size_t pos;
  11854. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  11855. auto request_block = buf_all.substr(0, pos + 4); // include separator
  11856. auto e = request_block.find("\r\n");
  11857. if (e != std::string::npos) {
  11858. auto request_line = request_block.substr(0, e);
  11859. std::string msg =
  11860. "CRLF injection detected in request line: '" + request_line + "'";
  11861. EXPECT_FALSE(true) << msg;
  11862. }
  11863. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  11864. ::send(cli,
  11865. #ifdef _WIN32
  11866. static_cast<const char *>(resp.c_str()),
  11867. static_cast<int>(resp.size()),
  11868. #else
  11869. resp.c_str(), resp.size(),
  11870. #endif
  11871. 0);
  11872. buf_all.erase(0, pos + 4);
  11873. }
  11874. }
  11875. detail::close_socket(cli);
  11876. detail::close_socket(srv);
  11877. });
  11878. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11879. auto cli = Client("127.0.0.1", PORT + 1);
  11880. auto headers = Headers{
  11881. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  11882. {"Connection", "keep-alive"}};
  11883. auto res = cli.Get("/hi", headers);
  11884. EXPECT_FALSE(res);
  11885. EXPECT_EQ(Error::InvalidHeaders, res.error());
  11886. server_thread.join();
  11887. }
  11888. TEST(PathParamsTest, StaticMatch) {
  11889. const auto pattern = "/users/all";
  11890. detail::PathParamsMatcher matcher(pattern);
  11891. Request request;
  11892. request.path = "/users/all";
  11893. ASSERT_TRUE(matcher.match(request));
  11894. std::unordered_map<std::string, std::string> expected_params = {};
  11895. EXPECT_EQ(request.path_params, expected_params);
  11896. }
  11897. TEST(PathParamsTest, StaticMismatch) {
  11898. const auto pattern = "/users/all";
  11899. detail::PathParamsMatcher matcher(pattern);
  11900. Request request;
  11901. request.path = "/users/1";
  11902. ASSERT_FALSE(matcher.match(request));
  11903. }
  11904. TEST(PathParamsTest, SingleParamInTheMiddle) {
  11905. const auto pattern = "/users/:id/subscriptions";
  11906. detail::PathParamsMatcher matcher(pattern);
  11907. Request request;
  11908. request.path = "/users/42/subscriptions";
  11909. ASSERT_TRUE(matcher.match(request));
  11910. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  11911. EXPECT_EQ(request.path_params, expected_params);
  11912. }
  11913. TEST(PathParamsTest, SingleParamInTheEnd) {
  11914. const auto pattern = "/users/:id";
  11915. detail::PathParamsMatcher matcher(pattern);
  11916. Request request;
  11917. request.path = "/users/24";
  11918. ASSERT_TRUE(matcher.match(request));
  11919. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  11920. EXPECT_EQ(request.path_params, expected_params);
  11921. }
  11922. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  11923. const auto pattern = "/users/:id/";
  11924. detail::PathParamsMatcher matcher(pattern);
  11925. Request request;
  11926. request.path = "/users/42/";
  11927. ASSERT_TRUE(matcher.match(request));
  11928. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  11929. EXPECT_EQ(request.path_params, expected_params);
  11930. }
  11931. TEST(PathParamsTest, EmptyParam) {
  11932. const auto pattern = "/users/:id/";
  11933. detail::PathParamsMatcher matcher(pattern);
  11934. Request request;
  11935. request.path = "/users//";
  11936. ASSERT_TRUE(matcher.match(request));
  11937. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  11938. EXPECT_EQ(request.path_params, expected_params);
  11939. }
  11940. TEST(PathParamsTest, FragmentMismatch) {
  11941. const auto pattern = "/users/:id/";
  11942. detail::PathParamsMatcher matcher(pattern);
  11943. Request request;
  11944. request.path = "/admins/24/";
  11945. ASSERT_FALSE(matcher.match(request));
  11946. }
  11947. TEST(PathParamsTest, ExtraFragments) {
  11948. const auto pattern = "/users/:id";
  11949. detail::PathParamsMatcher matcher(pattern);
  11950. Request request;
  11951. request.path = "/users/42/subscriptions";
  11952. ASSERT_FALSE(matcher.match(request));
  11953. }
  11954. TEST(PathParamsTest, MissingTrailingParam) {
  11955. const auto pattern = "/users/:id";
  11956. detail::PathParamsMatcher matcher(pattern);
  11957. Request request;
  11958. request.path = "/users";
  11959. ASSERT_FALSE(matcher.match(request));
  11960. }
  11961. TEST(PathParamsTest, MissingParamInTheMiddle) {
  11962. const auto pattern = "/users/:id/subscriptions";
  11963. detail::PathParamsMatcher matcher(pattern);
  11964. Request request;
  11965. request.path = "/users/subscriptions";
  11966. ASSERT_FALSE(matcher.match(request));
  11967. }
  11968. TEST(PathParamsTest, MultipleParams) {
  11969. const auto pattern = "/users/:userid/subscriptions/:subid";
  11970. detail::PathParamsMatcher matcher(pattern);
  11971. Request request;
  11972. request.path = "/users/42/subscriptions/2";
  11973. ASSERT_TRUE(matcher.match(request));
  11974. std::unordered_map<std::string, std::string> expected_params = {
  11975. {"userid", "42"}, {"subid", "2"}};
  11976. EXPECT_EQ(request.path_params, expected_params);
  11977. }
  11978. TEST(PathParamsTest, SequenceOfParams) {
  11979. const auto pattern = "/values/:x/:y/:z";
  11980. detail::PathParamsMatcher matcher(pattern);
  11981. Request request;
  11982. request.path = "/values/1/2/3";
  11983. ASSERT_TRUE(matcher.match(request));
  11984. std::unordered_map<std::string, std::string> expected_params = {
  11985. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  11986. EXPECT_EQ(request.path_params, expected_params);
  11987. }
  11988. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  11989. const auto pattern = "/prefix:suffix";
  11990. detail::PathParamsMatcher matcher(pattern);
  11991. Request request;
  11992. request.path = "/prefix:suffix";
  11993. ASSERT_TRUE(matcher.match(request));
  11994. const std::unordered_map<std::string, std::string> expected_params = {};
  11995. EXPECT_EQ(request.path_params, expected_params);
  11996. }
  11997. TEST(ParseUrlTest, VariousPatterns) {
  11998. {
  11999. detail::UrlComponents uc;
  12000. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  12001. EXPECT_EQ("http", uc.scheme);
  12002. EXPECT_EQ("example.com", uc.host);
  12003. EXPECT_EQ("8080", uc.port);
  12004. EXPECT_EQ("/path", uc.path);
  12005. EXPECT_EQ("?q=1", uc.query);
  12006. }
  12007. {
  12008. detail::UrlComponents uc;
  12009. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  12010. EXPECT_EQ("https", uc.scheme);
  12011. EXPECT_EQ("example.com", uc.host);
  12012. EXPECT_TRUE(uc.port.empty());
  12013. EXPECT_EQ("/path", uc.path);
  12014. }
  12015. {
  12016. detail::UrlComponents uc;
  12017. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  12018. EXPECT_EQ("::1", uc.host);
  12019. EXPECT_EQ("8080", uc.port);
  12020. EXPECT_EQ("/path", uc.path);
  12021. }
  12022. {
  12023. detail::UrlComponents uc;
  12024. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  12025. }
  12026. {
  12027. detail::UrlComponents uc;
  12028. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  12029. EXPECT_TRUE(uc.scheme.empty());
  12030. EXPECT_EQ("example.com", uc.host);
  12031. EXPECT_EQ("/path", uc.path);
  12032. EXPECT_EQ("?q=1", uc.query);
  12033. }
  12034. {
  12035. detail::UrlComponents uc;
  12036. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  12037. EXPECT_TRUE(uc.host.empty());
  12038. EXPECT_EQ("/path", uc.path);
  12039. EXPECT_EQ("?q=1", uc.query);
  12040. }
  12041. {
  12042. detail::UrlComponents uc;
  12043. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  12044. EXPECT_EQ("example.com", uc.host);
  12045. EXPECT_EQ("8080", uc.port);
  12046. }
  12047. {
  12048. // Unix socket path — must not be parsed as host
  12049. detail::UrlComponents uc;
  12050. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  12051. EXPECT_TRUE(uc.host.empty());
  12052. }
  12053. {
  12054. detail::UrlComponents uc;
  12055. ASSERT_TRUE(detail::parse_url("", uc));
  12056. EXPECT_TRUE(uc.host.empty());
  12057. EXPECT_TRUE(uc.path.empty());
  12058. }
  12059. {
  12060. detail::UrlComponents uc;
  12061. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  12062. }
  12063. {
  12064. detail::UrlComponents uc;
  12065. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  12066. }
  12067. {
  12068. // Accepted by parse_url; callers restrict to http/https
  12069. detail::UrlComponents uc;
  12070. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  12071. EXPECT_EQ("ftp", uc.scheme);
  12072. }
  12073. {
  12074. detail::UrlComponents uc;
  12075. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  12076. }
  12077. {
  12078. detail::UrlComponents uc;
  12079. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  12080. }
  12081. }
  12082. TEST(ParseUrlTest, FragmentHandling) {
  12083. {
  12084. detail::UrlComponents uc;
  12085. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  12086. EXPECT_EQ("/path", uc.path);
  12087. EXPECT_TRUE(uc.query.empty());
  12088. }
  12089. {
  12090. detail::UrlComponents uc;
  12091. ASSERT_TRUE(detail::parse_url("#frag", uc));
  12092. EXPECT_TRUE(uc.path.empty());
  12093. EXPECT_TRUE(uc.query.empty());
  12094. }
  12095. }
  12096. TEST(ParseUrlTest, UserinfoHandling) {
  12097. // Userinfo with @ but no colon — host includes @
  12098. detail::UrlComponents uc;
  12099. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  12100. EXPECT_EQ("user@host.com", uc.host);
  12101. EXPECT_EQ("/path", uc.path);
  12102. }
  12103. TEST(ParseUrlTest, IPv6EdgeCases) {
  12104. {
  12105. detail::UrlComponents uc;
  12106. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  12107. EXPECT_TRUE(uc.scheme.empty());
  12108. EXPECT_EQ("::1", uc.host);
  12109. EXPECT_EQ("8080", uc.port);
  12110. }
  12111. {
  12112. // Zone ID '%25' is not in [a-fA-F0-9:]
  12113. detail::UrlComponents uc;
  12114. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  12115. }
  12116. }
  12117. TEST(ParseUrlTest, SchemeEdgeCases) {
  12118. {
  12119. detail::UrlComponents uc;
  12120. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  12121. }
  12122. {
  12123. detail::UrlComponents uc;
  12124. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  12125. }
  12126. {
  12127. detail::UrlComponents uc;
  12128. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  12129. }
  12130. }
  12131. TEST(ParseUrlTest, PortEdgeCases) {
  12132. {
  12133. detail::UrlComponents uc;
  12134. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  12135. EXPECT_TRUE(uc.port.empty());
  12136. EXPECT_EQ("/path", uc.path);
  12137. }
  12138. {
  12139. // parse_url accepts any port string; validation is done by parse_port
  12140. detail::UrlComponents uc;
  12141. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  12142. EXPECT_EQ("abc", uc.port);
  12143. }
  12144. }
  12145. TEST(ParseUrlTest, WebSocketPatterns) {
  12146. {
  12147. detail::UrlComponents uc;
  12148. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  12149. EXPECT_EQ("ws", uc.scheme);
  12150. EXPECT_EQ("echo.example.com", uc.host);
  12151. EXPECT_EQ("8080", uc.port);
  12152. EXPECT_EQ("/ws", uc.path);
  12153. }
  12154. {
  12155. detail::UrlComponents uc;
  12156. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  12157. EXPECT_EQ("wss", uc.scheme);
  12158. EXPECT_EQ("echo.example.com", uc.host);
  12159. EXPECT_TRUE(uc.port.empty());
  12160. EXPECT_EQ("/ws", uc.path);
  12161. }
  12162. }
  12163. TEST(ParseUrlTest, QueryOnly) {
  12164. detail::UrlComponents uc;
  12165. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  12166. EXPECT_TRUE(uc.host.empty());
  12167. EXPECT_TRUE(uc.path.empty());
  12168. EXPECT_EQ("?q=1&r=2", uc.query);
  12169. }
  12170. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  12171. detail::UrlComponents uc;
  12172. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  12173. EXPECT_TRUE(uc.scheme.empty());
  12174. EXPECT_EQ("example.com", uc.host);
  12175. EXPECT_EQ("443", uc.port);
  12176. EXPECT_EQ("/path", uc.path);
  12177. }
  12178. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  12179. // If ipv6 regex working, regex match codepath is taken.
  12180. // else port will default to 80 in Client impl
  12181. int clientImplMagicPort = 80;
  12182. int port = 4321;
  12183. // above ports must be different to avoid false negative
  12184. EXPECT_NE(clientImplMagicPort, port);
  12185. std::string ipV6TestURL = "http://[ff06::c3]";
  12186. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  12187. CLIENT_PRIVATE_KEY_FILE);
  12188. EXPECT_EQ(cli.port(), port);
  12189. }
  12190. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  12191. auto file_path = "./www/dir/index.html";
  12192. auto dir_path = "./www/dir";
  12193. detail::FileStat stat_file(file_path);
  12194. EXPECT_TRUE(stat_file.is_file());
  12195. EXPECT_FALSE(stat_file.is_dir());
  12196. detail::FileStat stat_dir(dir_path);
  12197. EXPECT_FALSE(stat_dir.is_file());
  12198. EXPECT_TRUE(stat_dir.is_dir());
  12199. }
  12200. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  12201. // IPv4 with default HTTP port (80)
  12202. EXPECT_EQ("example.com",
  12203. detail::make_host_and_port_string("example.com", 80, false));
  12204. // IPv4 with default HTTPS port (443)
  12205. EXPECT_EQ("example.com",
  12206. detail::make_host_and_port_string("example.com", 443, true));
  12207. // IPv4 with non-default HTTP port
  12208. EXPECT_EQ("example.com:8080",
  12209. detail::make_host_and_port_string("example.com", 8080, false));
  12210. // IPv4 with non-default HTTPS port
  12211. EXPECT_EQ("example.com:8443",
  12212. detail::make_host_and_port_string("example.com", 8443, true));
  12213. // IPv6 with default HTTP port (80)
  12214. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  12215. // IPv6 with default HTTPS port (443)
  12216. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  12217. // IPv6 with non-default HTTP port
  12218. EXPECT_EQ("[::1]:8080",
  12219. detail::make_host_and_port_string("::1", 8080, false));
  12220. // IPv6 with non-default HTTPS port
  12221. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  12222. // IPv6 full address with default port
  12223. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  12224. detail::make_host_and_port_string(
  12225. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  12226. // IPv6 full address with non-default port
  12227. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  12228. detail::make_host_and_port_string(
  12229. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  12230. // IPv6 localhost with non-default port
  12231. EXPECT_EQ("[::1]:3000",
  12232. detail::make_host_and_port_string("::1", 3000, false));
  12233. // IPv6 with zone ID (link-local address) with default port
  12234. EXPECT_EQ("[fe80::1%eth0]",
  12235. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  12236. // IPv6 with zone ID (link-local address) with non-default port
  12237. EXPECT_EQ("[fe80::1%eth0]:8080",
  12238. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  12239. // Edge case: Port 443 with is_ssl=false (should add port)
  12240. EXPECT_EQ("example.com:443",
  12241. detail::make_host_and_port_string("example.com", 443, false));
  12242. // Edge case: Port 80 with is_ssl=true (should add port)
  12243. EXPECT_EQ("example.com:80",
  12244. detail::make_host_and_port_string("example.com", 80, true));
  12245. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  12246. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  12247. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  12248. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  12249. // Security fix: Already bracketed IPv6 should not get double brackets
  12250. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  12251. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  12252. EXPECT_EQ("[::1]:8080",
  12253. detail::make_host_and_port_string("[::1]", 8080, false));
  12254. EXPECT_EQ("[2001:db8::1]:8080",
  12255. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  12256. EXPECT_EQ("[fe80::1%eth0]",
  12257. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  12258. EXPECT_EQ("[fe80::1%eth0]:8080",
  12259. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  12260. // Edge case: Empty host (should return as-is)
  12261. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  12262. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  12263. // This is a known limitation but shouldn't crash
  12264. EXPECT_EQ("[host:name]",
  12265. detail::make_host_and_port_string("host:name", 80, false));
  12266. // Port number edge cases (no validation, but should not crash)
  12267. EXPECT_EQ("example.com:0",
  12268. detail::make_host_and_port_string("example.com", 0, false));
  12269. EXPECT_EQ("example.com:-1",
  12270. detail::make_host_and_port_string("example.com", -1, false));
  12271. EXPECT_EQ("example.com:65535",
  12272. detail::make_host_and_port_string("example.com", 65535, false));
  12273. EXPECT_EQ("example.com:65536",
  12274. detail::make_host_and_port_string("example.com", 65536, false));
  12275. }
  12276. #ifdef CPPHTTPLIB_SSL_ENABLED
  12277. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  12278. httplib::SSLClient cli("roblox.com", 443);
  12279. cli.set_follow_location(true);
  12280. auto res = cli.Get("/");
  12281. ASSERT_TRUE(res);
  12282. EXPECT_EQ(StatusCode::OK_200, res->status);
  12283. }
  12284. #endif
  12285. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  12286. Server svr;
  12287. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  12288. EXPECT_EQ(res.status, 400);
  12289. });
  12290. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12291. auto se = detail::scope_exit([&] {
  12292. svr.stop();
  12293. thread.join();
  12294. ASSERT_FALSE(svr.is_running());
  12295. });
  12296. svr.wait_until_ready();
  12297. Client cli(HOST, PORT);
  12298. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  12299. }
  12300. TEST(InvalidHeaderCharsTest, is_field_name) {
  12301. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  12302. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  12303. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  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("example_token "));
  12307. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  12308. EXPECT_FALSE(detail::fields::is_field_name(""));
  12309. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  12310. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  12311. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  12312. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  12313. }
  12314. TEST(InvalidHeaderCharsTest, is_field_value) {
  12315. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  12316. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  12317. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  12318. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  12319. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  12320. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  12321. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  12322. EXPECT_TRUE(detail::fields::is_field_value(""));
  12323. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  12324. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  12325. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  12326. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  12327. EXPECT_TRUE(detail::fields::is_field_value("0"));
  12328. }
  12329. TEST(InvalidHeaderCharsTest, OnServer) {
  12330. Server svr;
  12331. svr.Get("/test_name", [&](const Request &req, Response &res) {
  12332. std::string header = "Not Set";
  12333. if (req.has_param("header")) { header = req.get_param_value("header"); }
  12334. res.set_header(header, "value");
  12335. res.set_content("Page Content Page Content", "text/plain");
  12336. });
  12337. svr.Get("/test_value", [&](const Request &req, Response &res) {
  12338. std::string header = "Not Set";
  12339. if (req.has_param("header")) { header = req.get_param_value("header"); }
  12340. res.set_header("X-Test", header);
  12341. res.set_content("Page Content Page Content", "text/plain");
  12342. });
  12343. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12344. auto se = detail::scope_exit([&] {
  12345. svr.stop();
  12346. thread.join();
  12347. ASSERT_FALSE(svr.is_running());
  12348. });
  12349. svr.wait_until_ready();
  12350. Client cli(HOST, PORT);
  12351. {
  12352. auto res = cli.Get(
  12353. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  12354. ASSERT_TRUE(res);
  12355. EXPECT_EQ("Page Content Page Content", res->body);
  12356. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  12357. }
  12358. {
  12359. auto res = cli.Get(
  12360. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  12361. ASSERT_TRUE(res);
  12362. EXPECT_EQ("Page Content Page Content", res->body);
  12363. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  12364. }
  12365. }
  12366. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  12367. auto handled = false;
  12368. Server svr;
  12369. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  12370. thread t = thread([&] { svr.listen(HOST, PORT); });
  12371. auto se = detail::scope_exit([&] {
  12372. svr.stop();
  12373. t.join();
  12374. ASSERT_FALSE(svr.is_running());
  12375. ASSERT_FALSE(handled);
  12376. });
  12377. svr.wait_until_ready();
  12378. auto req = "POST /test HTTP/1.1\r\n"
  12379. "Content-Length: x\r\n"
  12380. "\r\n";
  12381. std::string response;
  12382. ASSERT_TRUE(send_request(1, req, &response));
  12383. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  12384. response.substr(0, response.find("\r\n")));
  12385. }
  12386. #ifndef _WIN32
  12387. TEST(Expect100ContinueTest, ServerClosesConnection) {
  12388. static constexpr char reject[] = "Unauthorized";
  12389. static constexpr char accept[] = "Upload accepted";
  12390. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  12391. Server svr;
  12392. svr.set_expect_100_continue_handler(
  12393. [](const Request & /*req*/, Response &res) {
  12394. res.status = StatusCode::Unauthorized_401;
  12395. res.set_content(reject, "text/plain");
  12396. return res.status;
  12397. });
  12398. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  12399. res.set_content(accept, "text/plain");
  12400. });
  12401. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12402. auto se = detail::scope_exit([&] {
  12403. svr.stop();
  12404. thread.join();
  12405. ASSERT_FALSE(svr.is_running());
  12406. });
  12407. svr.wait_until_ready();
  12408. {
  12409. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  12410. curl_easy_init(), &curl_easy_cleanup};
  12411. ASSERT_NE(curl, nullptr);
  12412. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  12413. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  12414. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  12415. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  12416. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  12417. &curl_slist_free_all};
  12418. ASSERT_NE(list, nullptr);
  12419. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  12420. struct read_data {
  12421. size_t read_size;
  12422. size_t total_size;
  12423. } data = {0, total_size};
  12424. using read_callback_t =
  12425. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  12426. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  12427. void *userdata) -> size_t {
  12428. read_data *d = (read_data *)userdata;
  12429. if (!userdata || d->read_size >= d->total_size) { return 0; }
  12430. std::fill_n(ptr, size * nmemb, 'A');
  12431. d->read_size += size * nmemb;
  12432. return size * nmemb;
  12433. };
  12434. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  12435. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  12436. std::vector<char> buffer;
  12437. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  12438. using write_callback_t =
  12439. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  12440. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  12441. void *userdata) -> size_t {
  12442. std::vector<char> *buf = (std::vector<char> *)userdata;
  12443. buf->reserve(buf->size() + size * nmemb + 1);
  12444. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  12445. return size * nmemb;
  12446. };
  12447. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  12448. {
  12449. const auto res = curl_easy_perform(curl.get());
  12450. ASSERT_EQ(res, CURLE_OK);
  12451. }
  12452. {
  12453. auto response_code = long{};
  12454. const auto res =
  12455. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  12456. ASSERT_EQ(res, CURLE_OK);
  12457. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  12458. }
  12459. {
  12460. auto dl = curl_off_t{};
  12461. const auto res =
  12462. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  12463. ASSERT_EQ(res, CURLE_OK);
  12464. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  12465. }
  12466. {
  12467. buffer.push_back('\0');
  12468. ASSERT_STRCASEEQ(buffer.data(), reject);
  12469. }
  12470. }
  12471. }
  12472. #endif
  12473. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  12474. // Regression test for #2458.
  12475. //
  12476. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  12477. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  12478. // ticket can make the client socket spuriously readable during the
  12479. // 100-continue wait. If the readiness is mistaken for an incoming response,
  12480. // the client withholds the body and then blocks reading a response that never
  12481. // comes, failing with `Failed to read connection`.
  12482. //
  12483. // A correct client (like curl) sends the body once no `100 Continue` arrives
  12484. // within the timeout. This raw OpenSSL server deliberately never sends
  12485. // `100 Continue`; the client must still deliver the body and receive 200.
  12486. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  12487. signal(SIGPIPE, SIG_IGN);
  12488. const auto port = PORT + 4;
  12489. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12490. ASSERT_NE(srv, INVALID_SOCKET);
  12491. int opt = 1;
  12492. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  12493. sockaddr_in addr{};
  12494. addr.sin_family = AF_INET;
  12495. addr.sin_port = htons(static_cast<uint16_t>(port));
  12496. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12497. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  12498. ASSERT_EQ(0, ::listen(srv, 1));
  12499. std::atomic<size_t> server_body_bytes{0};
  12500. auto server_thread = std::thread([&] {
  12501. sockaddr_in cli_addr{};
  12502. socklen_t cli_len = sizeof(cli_addr);
  12503. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12504. if (cli == INVALID_SOCKET) { return; }
  12505. // Bound the lifetime of the server side so a buggy client (which never
  12506. // sends the body) cannot make this thread block forever on join.
  12507. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  12508. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  12509. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  12510. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  12511. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  12512. SSL *ssl = SSL_new(ctx);
  12513. SSL_set_fd(ssl, static_cast<int>(cli));
  12514. if (SSL_accept(ssl) > 0) {
  12515. // Read the request headers. Reading here also flushes the TLS 1.3
  12516. // session tickets to the client. Deliberately do NOT send
  12517. // `100 Continue`.
  12518. std::string buf;
  12519. char tmp[1024];
  12520. while (buf.find("\r\n\r\n") == std::string::npos) {
  12521. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  12522. if (n <= 0) { break; }
  12523. buf.append(tmp, static_cast<size_t>(n));
  12524. }
  12525. // A correct client sends the body now; count what arrives.
  12526. auto pos = buf.find("\r\n\r\n");
  12527. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  12528. while (body < 4096) {
  12529. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  12530. if (n <= 0) { break; }
  12531. body += static_cast<size_t>(n);
  12532. }
  12533. server_body_bytes = body;
  12534. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  12535. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  12536. SSL_shutdown(ssl);
  12537. }
  12538. SSL_free(ssl);
  12539. detail::close_socket(cli);
  12540. SSL_CTX_free(ctx);
  12541. });
  12542. auto se = detail::scope_exit([&] {
  12543. server_thread.join();
  12544. detail::close_socket(srv);
  12545. });
  12546. SSLClient cli("127.0.0.1", port);
  12547. cli.enable_server_certificate_verification(false);
  12548. cli.set_connection_timeout(5, 0);
  12549. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  12550. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  12551. std::string body(4096, 'A');
  12552. auto res = cli.Put("/api/test", body, "application/json");
  12553. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  12554. EXPECT_EQ(StatusCode::OK_200, res->status);
  12555. EXPECT_EQ(body.size(), server_body_bytes.load());
  12556. }
  12557. #endif
  12558. template <typename S, typename C>
  12559. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  12560. svr.Get("/stream", [&](const Request &, Response &res) {
  12561. auto data = new std::string("01234567890123456789");
  12562. res.set_content_provider(
  12563. data->size(), "text/plain",
  12564. [&, data](size_t offset, size_t length, DataSink &sink) {
  12565. const size_t DATA_CHUNK_SIZE = 4;
  12566. const auto &d = *data;
  12567. std::this_thread::sleep_for(std::chrono::seconds(1));
  12568. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  12569. return true;
  12570. },
  12571. [data](bool success) {
  12572. EXPECT_FALSE(success);
  12573. delete data;
  12574. });
  12575. });
  12576. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  12577. auto i = new size_t(0);
  12578. res.set_content_provider(
  12579. "text/plain",
  12580. [i](size_t, DataSink &sink) {
  12581. if (*i < 5) {
  12582. std::this_thread::sleep_for(std::chrono::seconds(1));
  12583. sink.write("abcd", 4);
  12584. (*i)++;
  12585. } else {
  12586. sink.done();
  12587. }
  12588. return true;
  12589. },
  12590. [i](bool success) {
  12591. EXPECT_FALSE(success);
  12592. delete i;
  12593. });
  12594. });
  12595. svr.Get("/chunked", [&](const Request &, Response &res) {
  12596. auto i = new size_t(0);
  12597. res.set_chunked_content_provider(
  12598. "text/plain",
  12599. [i](size_t, DataSink &sink) {
  12600. if (*i < 5) {
  12601. std::this_thread::sleep_for(std::chrono::seconds(1));
  12602. sink.os << "abcd";
  12603. (*i)++;
  12604. } else {
  12605. sink.done();
  12606. }
  12607. return true;
  12608. },
  12609. [i](bool success) {
  12610. EXPECT_FALSE(success);
  12611. delete i;
  12612. });
  12613. });
  12614. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12615. auto se = detail::scope_exit([&] {
  12616. svr.stop();
  12617. listen_thread.join();
  12618. ASSERT_FALSE(svr.is_running());
  12619. });
  12620. svr.wait_until_ready();
  12621. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  12622. {
  12623. auto start = std::chrono::steady_clock::now();
  12624. auto res = cli.Get("/stream");
  12625. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12626. std::chrono::steady_clock::now() - start)
  12627. .count();
  12628. ASSERT_FALSE(res);
  12629. EXPECT_EQ(Error::Read, res.error());
  12630. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  12631. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  12632. }
  12633. {
  12634. auto start = std::chrono::steady_clock::now();
  12635. auto res = cli.Get("/stream_without_length");
  12636. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12637. std::chrono::steady_clock::now() - start)
  12638. .count();
  12639. ASSERT_FALSE(res);
  12640. EXPECT_EQ(Error::Read, res.error());
  12641. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  12642. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  12643. }
  12644. {
  12645. auto start = std::chrono::steady_clock::now();
  12646. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  12647. EXPECT_EQ("abcd", string(data, data_length));
  12648. return true;
  12649. });
  12650. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12651. std::chrono::steady_clock::now() - start)
  12652. .count();
  12653. ASSERT_FALSE(res);
  12654. EXPECT_EQ(Error::Read, res.error());
  12655. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  12656. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  12657. }
  12658. }
  12659. TEST(MaxTimeoutTest, ContentStream) {
  12660. time_t timeout = 2000;
  12661. time_t threshold = 200;
  12662. Server svr;
  12663. Client cli("localhost", PORT);
  12664. max_timeout_test(svr, cli, timeout, threshold);
  12665. }
  12666. #ifdef CPPHTTPLIB_SSL_ENABLED
  12667. TEST(MaxTimeoutTest, ContentStreamSSL) {
  12668. time_t timeout = 2000;
  12669. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  12670. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12671. SSLClient cli("localhost", PORT);
  12672. cli.enable_server_certificate_verification(false);
  12673. max_timeout_test(svr, cli, timeout, threshold);
  12674. }
  12675. #endif
  12676. class EventDispatcher {
  12677. public:
  12678. EventDispatcher() {}
  12679. bool wait_event(DataSink *sink) {
  12680. unique_lock<mutex> lk(m_);
  12681. int id = id_;
  12682. // Wait with timeout to prevent hanging if client disconnects
  12683. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  12684. [&] { return cid_ == id; })) {
  12685. return false; // Timeout occurred
  12686. }
  12687. sink->write(message_.data(), message_.size());
  12688. return true;
  12689. }
  12690. void send_event(const string &message) {
  12691. lock_guard<mutex> lk(m_);
  12692. cid_ = id_++;
  12693. message_ = message;
  12694. cv_.notify_all();
  12695. }
  12696. private:
  12697. mutex m_;
  12698. condition_variable cv_;
  12699. atomic_int id_{0};
  12700. atomic_int cid_{-1};
  12701. string message_;
  12702. };
  12703. TEST(ClientInThreadTest, Issue2068) {
  12704. EventDispatcher ed;
  12705. Server svr;
  12706. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  12707. res.set_chunked_content_provider("text/event-stream",
  12708. [&](size_t /*offset*/, DataSink &sink) {
  12709. return ed.wait_event(&sink);
  12710. });
  12711. });
  12712. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  12713. svr.wait_until_ready();
  12714. thread event_thread([&] {
  12715. int id = 0;
  12716. while (svr.is_running()) {
  12717. this_thread::sleep_for(chrono::milliseconds(500));
  12718. std::stringstream ss;
  12719. ss << "data: " << id << "\n\n";
  12720. ed.send_event(ss.str());
  12721. id++;
  12722. }
  12723. });
  12724. auto se = detail::scope_exit([&] {
  12725. svr.stop();
  12726. listen_thread.join();
  12727. event_thread.join();
  12728. ASSERT_FALSE(svr.is_running());
  12729. });
  12730. {
  12731. auto client = detail::make_unique<Client>(HOST, PORT);
  12732. client->set_read_timeout(std::chrono::minutes(10));
  12733. std::atomic<bool> stop{false};
  12734. std::thread t([&] {
  12735. client->Get("/event1",
  12736. [&](const char *, size_t) -> bool { return !stop; });
  12737. });
  12738. std::this_thread::sleep_for(std::chrono::seconds(2));
  12739. stop = true;
  12740. client->stop();
  12741. t.join();
  12742. // Reset client after thread has finished
  12743. client.reset();
  12744. }
  12745. }
  12746. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  12747. auto handled = false;
  12748. Server svr;
  12749. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  12750. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12751. auto se = detail::scope_exit([&] {
  12752. svr.stop();
  12753. t.join();
  12754. ASSERT_FALSE(svr.is_running());
  12755. ASSERT_FALSE(handled);
  12756. });
  12757. svr.wait_until_ready();
  12758. // Two Content-Length headers with different values — must be rejected
  12759. auto req = "POST /test HTTP/1.1\r\n"
  12760. "Content-Length: 5\r\n"
  12761. "Content-Length: 10\r\n"
  12762. "\r\n"
  12763. "hello";
  12764. std::string response;
  12765. ASSERT_TRUE(send_request(1, req, &response));
  12766. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  12767. response.substr(0, response.find("\r\n")));
  12768. }
  12769. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  12770. auto handled = false;
  12771. Server svr;
  12772. svr.Post("/test", [&](const Request &, Response &res) {
  12773. handled = true;
  12774. res.set_content("ok", "text/plain");
  12775. });
  12776. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12777. auto se = detail::scope_exit([&] {
  12778. svr.stop();
  12779. t.join();
  12780. ASSERT_FALSE(svr.is_running());
  12781. ASSERT_TRUE(handled);
  12782. });
  12783. svr.wait_until_ready();
  12784. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  12785. auto req = "POST /test HTTP/1.1\r\n"
  12786. "Content-Length: 5\r\n"
  12787. "Content-Length: 5\r\n"
  12788. "\r\n"
  12789. "hello";
  12790. std::string response;
  12791. ASSERT_TRUE(send_request(1, req, &response));
  12792. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  12793. }
  12794. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  12795. Server svr;
  12796. svr.Get("/", [](const Request &req, Response &res) {
  12797. EXPECT_EQ(2U, req.trailers.size());
  12798. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  12799. // Denied
  12800. EXPECT_FALSE(req.has_trailer("Content-Length"));
  12801. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  12802. // Accepted
  12803. EXPECT_TRUE(req.has_trailer("X-Hello"));
  12804. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  12805. EXPECT_TRUE(req.has_trailer("X-World"));
  12806. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  12807. res.set_content("ok", "text/plain");
  12808. });
  12809. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12810. auto se = detail::scope_exit([&] {
  12811. svr.stop();
  12812. t.join();
  12813. ASSERT_FALSE(svr.is_running());
  12814. });
  12815. svr.wait_until_ready();
  12816. const std::string req = "GET / HTTP/1.1\r\n"
  12817. "Transfer-Encoding: chunked\r\n"
  12818. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  12819. "\r\n"
  12820. "0\r\n"
  12821. "Content-Length: 10\r\n"
  12822. "Host: internal.local\r\n"
  12823. "Content-Type: malicious/content\r\n"
  12824. "Cookie: any\r\n"
  12825. "Set-Cookie: any\r\n"
  12826. "X-Forwarded-For: attacker.com\r\n"
  12827. "X-Real-Ip: 1.1.1.1\r\n"
  12828. "X-Hello: hello\r\n"
  12829. "X-World: world\r\n"
  12830. "\r\n";
  12831. std::string res;
  12832. ASSERT_TRUE(send_request(1, req, &res));
  12833. }
  12834. // A direct client that is not listed in trusted_proxies must not be able to
  12835. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  12836. // the peer address on the actual TCP connection determines whether the
  12837. // header is honored.
  12838. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  12839. Server svr;
  12840. // Deliberately does NOT include the loopback address the test client
  12841. // actually connects from, so the direct connection is not a trusted proxy.
  12842. svr.set_trusted_proxies({"203.0.113.66"});
  12843. std::string observed_remote_addr;
  12844. svr.Get("/ip", [&](const Request &req, Response &res) {
  12845. observed_remote_addr = req.remote_addr;
  12846. res.set_content("ok", "text/plain");
  12847. });
  12848. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12849. auto se = detail::scope_exit([&] {
  12850. svr.stop();
  12851. t.join();
  12852. ASSERT_FALSE(svr.is_running());
  12853. });
  12854. svr.wait_until_ready();
  12855. Client cli(HOST, PORT);
  12856. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  12857. ASSERT_TRUE(res);
  12858. EXPECT_EQ(StatusCode::OK_200, res->status);
  12859. // The connecting peer is not a trusted proxy, so the spoofed header must be
  12860. // ignored entirely and the real connection-level address retained.
  12861. EXPECT_TRUE(observed_remote_addr == "::1" ||
  12862. observed_remote_addr == "127.0.0.1");
  12863. }
  12864. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  12865. Server svr;
  12866. std::string observed_remote_addr;
  12867. std::string observed_xff;
  12868. svr.Get("/ip", [&](const Request &req, Response &res) {
  12869. observed_remote_addr = req.remote_addr;
  12870. observed_xff = req.get_header_value("X-Forwarded-For");
  12871. res.set_content("ok", "text/plain");
  12872. });
  12873. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12874. auto se = detail::scope_exit([&] {
  12875. svr.stop();
  12876. t.join();
  12877. ASSERT_FALSE(svr.is_running());
  12878. });
  12879. svr.wait_until_ready();
  12880. Client cli(HOST, PORT);
  12881. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  12882. ASSERT_TRUE(res);
  12883. EXPECT_EQ(StatusCode::OK_200, res->status);
  12884. EXPECT_EQ(observed_xff, "203.0.113.66");
  12885. EXPECT_TRUE(observed_remote_addr == "::1" ||
  12886. observed_remote_addr == "127.0.0.1");
  12887. }
  12888. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  12889. Server svr;
  12890. svr.set_trusted_proxies({"203.0.113.66"});
  12891. std::string observed_remote_addr;
  12892. std::string observed_xff;
  12893. svr.Get("/ip", [&](const Request &req, Response &res) {
  12894. observed_remote_addr = req.remote_addr;
  12895. observed_xff = req.get_header_value("X-Forwarded-For");
  12896. res.set_content("ok", "text/plain");
  12897. });
  12898. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12899. auto se = detail::scope_exit([&] {
  12900. svr.stop();
  12901. t.join();
  12902. ASSERT_FALSE(svr.is_running());
  12903. });
  12904. svr.wait_until_ready();
  12905. Client cli(HOST, PORT);
  12906. auto res = cli.Get("/ip");
  12907. ASSERT_TRUE(res);
  12908. EXPECT_EQ(StatusCode::OK_200, res->status);
  12909. EXPECT_EQ(observed_xff, "");
  12910. EXPECT_TRUE(observed_remote_addr == "::1" ||
  12911. observed_remote_addr == "127.0.0.1");
  12912. }
  12913. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  12914. Server svr;
  12915. // Include the loopback address the test client actually connects from, so
  12916. // the direct connection itself is recognized as the trusted proxy hop.
  12917. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  12918. std::string observed_remote_addr;
  12919. std::string observed_xff;
  12920. svr.Get("/ip", [&](const Request &req, Response &res) {
  12921. observed_remote_addr = req.remote_addr;
  12922. observed_xff = req.get_header_value("X-Forwarded-For");
  12923. res.set_content("ok", "text/plain");
  12924. });
  12925. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12926. auto se = detail::scope_exit([&] {
  12927. svr.stop();
  12928. t.join();
  12929. ASSERT_FALSE(svr.is_running());
  12930. });
  12931. svr.wait_until_ready();
  12932. Client cli(HOST, PORT);
  12933. auto res = cli.Get(
  12934. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  12935. ASSERT_TRUE(res);
  12936. EXPECT_EQ(StatusCode::OK_200, res->status);
  12937. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  12938. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  12939. }
  12940. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  12941. Server svr;
  12942. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  12943. std::string observed_remote_addr;
  12944. std::string observed_xff;
  12945. svr.Get("/ip", [&](const Request &req, Response &res) {
  12946. observed_remote_addr = req.remote_addr;
  12947. observed_xff = req.get_header_value("X-Forwarded-For");
  12948. res.set_content("ok", "text/plain");
  12949. });
  12950. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12951. auto se = detail::scope_exit([&] {
  12952. svr.stop();
  12953. t.join();
  12954. ASSERT_FALSE(svr.is_running());
  12955. });
  12956. svr.wait_until_ready();
  12957. Client cli(HOST, PORT);
  12958. auto res = cli.Get(
  12959. "/ip",
  12960. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  12961. ASSERT_TRUE(res);
  12962. EXPECT_EQ(StatusCode::OK_200, res->status);
  12963. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  12964. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  12965. }
  12966. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  12967. Server svr;
  12968. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  12969. std::string observed_remote_addr;
  12970. std::string observed_xff;
  12971. svr.Get("/ip", [&](const Request &req, Response &res) {
  12972. observed_remote_addr = req.remote_addr;
  12973. observed_xff = req.get_header_value("X-Forwarded-For");
  12974. res.set_content("ok", "text/plain");
  12975. });
  12976. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12977. auto se = detail::scope_exit([&] {
  12978. svr.stop();
  12979. t.join();
  12980. ASSERT_FALSE(svr.is_running());
  12981. });
  12982. svr.wait_until_ready();
  12983. Client cli(HOST, PORT);
  12984. auto res = cli.Get(
  12985. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  12986. ASSERT_TRUE(res);
  12987. EXPECT_EQ(StatusCode::OK_200, res->status);
  12988. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  12989. // by the closest hop) is used. The leftmost entry is fully client-controlled
  12990. // and must not be selected.
  12991. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  12992. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  12993. }
  12994. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  12995. Server svr;
  12996. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  12997. std::string observed_remote_addr;
  12998. svr.Get("/ip", [&](const Request &req, Response &res) {
  12999. observed_remote_addr = req.remote_addr;
  13000. res.set_content("ok", "text/plain");
  13001. });
  13002. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13003. auto se = detail::scope_exit([&] {
  13004. svr.stop();
  13005. t.join();
  13006. ASSERT_FALSE(svr.is_running());
  13007. });
  13008. svr.wait_until_ready();
  13009. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  13010. // a forged address and the trusted proxy's own address; the forged value must
  13011. // not win over the address the trusted proxy actually recorded.
  13012. Client cli(HOST, PORT);
  13013. auto res = cli.Get(
  13014. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  13015. ASSERT_TRUE(res);
  13016. EXPECT_EQ(StatusCode::OK_200, res->status);
  13017. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  13018. }
  13019. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  13020. Server svr;
  13021. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  13022. std::string observed_remote_addr;
  13023. std::string observed_xff;
  13024. svr.Get("/ip", [&](const Request &req, Response &res) {
  13025. observed_remote_addr = req.remote_addr;
  13026. observed_xff = req.get_header_value("X-Forwarded-For");
  13027. res.set_content("ok", "text/plain");
  13028. });
  13029. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13030. auto se = detail::scope_exit([&] {
  13031. svr.stop();
  13032. t.join();
  13033. ASSERT_FALSE(svr.is_running());
  13034. });
  13035. svr.wait_until_ready();
  13036. Client cli(HOST, PORT);
  13037. auto res = cli.Get(
  13038. "/ip",
  13039. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  13040. ASSERT_TRUE(res);
  13041. EXPECT_EQ(StatusCode::OK_200, res->status);
  13042. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  13043. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  13044. }
  13045. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  13046. Server svr;
  13047. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  13048. std::string observed_remote_addr;
  13049. std::string observed_xff;
  13050. svr.Get("/ip", [&](const Request &req, Response &res) {
  13051. observed_remote_addr = req.remote_addr;
  13052. observed_xff = req.get_header_value("X-Forwarded-For");
  13053. res.set_content("ok", "text/plain");
  13054. });
  13055. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13056. auto se = detail::scope_exit([&] {
  13057. svr.stop();
  13058. t.join();
  13059. ASSERT_FALSE(svr.is_running());
  13060. });
  13061. svr.wait_until_ready();
  13062. std::string raw_req =
  13063. "GET /ip HTTP/1.1\r\n"
  13064. "Host: localhost\r\n"
  13065. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  13066. "Connection: close\r\n"
  13067. "\r\n";
  13068. std::string out;
  13069. ASSERT_TRUE(send_request(5, raw_req, &out));
  13070. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  13071. // Header parser trims surrounding whitespace of the header value
  13072. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  13073. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  13074. }
  13075. // An X-Forwarded-For header whose value parses to zero IP segments must not
  13076. // crash the server (it used to call front() on an empty vector inside
  13077. // get_client_ip). The connection-level remote address must be retained instead.
  13078. static void run_malformed_xff_test(const std::string &xff_value) {
  13079. Server svr;
  13080. svr.set_trusted_proxies({"192.0.2.45"});
  13081. std::string observed_remote_addr;
  13082. svr.Get("/ip", [&](const Request &req, Response &res) {
  13083. observed_remote_addr = req.remote_addr;
  13084. res.set_content("ok", "text/plain");
  13085. });
  13086. int port = 0;
  13087. thread t = thread([&]() {
  13088. port = svr.bind_to_any_port(HOST);
  13089. svr.listen_after_bind();
  13090. });
  13091. auto se = detail::scope_exit([&] {
  13092. svr.stop();
  13093. t.join();
  13094. ASSERT_FALSE(svr.is_running());
  13095. });
  13096. svr.wait_until_ready();
  13097. Client cli(HOST, port);
  13098. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  13099. ASSERT_TRUE(res);
  13100. EXPECT_EQ(StatusCode::OK_200, res->status);
  13101. EXPECT_TRUE(observed_remote_addr == "::1" ||
  13102. observed_remote_addr == "127.0.0.1");
  13103. }
  13104. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  13105. run_malformed_xff_test("");
  13106. }
  13107. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  13108. run_malformed_xff_test(",");
  13109. }
  13110. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  13111. run_malformed_xff_test(", , ,");
  13112. }
  13113. #ifndef _WIN32
  13114. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  13115. Server svr;
  13116. svr.Post("/post", [&](const Request &req, Response &res) {
  13117. res.set_content(req.body, "text/plain");
  13118. });
  13119. svr.Put("/put", [&](const Request &req, Response &res) {
  13120. res.set_content(req.body, "text/plain");
  13121. });
  13122. svr.Patch("/patch", [&](const Request &req, Response &res) {
  13123. res.set_content(req.body, "text/plain");
  13124. });
  13125. svr.Delete("/delete", [&](const Request &req, Response &res) {
  13126. res.set_content(req.body, "text/plain");
  13127. });
  13128. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13129. auto se = detail::scope_exit([&] {
  13130. svr.stop();
  13131. t.join();
  13132. ASSERT_FALSE(svr.is_running());
  13133. });
  13134. svr.wait_until_ready();
  13135. std::string resp;
  13136. // POST without Content-Length
  13137. ASSERT_TRUE(send_request(5,
  13138. "POST /post HTTP/1.1\r\n"
  13139. "Host: localhost\r\n"
  13140. "Connection: close\r\n"
  13141. "\r\n",
  13142. &resp));
  13143. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  13144. // PUT without Content-Length
  13145. resp.clear();
  13146. ASSERT_TRUE(send_request(5,
  13147. "PUT /put HTTP/1.1\r\n"
  13148. "Host: localhost\r\n"
  13149. "Connection: close\r\n"
  13150. "\r\n",
  13151. &resp));
  13152. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  13153. // PATCH without Content-Length
  13154. resp.clear();
  13155. ASSERT_TRUE(send_request(5,
  13156. "PATCH /patch HTTP/1.1\r\n"
  13157. "Host: localhost\r\n"
  13158. "Connection: close\r\n"
  13159. "\r\n",
  13160. &resp));
  13161. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  13162. // DELETE without Content-Length
  13163. resp.clear();
  13164. ASSERT_TRUE(send_request(5,
  13165. "DELETE /delete HTTP/1.1\r\n"
  13166. "Host: localhost\r\n"
  13167. "Connection: close\r\n"
  13168. "\r\n",
  13169. &resp));
  13170. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  13171. }
  13172. #endif
  13173. //==============================================================================
  13174. // open_stream() Tests
  13175. //==============================================================================
  13176. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  13177. std::string result;
  13178. char buf[8192];
  13179. ssize_t n;
  13180. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13181. result.append(buf, static_cast<size_t>(n));
  13182. }
  13183. return result;
  13184. }
  13185. // Mock stream for unit tests
  13186. class MockStream : public Stream {
  13187. public:
  13188. std::string data;
  13189. size_t pos = 0;
  13190. ssize_t error_after = -1; // -1 = no error
  13191. explicit MockStream(const std::string &d, ssize_t err = -1)
  13192. : data(d), error_after(err) {}
  13193. bool is_readable() const override { return true; }
  13194. bool wait_readable() const override { return true; }
  13195. bool wait_writable() const override { return true; }
  13196. ssize_t read(char *ptr, size_t size) override {
  13197. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  13198. if (pos >= data.size()) return 0;
  13199. size_t limit =
  13200. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  13201. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  13202. std::memcpy(ptr, data.data() + pos, to_read);
  13203. pos += to_read;
  13204. return static_cast<ssize_t>(to_read);
  13205. }
  13206. ssize_t write(const char *, size_t) override { return -1; }
  13207. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  13208. ip = "127.0.0.1";
  13209. port = 0;
  13210. }
  13211. void get_local_ip_and_port(std::string &ip, int &port) const override {
  13212. ip = "127.0.0.1";
  13213. port = 0;
  13214. }
  13215. socket_t socket() const override { return INVALID_SOCKET; }
  13216. time_t duration() const override { return 0; }
  13217. };
  13218. TEST(StreamHandleTest, Basic) {
  13219. ClientImpl::StreamHandle handle;
  13220. EXPECT_FALSE(handle.is_valid());
  13221. handle.response = detail::make_unique<Response>();
  13222. handle.error = Error::Connection;
  13223. EXPECT_FALSE(handle.is_valid());
  13224. handle.error = Error::Success;
  13225. EXPECT_TRUE(handle.is_valid());
  13226. }
  13227. TEST(BodyReaderTest, Basic) {
  13228. MockStream stream("Hello, World!");
  13229. detail::BodyReader reader;
  13230. reader.stream = &stream;
  13231. reader.content_length = 13;
  13232. char buf[32];
  13233. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  13234. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  13235. EXPECT_TRUE(reader.eof);
  13236. }
  13237. TEST(BodyReaderTest, NoStream) {
  13238. detail::BodyReader reader;
  13239. char buf[32];
  13240. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  13241. EXPECT_EQ(Error::Connection, reader.last_error);
  13242. }
  13243. TEST(BodyReaderTest, Error) {
  13244. MockStream stream("Hello, World!", 5);
  13245. detail::BodyReader reader;
  13246. reader.stream = &stream;
  13247. reader.content_length = 13;
  13248. char buf[32];
  13249. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  13250. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  13251. EXPECT_EQ(Error::Read, reader.last_error);
  13252. }
  13253. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  13254. // Mock-based StreamHandle tests relying on private internals are removed.
  13255. class OpenStreamTest : public ::testing::Test {
  13256. protected:
  13257. void SetUp() override {
  13258. svr_.Get("/hello", [](const Request &, Response &res) {
  13259. res.set_content("Hello World!", "text/plain");
  13260. });
  13261. svr_.Get("/large", [](const Request &, Response &res) {
  13262. res.set_content(std::string(10000, 'X'), "text/plain");
  13263. });
  13264. svr_.Get("/chunked", [](const Request &, Response &res) {
  13265. res.set_chunked_content_provider("text/plain",
  13266. [](size_t offset, DataSink &sink) {
  13267. if (offset < 15) {
  13268. sink.write("chunk", 5);
  13269. return true;
  13270. }
  13271. sink.done();
  13272. return true;
  13273. });
  13274. });
  13275. svr_.Get("/compressible", [](const Request &, Response &res) {
  13276. res.set_chunked_content_provider("text/plain", [](size_t offset,
  13277. DataSink &sink) {
  13278. if (offset < 100 * 1024) {
  13279. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  13280. sink.write(chunk.data(), chunk.size());
  13281. return true;
  13282. }
  13283. sink.done();
  13284. return true;
  13285. });
  13286. });
  13287. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  13288. [](const Request & /*req*/, Response &res) {
  13289. auto i = new int(0);
  13290. res.set_header("Trailer", "Content-Length, X-Allowed");
  13291. res.set_chunked_content_provider(
  13292. "text/plain",
  13293. [i](size_t /*offset*/, DataSink &sink) {
  13294. switch (*i) {
  13295. case 0: sink.os << "123"; break;
  13296. case 1: sink.os << "456"; break;
  13297. case 2: sink.os << "789"; break;
  13298. case 3: {
  13299. sink.done_with_trailer(
  13300. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  13301. } break;
  13302. }
  13303. (*i)++;
  13304. return true;
  13305. },
  13306. [i](bool success) {
  13307. EXPECT_TRUE(success);
  13308. delete i;
  13309. });
  13310. });
  13311. // Echo headers endpoint for header-related tests
  13312. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  13313. std::string body;
  13314. for (const auto &h : req.headers) {
  13315. body.append(h.first);
  13316. body.push_back(':');
  13317. body.append(h.second);
  13318. body.push_back('\n');
  13319. }
  13320. res.set_content(body, "text/plain");
  13321. });
  13322. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  13323. std::string body;
  13324. for (const auto &h : req.headers) {
  13325. body.append(h.first);
  13326. body.push_back(':');
  13327. body.append(h.second);
  13328. body.push_back('\n');
  13329. }
  13330. res.set_content(body, "text/plain");
  13331. });
  13332. port_ = svr_.bind_to_any_port("127.0.0.1");
  13333. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  13334. svr_.wait_until_ready();
  13335. }
  13336. void TearDown() override {
  13337. svr_.stop();
  13338. if (thread_.joinable()) thread_.join();
  13339. }
  13340. Server svr_;
  13341. std::thread thread_;
  13342. int port_ = 0;
  13343. };
  13344. TEST_F(OpenStreamTest, Basic) {
  13345. Client cli("127.0.0.1", port_);
  13346. auto handle = cli.open_stream("GET", "/hello");
  13347. EXPECT_TRUE(handle.is_valid());
  13348. EXPECT_EQ("Hello World!", read_all(handle));
  13349. }
  13350. TEST_F(OpenStreamTest, SmallBuffer) {
  13351. Client cli("127.0.0.1", port_);
  13352. auto handle = cli.open_stream("GET", "/hello");
  13353. std::string result;
  13354. char buf[4];
  13355. ssize_t n;
  13356. while ((n = handle.read(buf, sizeof(buf))) > 0)
  13357. result.append(buf, static_cast<size_t>(n));
  13358. EXPECT_EQ("Hello World!", result);
  13359. }
  13360. TEST_F(OpenStreamTest, DefaultHeaders) {
  13361. Client cli("127.0.0.1", port_);
  13362. // open_stream GET should include Host, User-Agent and Accept-Encoding
  13363. {
  13364. auto handle = cli.open_stream("GET", "/echo-headers");
  13365. ASSERT_TRUE(handle.is_valid());
  13366. auto body = read_all(handle);
  13367. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  13368. std::string::npos);
  13369. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  13370. std::string::npos);
  13371. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  13372. }
  13373. // open_stream POST with body and no explicit content_type should NOT add
  13374. // text/plain Content-Type (behavior differs from non-streaming path), but
  13375. // should include Content-Length
  13376. {
  13377. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  13378. ASSERT_TRUE(handle.is_valid());
  13379. auto body = read_all(handle);
  13380. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  13381. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  13382. }
  13383. // open_stream POST with explicit Content-Type should preserve it
  13384. {
  13385. auto handle = cli.open_stream("POST", "/echo-headers", {},
  13386. {{"Content-Type", "application/custom"}},
  13387. "{}", "application/custom");
  13388. ASSERT_TRUE(handle.is_valid());
  13389. auto body = read_all(handle);
  13390. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  13391. }
  13392. // User-specified User-Agent must not be overwritten for stream API
  13393. {
  13394. auto handle = cli.open_stream("GET", "/echo-headers", {},
  13395. {{"User-Agent", "MyAgent/1.2"}});
  13396. ASSERT_TRUE(handle.is_valid());
  13397. auto body = read_all(handle);
  13398. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  13399. }
  13400. }
  13401. TEST_F(OpenStreamTest, Large) {
  13402. Client cli("127.0.0.1", port_);
  13403. auto handle = cli.open_stream("GET", "/large");
  13404. EXPECT_EQ(10000u, read_all(handle).size());
  13405. }
  13406. TEST_F(OpenStreamTest, ConnectionError) {
  13407. Client cli("127.0.0.1", 9999);
  13408. auto handle = cli.open_stream("GET", "/hello");
  13409. EXPECT_FALSE(handle.is_valid());
  13410. }
  13411. TEST_F(OpenStreamTest, Chunked) {
  13412. Client cli("127.0.0.1", port_);
  13413. auto handle = cli.open_stream("GET", "/chunked");
  13414. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  13415. "Transfer-Encoding") == "chunked");
  13416. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  13417. }
  13418. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  13419. Client cli("127.0.0.1", port_);
  13420. auto handle =
  13421. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  13422. ASSERT_TRUE(handle.is_valid());
  13423. // Consume body to allow trailers to be received/parsed
  13424. auto body = read_all(handle);
  13425. // Explicitly parse trailers (ensure trailers are available for assertion)
  13426. handle.parse_trailers_if_needed();
  13427. EXPECT_EQ(std::string("123456789"), body);
  13428. // The response should include a Trailer header declaring both names
  13429. ASSERT_TRUE(handle.response);
  13430. EXPECT_TRUE(handle.response->has_header("Trailer"));
  13431. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  13432. handle.response->get_header_value("Trailer"));
  13433. // Prohibited trailer must not be present
  13434. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  13435. // Allowed trailer should be present
  13436. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  13437. EXPECT_EQ(std::string("yes"),
  13438. handle.response->get_trailer_value("X-Allowed"));
  13439. // Verify trailers are NOT present as regular headers
  13440. EXPECT_EQ(std::string(""),
  13441. handle.response->get_header_value("Content-Length"));
  13442. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  13443. }
  13444. static std::thread serve_single_response(std::promise<int> &port_promise,
  13445. const std::string &response) {
  13446. return std::thread([&port_promise, response] {
  13447. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13448. default_socket_options(srv);
  13449. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13450. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13451. sockaddr_in addr{};
  13452. addr.sin_family = AF_INET;
  13453. addr.sin_port = htons(0); // Let OS assign a free port
  13454. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13455. int opt = 1;
  13456. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13457. #ifdef _WIN32
  13458. reinterpret_cast<const char *>(&opt),
  13459. #else
  13460. &opt,
  13461. #endif
  13462. sizeof(opt));
  13463. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  13464. ::listen(srv, 1) != 0) {
  13465. port_promise.set_value(-1);
  13466. detail::close_socket(srv);
  13467. return;
  13468. }
  13469. socklen_t addr_len = sizeof(addr);
  13470. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  13471. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  13472. sockaddr_in cli_addr{};
  13473. socklen_t cli_len = sizeof(cli_addr);
  13474. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13475. if (cli != INVALID_SOCKET) {
  13476. // Read the complete HTTP request (until the blank line that terminates
  13477. // headers) before sending the response. If the server closes the socket
  13478. // while the client's request data is still unread in the kernel receive
  13479. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  13480. // connection on both sides: it discards the client's receive buffer
  13481. // (which already holds our response) and causes any in-progress write on
  13482. // the client to fail with ECONNRESET. Reading all request data first
  13483. // ensures close() emits a graceful FIN.
  13484. {
  13485. char rbuf[256];
  13486. std::string req;
  13487. while (req.find("\r\n\r\n") == std::string::npos) {
  13488. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  13489. if (n <= 0) { break; }
  13490. req.append(rbuf, static_cast<size_t>(n));
  13491. }
  13492. }
  13493. ::send(cli,
  13494. #ifdef _WIN32
  13495. static_cast<const char *>(response.c_str()),
  13496. static_cast<int>(response.size()),
  13497. #else
  13498. response.c_str(), response.size(),
  13499. #endif
  13500. 0);
  13501. detail::close_socket(cli);
  13502. }
  13503. detail::close_socket(srv);
  13504. });
  13505. }
  13506. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  13507. #ifndef _WIN32
  13508. signal(SIGPIPE, SIG_IGN);
  13509. #endif
  13510. std::promise<int> port_promise;
  13511. auto port_future = port_promise.get_future();
  13512. auto server_thread =
  13513. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  13514. "Content-Type: text/plain\r\n"
  13515. "Content-Length: not-a-number\r\n"
  13516. "Connection: close\r\n"
  13517. "\r\n"
  13518. "hello");
  13519. auto port = port_future.get();
  13520. ASSERT_GT(port, 0);
  13521. Client cli("127.0.0.1", port);
  13522. auto handle = cli.open_stream("GET", "/");
  13523. EXPECT_FALSE(handle.is_valid());
  13524. server_thread.join();
  13525. }
  13526. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  13527. #ifndef _WIN32
  13528. signal(SIGPIPE, SIG_IGN);
  13529. #endif
  13530. std::promise<int> port_promise;
  13531. auto port_future = port_promise.get_future();
  13532. auto server_thread = serve_single_response(
  13533. port_promise, "HTTP/1.1 200 OK\r\n"
  13534. "Content-Type: text/plain\r\n"
  13535. "Content-Length: 99999999999999999999999999\r\n"
  13536. "Connection: close\r\n"
  13537. "\r\n"
  13538. "hello");
  13539. auto port = port_future.get();
  13540. ASSERT_GT(port, 0);
  13541. // Historically std::stoull would throw std::out_of_range here and crash
  13542. // the process, then parsing silently clamped to a bogus framing length and
  13543. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  13544. // so the stream fails to open, matching the not-a-number case above. The
  13545. // process still must NOT terminate.
  13546. Client cli("127.0.0.1", port);
  13547. auto handle = cli.open_stream("GET", "/");
  13548. EXPECT_FALSE(handle.is_valid());
  13549. server_thread.join();
  13550. }
  13551. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13552. TEST_F(OpenStreamTest, Gzip) {
  13553. Client cli("127.0.0.1", port_);
  13554. auto handle = cli.open_stream("GET", "/compressible", {},
  13555. {{"Accept-Encoding", "gzip"}});
  13556. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  13557. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  13558. }
  13559. #endif
  13560. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  13561. TEST_F(OpenStreamTest, Brotli) {
  13562. Client cli("127.0.0.1", port_);
  13563. auto handle =
  13564. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  13565. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  13566. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  13567. }
  13568. #endif
  13569. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  13570. TEST_F(OpenStreamTest, Zstd) {
  13571. Client cli("127.0.0.1", port_);
  13572. auto handle = cli.open_stream("GET", "/compressible", {},
  13573. {{"Accept-Encoding", "zstd"}});
  13574. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  13575. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  13576. }
  13577. #endif
  13578. #ifdef CPPHTTPLIB_SSL_ENABLED
  13579. class SSLOpenStreamTest : public ::testing::Test {
  13580. protected:
  13581. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  13582. void SetUp() override {
  13583. svr_.Get("/hello", [](const Request &, Response &res) {
  13584. res.set_content("Hello SSL World!", "text/plain");
  13585. });
  13586. svr_.Get("/chunked", [](const Request &, Response &res) {
  13587. res.set_chunked_content_provider("text/plain",
  13588. [](size_t offset, DataSink &sink) {
  13589. if (offset < 15) {
  13590. sink.write("chunk", 5);
  13591. return true;
  13592. }
  13593. sink.done();
  13594. return true;
  13595. });
  13596. });
  13597. svr_.Post("/echo", [](const Request &req, Response &res) {
  13598. res.set_content(req.body, req.get_header_value("Content-Type"));
  13599. });
  13600. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  13601. std::string body = req.body;
  13602. res.set_chunked_content_provider(
  13603. "text/plain", [body](size_t offset, DataSink &sink) {
  13604. if (offset < body.size()) {
  13605. sink.write(body.data() + offset, body.size() - offset);
  13606. }
  13607. sink.done();
  13608. return true;
  13609. });
  13610. });
  13611. port_ = svr_.bind_to_any_port("127.0.0.1");
  13612. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  13613. svr_.wait_until_ready();
  13614. }
  13615. void TearDown() override {
  13616. svr_.stop();
  13617. if (thread_.joinable()) thread_.join();
  13618. }
  13619. SSLServer svr_;
  13620. std::thread thread_;
  13621. int port_ = 0;
  13622. };
  13623. TEST_F(SSLOpenStreamTest, Basic) {
  13624. SSLClient cli("127.0.0.1", port_);
  13625. cli.enable_server_certificate_verification(false);
  13626. auto handle = cli.open_stream("GET", "/hello");
  13627. ASSERT_TRUE(handle.is_valid());
  13628. EXPECT_EQ("Hello SSL World!", read_all(handle));
  13629. }
  13630. TEST_F(SSLOpenStreamTest, Chunked) {
  13631. SSLClient cli("127.0.0.1", port_);
  13632. cli.enable_server_certificate_verification(false);
  13633. auto handle = cli.open_stream("GET", "/chunked");
  13634. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  13635. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  13636. "Transfer-Encoding") == "chunked");
  13637. auto body = read_all(handle);
  13638. EXPECT_EQ("chunkchunkchunk", body);
  13639. }
  13640. TEST_F(SSLOpenStreamTest, Post) {
  13641. SSLClient cli("127.0.0.1", port_);
  13642. cli.enable_server_certificate_verification(false);
  13643. auto handle =
  13644. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  13645. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  13646. EXPECT_EQ(200, handle.response->status);
  13647. auto body = read_all(handle);
  13648. EXPECT_EQ("Hello SSL POST", body);
  13649. }
  13650. TEST_F(SSLOpenStreamTest, PostChunked) {
  13651. SSLClient cli("127.0.0.1", port_);
  13652. cli.enable_server_certificate_verification(false);
  13653. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  13654. "Chunked SSL Data", "text/plain");
  13655. ASSERT_TRUE(handle.is_valid());
  13656. EXPECT_EQ(200, handle.response->status);
  13657. auto body = read_all(handle);
  13658. EXPECT_EQ("Chunked SSL Data", body);
  13659. }
  13660. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  13661. // Content-Length is terminated by the server closing the connection. When the
  13662. // SSL peer sends a close_notify after the body, the client must treat it as a
  13663. // clean EOF and return a successful response rather than an error.
  13664. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  13665. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13666. ASSERT_TRUE(svr.is_valid());
  13667. svr.set_keep_alive_max_count(1);
  13668. const std::string expected_body = "Hello from connection-close response!";
  13669. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  13670. res.set_content_provider("text/plain",
  13671. [&](size_t offset, DataSink &sink) -> bool {
  13672. if (offset < expected_body.size()) {
  13673. sink.write(expected_body.data() + offset,
  13674. expected_body.size() - offset);
  13675. }
  13676. sink.done();
  13677. return true;
  13678. });
  13679. });
  13680. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  13681. auto se = detail::scope_exit([&] {
  13682. svr.stop();
  13683. listen_thread.join();
  13684. ASSERT_FALSE(svr.is_running());
  13685. });
  13686. svr.wait_until_ready();
  13687. SSLClient cli(HOST, PORT);
  13688. cli.enable_server_certificate_verification(false);
  13689. auto res = cli.Get("/no-content-length");
  13690. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  13691. EXPECT_EQ(StatusCode::OK_200, res->status);
  13692. EXPECT_EQ(expected_body, res->body);
  13693. }
  13694. #endif // CPPHTTPLIB_SSL_ENABLED
  13695. //==============================================================================
  13696. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  13697. // results for various scenarios.
  13698. //==============================================================================
  13699. TEST(ParityTest, GetVsOpenStream) {
  13700. Server svr;
  13701. const std::string path = "/parity";
  13702. const std::string content = "Parity test content: hello world";
  13703. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  13704. res.set_content(content, "text/plain");
  13705. });
  13706. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13707. auto se = detail::scope_exit([&] {
  13708. svr.stop();
  13709. t.join();
  13710. ASSERT_FALSE(svr.is_running());
  13711. });
  13712. svr.wait_until_ready();
  13713. Client cli(HOST, PORT);
  13714. // Non-stream path
  13715. auto r1 = cli.Get(path);
  13716. ASSERT_TRUE(r1);
  13717. EXPECT_EQ(StatusCode::OK_200, r1->status);
  13718. // Stream path
  13719. auto h = cli.open_stream("GET", path);
  13720. ASSERT_TRUE(h.is_valid());
  13721. EXPECT_EQ(r1->body, read_all(h));
  13722. }
  13723. // Helper to compress data with provided compressor type T
  13724. template <typename Compressor>
  13725. static std::string compress_payload_for_parity(const std::string &in) {
  13726. std::string out;
  13727. Compressor compressor;
  13728. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  13729. [&](const char *data, size_t n) {
  13730. out.append(data, n);
  13731. return true;
  13732. });
  13733. EXPECT_TRUE(ok);
  13734. return out;
  13735. }
  13736. // Helper function for compression parity tests
  13737. template <typename Compressor>
  13738. static void test_compression_parity(const std::string &original,
  13739. const std::string &path,
  13740. const std::string &encoding) {
  13741. const std::string compressed =
  13742. compress_payload_for_parity<Compressor>(original);
  13743. Server svr;
  13744. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  13745. res.set_content(compressed, "application/octet-stream");
  13746. res.set_header("Content-Encoding", encoding);
  13747. });
  13748. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  13749. auto se = detail::scope_exit([&] {
  13750. svr.stop();
  13751. t.join();
  13752. ASSERT_FALSE(svr.is_running());
  13753. });
  13754. svr.wait_until_ready();
  13755. Client cli(HOST, PORT);
  13756. // Non-streaming
  13757. {
  13758. auto res = cli.Get(path);
  13759. ASSERT_TRUE(res);
  13760. EXPECT_EQ(StatusCode::OK_200, res->status);
  13761. EXPECT_EQ(original, res->body);
  13762. }
  13763. // Streaming
  13764. {
  13765. auto h = cli.open_stream("GET", path);
  13766. ASSERT_TRUE(h.is_valid());
  13767. EXPECT_EQ(original, read_all(h));
  13768. }
  13769. }
  13770. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13771. TEST(ParityTest, Gzip) {
  13772. test_compression_parity<detail::gzip_compressor>(
  13773. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  13774. }
  13775. #endif
  13776. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  13777. TEST(ParityTest, Brotli) {
  13778. test_compression_parity<detail::brotli_compressor>(
  13779. "Hello, brotli parity test payload", "/parity-br", "br");
  13780. }
  13781. #endif
  13782. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  13783. TEST(ParityTest, Zstd) {
  13784. test_compression_parity<detail::zstd_compressor>(
  13785. "Zstandard parity test payload", "/parity-zstd", "zstd");
  13786. }
  13787. #endif
  13788. //==============================================================================
  13789. // New Stream API Tests
  13790. //==============================================================================
  13791. inline std::string read_body(httplib::stream::Result &result) {
  13792. std::string body;
  13793. while (result.next()) {
  13794. body.append(result.data(), result.size());
  13795. }
  13796. return body;
  13797. }
  13798. TEST(ClientConnectionTest, Basic) {
  13799. httplib::ClientConnection conn;
  13800. EXPECT_FALSE(conn.is_open());
  13801. conn.sock = 1;
  13802. EXPECT_TRUE(conn.is_open());
  13803. httplib::ClientConnection conn2(std::move(conn));
  13804. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  13805. conn2.sock = INVALID_SOCKET;
  13806. }
  13807. // Unified test server for all stream::* tests
  13808. class StreamApiTest : public ::testing::Test {
  13809. protected:
  13810. void SetUp() override {
  13811. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  13812. res.set_content("Hello World!", "text/plain");
  13813. });
  13814. svr_.Get("/echo-params",
  13815. [](const httplib::Request &req, httplib::Response &res) {
  13816. std::string r;
  13817. for (const auto &p : req.params) {
  13818. if (!r.empty()) r += "&";
  13819. r += p.first + "=" + p.second;
  13820. }
  13821. res.set_content(r, "text/plain");
  13822. });
  13823. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  13824. res.set_content(req.body, req.get_header_value("Content-Type"));
  13825. });
  13826. svr_.Post("/echo-headers",
  13827. [](const httplib::Request &req, httplib::Response &res) {
  13828. std::string r;
  13829. for (const auto &h : req.headers)
  13830. r += h.first + ": " + h.second + "\n";
  13831. res.set_content(r, "text/plain");
  13832. });
  13833. svr_.Post("/echo-params",
  13834. [](const httplib::Request &req, httplib::Response &res) {
  13835. std::string r = "params:";
  13836. for (const auto &p : req.params)
  13837. r += p.first + "=" + p.second + ";";
  13838. res.set_content(r + " body:" + req.body, "text/plain");
  13839. });
  13840. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  13841. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  13842. });
  13843. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  13844. res.set_content("PUT:" + req.body, "text/plain");
  13845. });
  13846. svr_.Patch("/echo",
  13847. [](const httplib::Request &req, httplib::Response &res) {
  13848. res.set_content("PATCH:" + req.body, "text/plain");
  13849. });
  13850. svr_.Delete(
  13851. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  13852. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  13853. "text/plain");
  13854. });
  13855. svr_.Get("/head-test",
  13856. [](const httplib::Request &, httplib::Response &res) {
  13857. res.set_content("body for HEAD", "text/plain");
  13858. });
  13859. svr_.Options("/options",
  13860. [](const httplib::Request &, httplib::Response &res) {
  13861. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  13862. });
  13863. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  13864. svr_.wait_until_ready();
  13865. }
  13866. void TearDown() override {
  13867. svr_.stop();
  13868. if (thread_.joinable()) thread_.join();
  13869. }
  13870. httplib::Server svr_;
  13871. std::thread thread_;
  13872. };
  13873. // stream::Get tests
  13874. TEST_F(StreamApiTest, GetBasic) {
  13875. httplib::Client cli(HOST, PORT);
  13876. auto result = httplib::stream::Get(cli, "/hello");
  13877. ASSERT_TRUE(result.is_valid());
  13878. EXPECT_EQ(200, result.status());
  13879. EXPECT_EQ("Hello World!", read_body(result));
  13880. }
  13881. TEST_F(StreamApiTest, GetWithParams) {
  13882. httplib::Client cli(HOST, PORT);
  13883. httplib::Params params{{"foo", "bar"}};
  13884. auto result = httplib::stream::Get(cli, "/echo-params", params);
  13885. ASSERT_TRUE(result.is_valid());
  13886. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  13887. }
  13888. TEST_F(StreamApiTest, GetConnectionError) {
  13889. httplib::Client cli(HOST, 9999);
  13890. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  13891. }
  13892. TEST_F(StreamApiTest, Get404) {
  13893. httplib::Client cli(HOST, PORT);
  13894. auto result = httplib::stream::Get(cli, "/nonexistent");
  13895. EXPECT_TRUE(result.is_valid());
  13896. EXPECT_EQ(404, result.status());
  13897. }
  13898. // stream::Post tests
  13899. TEST_F(StreamApiTest, PostBasic) {
  13900. httplib::Client cli(HOST, PORT);
  13901. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  13902. "application/json");
  13903. ASSERT_TRUE(result.is_valid());
  13904. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  13905. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  13906. }
  13907. TEST_F(StreamApiTest, PostWithHeaders) {
  13908. httplib::Client cli(HOST, PORT);
  13909. httplib::Headers headers{{"X-Custom", "value"}};
  13910. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  13911. "text/plain");
  13912. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  13913. }
  13914. TEST_F(StreamApiTest, PostWithParams) {
  13915. httplib::Client cli(HOST, PORT);
  13916. httplib::Params params{{"k", "v"}};
  13917. auto result =
  13918. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  13919. auto body = read_body(result);
  13920. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  13921. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  13922. }
  13923. TEST_F(StreamApiTest, PostLarge) {
  13924. httplib::Client cli(HOST, PORT);
  13925. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  13926. size_t total = 0;
  13927. while (result.next()) {
  13928. total += result.size();
  13929. }
  13930. EXPECT_EQ(100u * 1024u, total);
  13931. }
  13932. // stream::Put/Patch tests
  13933. TEST_F(StreamApiTest, PutAndPatch) {
  13934. httplib::Client cli(HOST, PORT);
  13935. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  13936. EXPECT_EQ("PUT:test", read_body(put));
  13937. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  13938. EXPECT_EQ("PATCH:test", read_body(patch));
  13939. }
  13940. // stream::Delete tests
  13941. TEST_F(StreamApiTest, Delete) {
  13942. httplib::Client cli(HOST, PORT);
  13943. auto del1 = httplib::stream::Delete(cli, "/resource");
  13944. EXPECT_EQ("Deleted", read_body(del1));
  13945. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  13946. EXPECT_EQ("Deleted:data", read_body(del2));
  13947. }
  13948. // stream::Head/Options tests
  13949. TEST_F(StreamApiTest, HeadAndOptions) {
  13950. httplib::Client cli(HOST, PORT);
  13951. auto head = httplib::stream::Head(cli, "/head-test");
  13952. EXPECT_TRUE(head.is_valid());
  13953. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  13954. auto opts = httplib::stream::Options(cli, "/options");
  13955. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  13956. }
  13957. // SSL stream::* tests
  13958. #ifdef CPPHTTPLIB_SSL_ENABLED
  13959. class SSLStreamApiTest : public ::testing::Test {
  13960. protected:
  13961. void SetUp() override {
  13962. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  13963. res.set_content("Hello SSL!", "text/plain");
  13964. });
  13965. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  13966. res.set_content(req.body, "text/plain");
  13967. });
  13968. port_ = svr_.bind_to_any_port("127.0.0.1");
  13969. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  13970. svr_.wait_until_ready();
  13971. }
  13972. void TearDown() override {
  13973. svr_.stop();
  13974. if (thread_.joinable()) thread_.join();
  13975. }
  13976. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  13977. std::thread thread_;
  13978. int port_ = 0;
  13979. };
  13980. TEST_F(SSLStreamApiTest, GetAndPost) {
  13981. httplib::SSLClient cli("127.0.0.1", port_);
  13982. cli.enable_server_certificate_verification(false);
  13983. auto get = httplib::stream::Get(cli, "/hello");
  13984. EXPECT_EQ("Hello SSL!", read_body(get));
  13985. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  13986. EXPECT_EQ("test", read_body(post));
  13987. }
  13988. #endif
  13989. // Tests for Error::Timeout and Error::ConnectionClosed error types
  13990. // These errors are set in SocketStream/SSLSocketStream and propagated through
  13991. // BodyReader
  13992. TEST(ErrorHandlingTest, StreamReadTimeout) {
  13993. // Test that read timeout during streaming is detected
  13994. // Use a large content-length response where server delays mid-stream
  13995. Server svr;
  13996. svr.Get("/slow-stream", [](const Request &, Response &res) {
  13997. // Send a large response with delay in the middle
  13998. res.set_content_provider(
  13999. 1000, // content_length
  14000. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  14001. if (offset < 100) {
  14002. // Send first 100 bytes immediately
  14003. std::string data(100, 'A');
  14004. sink.write(data.c_str(), data.size());
  14005. return true;
  14006. }
  14007. // Then delay longer than client timeout
  14008. std::this_thread::sleep_for(std::chrono::seconds(3));
  14009. std::string data(900, 'B');
  14010. sink.write(data.c_str(), data.size());
  14011. return true;
  14012. });
  14013. });
  14014. auto port = 8091;
  14015. std::thread t([&]() { svr.listen("localhost", port); });
  14016. svr.wait_until_ready();
  14017. Client cli("localhost", port);
  14018. cli.set_read_timeout(1, 0); // 1 second timeout
  14019. auto handle = cli.open_stream("GET", "/slow-stream");
  14020. ASSERT_TRUE(handle.is_valid());
  14021. char buf[256];
  14022. ssize_t total = 0;
  14023. ssize_t n;
  14024. bool got_error = false;
  14025. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  14026. total += n;
  14027. }
  14028. if (n < 0) {
  14029. got_error = true;
  14030. // Should be timeout or read error
  14031. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  14032. handle.get_read_error() == Error::Read)
  14033. << "Actual error: " << to_string(handle.get_read_error());
  14034. }
  14035. // Either we got an error, or we got less data than expected
  14036. EXPECT_TRUE(got_error || total < 1000)
  14037. << "Expected timeout but got all " << total << " bytes";
  14038. svr.stop();
  14039. t.join();
  14040. }
  14041. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  14042. // Test connection closed detection via BodyReader
  14043. Server svr;
  14044. std::atomic<bool> close_now{false};
  14045. svr.Get("/will-close", [&](const Request &, Response &res) {
  14046. res.set_content_provider(
  14047. 10000, // Large content_length that we won't fully send
  14048. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  14049. if (offset < 100) {
  14050. std::string data(100, 'X');
  14051. sink.write(data.c_str(), data.size());
  14052. return true;
  14053. }
  14054. // Wait for signal then abort
  14055. while (!close_now) {
  14056. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  14057. }
  14058. return false; // Abort - server will close connection
  14059. });
  14060. });
  14061. auto port = 8092;
  14062. std::thread t([&]() { svr.listen("localhost", port); });
  14063. svr.wait_until_ready();
  14064. Client cli("localhost", port);
  14065. auto handle = cli.open_stream("GET", "/will-close");
  14066. ASSERT_TRUE(handle.is_valid());
  14067. char buf[256];
  14068. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  14069. EXPECT_GT(n, 0) << "First read should succeed";
  14070. // Signal server to close
  14071. close_now = true;
  14072. // Keep reading until error or EOF
  14073. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  14074. // Keep reading
  14075. }
  14076. // Should get an error since content_length wasn't satisfied
  14077. if (n < 0) {
  14078. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  14079. handle.get_read_error() == Error::Read)
  14080. << "Actual error: " << to_string(handle.get_read_error());
  14081. }
  14082. svr.stop();
  14083. t.join();
  14084. }
  14085. #ifdef CPPHTTPLIB_SSL_ENABLED
  14086. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  14087. // Test that read timeout during SSL streaming is detected
  14088. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14089. svr.Get("/slow-stream", [](const Request &, Response &res) {
  14090. res.set_content_provider(
  14091. 1000, "text/plain",
  14092. [](size_t offset, size_t /*length*/, DataSink &sink) {
  14093. if (offset < 100) {
  14094. std::string data(100, 'A');
  14095. sink.write(data.c_str(), data.size());
  14096. return true;
  14097. }
  14098. std::this_thread::sleep_for(std::chrono::seconds(3));
  14099. std::string data(900, 'B');
  14100. sink.write(data.c_str(), data.size());
  14101. return true;
  14102. });
  14103. });
  14104. auto port = 8093;
  14105. std::thread t([&]() { svr.listen("localhost", port); });
  14106. svr.wait_until_ready();
  14107. SSLClient cli("localhost", port);
  14108. cli.enable_server_certificate_verification(false);
  14109. cli.set_read_timeout(1, 0); // 1 second timeout
  14110. auto handle = cli.open_stream("GET", "/slow-stream");
  14111. ASSERT_TRUE(handle.is_valid());
  14112. char buf[256];
  14113. ssize_t total = 0;
  14114. ssize_t n;
  14115. bool got_error = false;
  14116. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  14117. total += n;
  14118. }
  14119. if (n < 0) {
  14120. got_error = true;
  14121. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  14122. handle.get_read_error() == Error::Read)
  14123. << "Actual error: " << to_string(handle.get_read_error());
  14124. }
  14125. EXPECT_TRUE(got_error || total < 1000)
  14126. << "Expected timeout but got all " << total << " bytes";
  14127. svr.stop();
  14128. t.join();
  14129. }
  14130. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  14131. // Test SSL connection closed detection
  14132. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14133. std::atomic<bool> close_now{false};
  14134. svr.Get("/will-close", [&](const Request &, Response &res) {
  14135. res.set_content_provider(
  14136. 10000, "text/plain",
  14137. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  14138. if (offset < 100) {
  14139. std::string data(100, 'X');
  14140. sink.write(data.c_str(), data.size());
  14141. return true;
  14142. }
  14143. while (!close_now) {
  14144. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  14145. }
  14146. return false;
  14147. });
  14148. });
  14149. auto port = 8094;
  14150. std::thread t([&]() { svr.listen("localhost", port); });
  14151. svr.wait_until_ready();
  14152. SSLClient cli("localhost", port);
  14153. cli.enable_server_certificate_verification(false);
  14154. auto handle = cli.open_stream("GET", "/will-close");
  14155. ASSERT_TRUE(handle.is_valid());
  14156. char buf[256];
  14157. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  14158. EXPECT_GT(n, 0);
  14159. // Signal server to close
  14160. close_now = true;
  14161. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  14162. // Keep reading
  14163. }
  14164. if (n < 0) {
  14165. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  14166. handle.get_read_error() == Error::Read)
  14167. << "Actual error: " << to_string(handle.get_read_error());
  14168. }
  14169. svr.stop();
  14170. t.join();
  14171. }
  14172. #endif
  14173. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  14174. using namespace httplib;
  14175. // Create a test file
  14176. const char *fname = "etag_testfile.txt";
  14177. const char *content = "etag-content";
  14178. {
  14179. std::ofstream ofs(fname);
  14180. ofs << content;
  14181. ASSERT_TRUE(ofs.good());
  14182. }
  14183. Server svr;
  14184. svr.set_mount_point("/static", ".");
  14185. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  14186. svr.wait_until_ready();
  14187. Client cli(HOST, PORT);
  14188. // First request: should get 200 with ETag header
  14189. auto res1 = cli.Get("/static/etag_testfile.txt");
  14190. ASSERT_TRUE(res1);
  14191. ASSERT_EQ(200, res1->status);
  14192. ASSERT_TRUE(res1->has_header("ETag"));
  14193. std::string etag = res1->get_header_value("ETag");
  14194. EXPECT_FALSE(etag.empty());
  14195. // Verify ETag format: W/"hex-hex"
  14196. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  14197. EXPECT_EQ('W', etag[0]);
  14198. EXPECT_EQ('/', etag[1]);
  14199. EXPECT_EQ('"', etag[2]);
  14200. EXPECT_EQ('"', etag.back());
  14201. // Exact match: expect 304 Not Modified
  14202. Headers h2 = {{"If-None-Match", etag}};
  14203. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  14204. ASSERT_TRUE(res2);
  14205. EXPECT_EQ(304, res2->status);
  14206. // Wildcard match: expect 304 Not Modified
  14207. Headers h3 = {{"If-None-Match", "*"}};
  14208. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  14209. ASSERT_TRUE(res3);
  14210. EXPECT_EQ(304, res3->status);
  14211. // Non-matching ETag: expect 200
  14212. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  14213. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  14214. ASSERT_TRUE(res4);
  14215. EXPECT_EQ(200, res4->status);
  14216. // Multiple ETags with one matching: expect 304
  14217. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  14218. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  14219. ASSERT_TRUE(res5);
  14220. EXPECT_EQ(304, res5->status);
  14221. svr.stop();
  14222. t.join();
  14223. std::remove(fname);
  14224. }
  14225. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  14226. using namespace httplib;
  14227. Server svr;
  14228. svr.set_mount_point("/static", ".");
  14229. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14230. svr.wait_until_ready();
  14231. Client cli(HOST, PORT);
  14232. // Send If-None-Match: * to a non-existent file
  14233. Headers h = {{"If-None-Match", "*"}};
  14234. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  14235. ASSERT_TRUE(res);
  14236. EXPECT_EQ(404, res->status);
  14237. svr.stop();
  14238. t.join();
  14239. }
  14240. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  14241. using namespace httplib;
  14242. // Create a test file
  14243. const char *fname = "etag_boundary_testfile.txt";
  14244. const char *content = "boundary-test";
  14245. {
  14246. std::ofstream ofs(fname);
  14247. ofs << content;
  14248. ASSERT_TRUE(ofs.good());
  14249. }
  14250. Server svr;
  14251. svr.set_mount_point("/static", ".");
  14252. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  14253. svr.wait_until_ready();
  14254. Client cli(HOST, PORT);
  14255. // Get the actual ETag
  14256. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  14257. ASSERT_TRUE(res1);
  14258. ASSERT_EQ(200, res1->status);
  14259. ASSERT_TRUE(res1->has_header("ETag"));
  14260. std::string etag = res1->get_header_value("ETag");
  14261. // Test 1: Very long ETag value (longer than actual ETag)
  14262. // Should NOT match and return 200 (not trigger out-of-bounds read)
  14263. Headers h1 = {{"If-None-Match", "W/"
  14264. "\"very-long-etag-value-that-is-much-longer-"
  14265. "than-the-actual-etag-value\""}};
  14266. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  14267. ASSERT_TRUE(res2);
  14268. EXPECT_EQ(200, res2->status); // Should not match
  14269. // Test 2: Long string followed by wildcard
  14270. // Should match on "*" and return 304 (without out-of-bounds read on the long
  14271. // string)
  14272. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  14273. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  14274. ASSERT_TRUE(res3);
  14275. EXPECT_EQ(304, res3->status); // Should match on "*"
  14276. // Test 3: Wildcard followed by long string
  14277. // Should match on "*" immediately and return 304
  14278. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  14279. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  14280. ASSERT_TRUE(res4);
  14281. EXPECT_EQ(304, res4->status); // Should match on "*"
  14282. // Test 4: Multiple long non-matching values
  14283. // Should NOT match and return 200 (test that all comparisons are safe)
  14284. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  14285. "W/\"second-long-non-matching-value\", "
  14286. "W/\"third-long-non-matching-value\""}};
  14287. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  14288. ASSERT_TRUE(res5);
  14289. EXPECT_EQ(200, res5->status); // Should not match
  14290. // Test 5: Single character that is not "*" (edge case)
  14291. Headers h5 = {{"If-None-Match", "X"}};
  14292. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  14293. ASSERT_TRUE(res6);
  14294. EXPECT_EQ(200, res6->status); // Should not match
  14295. svr.stop();
  14296. t.join();
  14297. std::remove(fname);
  14298. }
  14299. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  14300. using namespace httplib;
  14301. // Create a test file
  14302. const char *fname = "ims_testfile.txt";
  14303. const char *content = "if-modified-since-test";
  14304. {
  14305. std::ofstream ofs(fname);
  14306. ofs << content;
  14307. ASSERT_TRUE(ofs.good());
  14308. }
  14309. Server svr;
  14310. svr.set_mount_point("/static", ".");
  14311. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14312. svr.wait_until_ready();
  14313. Client cli(HOST, PORT);
  14314. // First request: should get 200 with Last-Modified header
  14315. auto res1 = cli.Get("/static/ims_testfile.txt");
  14316. ASSERT_TRUE(res1);
  14317. ASSERT_EQ(200, res1->status);
  14318. ASSERT_TRUE(res1->has_header("Last-Modified"));
  14319. std::string last_modified = res1->get_header_value("Last-Modified");
  14320. EXPECT_FALSE(last_modified.empty());
  14321. // If-Modified-Since with same time: expect 304
  14322. Headers h2 = {{"If-Modified-Since", last_modified}};
  14323. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  14324. ASSERT_TRUE(res2);
  14325. EXPECT_EQ(304, res2->status);
  14326. // If-Modified-Since with future time: expect 304
  14327. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  14328. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  14329. ASSERT_TRUE(res3);
  14330. EXPECT_EQ(304, res3->status);
  14331. // If-Modified-Since with past time: expect 200
  14332. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  14333. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  14334. ASSERT_TRUE(res4);
  14335. EXPECT_EQ(200, res4->status);
  14336. // If-None-Match takes precedence over If-Modified-Since
  14337. // (send matching ETag with old If-Modified-Since -> should still be 304)
  14338. ASSERT_TRUE(res1->has_header("ETag"));
  14339. std::string etag = res1->get_header_value("ETag");
  14340. Headers h5 = {{"If-None-Match", etag},
  14341. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  14342. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  14343. ASSERT_TRUE(res5);
  14344. EXPECT_EQ(304, res5->status);
  14345. svr.stop();
  14346. t.join();
  14347. std::remove(fname);
  14348. }
  14349. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  14350. using namespace httplib;
  14351. Server svr;
  14352. // Endpoint that returns compressible content
  14353. svr.Get("/compressible", [](const Request &, Response &res) {
  14354. // Return a large enough body to trigger compression
  14355. std::string body(1000, 'a');
  14356. res.set_content(body, "text/plain");
  14357. });
  14358. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14359. svr.wait_until_ready();
  14360. Client cli(HOST, PORT);
  14361. // Request with gzip support: should get Vary header when compressed
  14362. cli.set_compress(true);
  14363. auto res1 = cli.Get("/compressible");
  14364. ASSERT_TRUE(res1);
  14365. EXPECT_EQ(200, res1->status);
  14366. // If Content-Encoding is set, Vary should also be set
  14367. if (res1->has_header("Content-Encoding")) {
  14368. EXPECT_TRUE(res1->has_header("Vary"));
  14369. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  14370. }
  14371. // Request without Accept-Encoding header: should not have compression
  14372. Headers h_no_compress;
  14373. auto res2 = cli.Get("/compressible", h_no_compress);
  14374. ASSERT_TRUE(res2);
  14375. EXPECT_EQ(200, res2->status);
  14376. // Verify Vary header is present when compression is applied
  14377. // (the exact behavior depends on server configuration)
  14378. svr.stop();
  14379. t.join();
  14380. }
  14381. TEST(ETagTest, IfRangeWithETag) {
  14382. using namespace httplib;
  14383. // Create a test file with known content
  14384. const char *fname = "if_range_testfile.txt";
  14385. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  14386. {
  14387. std::ofstream ofs(fname);
  14388. ofs << content;
  14389. ASSERT_TRUE(ofs.good());
  14390. }
  14391. Server svr;
  14392. svr.set_mount_point("/static", ".");
  14393. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14394. svr.wait_until_ready();
  14395. Client cli(HOST, PORT);
  14396. // First request: get ETag
  14397. auto res1 = cli.Get("/static/if_range_testfile.txt");
  14398. ASSERT_TRUE(res1);
  14399. ASSERT_EQ(200, res1->status);
  14400. ASSERT_TRUE(res1->has_header("ETag"));
  14401. std::string etag = res1->get_header_value("ETag");
  14402. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  14403. // Since our server generates weak ETags (W/"..."), If-Range with our
  14404. // ETag should NOT result in partial content - it should return full content.
  14405. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  14406. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  14407. ASSERT_TRUE(res2);
  14408. // Weak ETag in If-Range -> full content (200), not partial (206)
  14409. EXPECT_EQ(200, res2->status);
  14410. EXPECT_EQ(content, res2->body);
  14411. EXPECT_FALSE(res2->has_header("Content-Range"));
  14412. // Range request with non-matching If-Range (ETag): should get 200 (full
  14413. // content)
  14414. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  14415. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  14416. ASSERT_TRUE(res3);
  14417. EXPECT_EQ(200, res3->status);
  14418. EXPECT_EQ(content, res3->body);
  14419. EXPECT_FALSE(res3->has_header("Content-Range"));
  14420. // Range request with strong ETag (hypothetical - our server doesn't generate
  14421. // strong ETags, but if client sends a strong ETag that doesn't match, it
  14422. // should return full content)
  14423. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  14424. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  14425. ASSERT_TRUE(res4);
  14426. EXPECT_EQ(200, res4->status);
  14427. EXPECT_EQ(content, res4->body);
  14428. EXPECT_FALSE(res4->has_header("Content-Range"));
  14429. svr.stop();
  14430. t.join();
  14431. std::remove(fname);
  14432. }
  14433. TEST(ETagTest, IfRangeWithDate) {
  14434. using namespace httplib;
  14435. // Create a test file
  14436. const char *fname = "if_range_date_testfile.txt";
  14437. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  14438. {
  14439. std::ofstream ofs(fname);
  14440. ofs << content;
  14441. ASSERT_TRUE(ofs.good());
  14442. }
  14443. Server svr;
  14444. svr.set_mount_point("/static", ".");
  14445. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14446. svr.wait_until_ready();
  14447. Client cli(HOST, PORT);
  14448. // First request: get Last-Modified
  14449. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  14450. ASSERT_TRUE(res1);
  14451. ASSERT_EQ(200, res1->status);
  14452. ASSERT_TRUE(res1->has_header("Last-Modified"));
  14453. std::string last_modified = res1->get_header_value("Last-Modified");
  14454. // Range request with matching If-Range (date): should get 206
  14455. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  14456. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  14457. ASSERT_TRUE(res2);
  14458. EXPECT_EQ(206, res2->status);
  14459. EXPECT_EQ("FGHIJ", res2->body);
  14460. // Range request with old If-Range date: should get 200 (full content)
  14461. Headers h3 = {{"Range", "bytes=5-9"},
  14462. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  14463. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  14464. ASSERT_TRUE(res3);
  14465. EXPECT_EQ(200, res3->status);
  14466. EXPECT_EQ(content, res3->body);
  14467. // Range request with future If-Range date: should get 206
  14468. Headers h4 = {{"Range", "bytes=0-4"},
  14469. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  14470. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  14471. ASSERT_TRUE(res4);
  14472. EXPECT_EQ(206, res4->status);
  14473. EXPECT_EQ("ABCDE", res4->body);
  14474. svr.stop();
  14475. t.join();
  14476. std::remove(fname);
  14477. }
  14478. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  14479. using namespace httplib;
  14480. const char *fname = "etag_malformed.txt";
  14481. const char *content = "malformed-etag";
  14482. {
  14483. std::ofstream ofs(fname);
  14484. ofs << content;
  14485. ASSERT_TRUE(ofs.good());
  14486. }
  14487. Server svr;
  14488. svr.set_mount_point("/static", ".");
  14489. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14490. svr.wait_until_ready();
  14491. Client cli(HOST, PORT);
  14492. // baseline: should get 200 and an ETag
  14493. auto res1 = cli.Get("/static/etag_malformed.txt");
  14494. ASSERT_TRUE(res1);
  14495. ASSERT_EQ(200, res1->status);
  14496. ASSERT_TRUE(res1->has_header("ETag"));
  14497. // Malformed ETag value (missing quotes) should be treated as non-matching
  14498. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  14499. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  14500. ASSERT_TRUE(res_bad);
  14501. EXPECT_EQ(200, res_bad->status);
  14502. // Whitespace-only header value should be considered invalid / non-matching
  14503. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  14504. "Host: localhost\r\n"
  14505. "If-None-Match: \r\n"
  14506. "Connection: close\r\n"
  14507. "\r\n";
  14508. std::string out;
  14509. ASSERT_TRUE(send_request(5, raw_req, &out));
  14510. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  14511. svr.stop();
  14512. t.join();
  14513. std::remove(fname);
  14514. }
  14515. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  14516. using namespace httplib;
  14517. const char *fname = "ims_invalid_format.txt";
  14518. const char *content = "ims-bad-format";
  14519. {
  14520. std::ofstream ofs(fname);
  14521. ofs << content;
  14522. ASSERT_TRUE(ofs.good());
  14523. }
  14524. Server svr;
  14525. svr.set_mount_point("/static", ".");
  14526. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14527. svr.wait_until_ready();
  14528. Client cli(HOST, PORT);
  14529. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  14530. ASSERT_TRUE(res1);
  14531. ASSERT_EQ(200, res1->status);
  14532. ASSERT_TRUE(res1->has_header("Last-Modified"));
  14533. // If-Modified-Since with invalid format should not result in 304
  14534. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  14535. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  14536. ASSERT_TRUE(res_bad);
  14537. EXPECT_EQ(200, res_bad->status);
  14538. // If-Range with invalid date format should be treated as mismatch -> full
  14539. // content (200)
  14540. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  14541. {"If-Range", "invalid-date"}};
  14542. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  14543. ASSERT_TRUE(res_ifrange);
  14544. EXPECT_EQ(200, res_ifrange->status);
  14545. svr.stop();
  14546. t.join();
  14547. std::remove(fname);
  14548. }
  14549. TEST(ETagTest, IfRangeWithMalformedETag) {
  14550. using namespace httplib;
  14551. const char *fname = "ifrange_malformed.txt";
  14552. const std::string content = "0123456789";
  14553. {
  14554. std::ofstream ofs(fname);
  14555. ofs << content;
  14556. ASSERT_TRUE(ofs.good());
  14557. }
  14558. Server svr;
  14559. svr.set_mount_point("/static", ".");
  14560. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14561. svr.wait_until_ready();
  14562. Client cli(HOST, PORT);
  14563. // First request: get ETag
  14564. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  14565. ASSERT_TRUE(res1);
  14566. ASSERT_EQ(200, res1->status);
  14567. ASSERT_TRUE(res1->has_header("ETag"));
  14568. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  14569. // full content (200)
  14570. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  14571. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  14572. ASSERT_TRUE(res2);
  14573. EXPECT_EQ(200, res2->status);
  14574. EXPECT_EQ(content, res2->body);
  14575. svr.stop();
  14576. t.join();
  14577. std::remove(fname);
  14578. }
  14579. TEST(ETagTest, ExtremeLargeDateValues) {
  14580. using namespace httplib;
  14581. const char *fname = "ims_extreme_date.txt";
  14582. const char *content = "ims-extreme-date";
  14583. {
  14584. std::ofstream ofs(fname);
  14585. ofs << content;
  14586. ASSERT_TRUE(ofs.good());
  14587. }
  14588. Server svr;
  14589. svr.set_mount_point("/static", ".");
  14590. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14591. svr.wait_until_ready();
  14592. Client cli(HOST, PORT);
  14593. auto res1 = cli.Get(std::string("/static/") + fname);
  14594. ASSERT_TRUE(res1);
  14595. ASSERT_EQ(200, res1->status);
  14596. ASSERT_TRUE(res1->has_header("Last-Modified"));
  14597. // Extremely large year that may overflow date parsing routines.
  14598. Headers h_large_date = {
  14599. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  14600. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  14601. ASSERT_TRUE(res_bad);
  14602. // Expect server to treat this as invalid/mismatch and return full content
  14603. EXPECT_EQ(200, res_bad->status);
  14604. // If-Range with extremely large date should be treated as mismatch -> full
  14605. // content (200)
  14606. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  14607. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  14608. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  14609. ASSERT_TRUE(res_ifrange);
  14610. EXPECT_EQ(200, res_ifrange->status);
  14611. svr.stop();
  14612. t.join();
  14613. std::remove(fname);
  14614. }
  14615. TEST(ETagTest, NegativeFileModificationTime) {
  14616. using namespace httplib;
  14617. const char *fname = "ims_negative_mtime.txt";
  14618. const std::string content = "negative-mtime";
  14619. {
  14620. std::ofstream ofs(fname);
  14621. ofs << content;
  14622. ASSERT_TRUE(ofs.good());
  14623. }
  14624. // Try to set file mtime to a negative value. This may fail on some
  14625. // platforms/filesystems; if it fails, the test will still verify server
  14626. // behaves safely by performing a regular conditional request.
  14627. #if defined(__APPLE__) || defined(__linux__)
  14628. bool set_negative = false;
  14629. do {
  14630. struct timeval times[2];
  14631. // access time: now
  14632. times[0].tv_sec = time(nullptr);
  14633. times[0].tv_usec = 0;
  14634. // modification time: negative (e.g., -1)
  14635. times[1].tv_sec = -1;
  14636. times[1].tv_usec = 0;
  14637. if (utimes(fname, times) == 0) { set_negative = true; }
  14638. } while (0);
  14639. #else
  14640. bool set_negative = false;
  14641. #endif
  14642. Server svr;
  14643. svr.set_mount_point("/static", ".");
  14644. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14645. svr.wait_until_ready();
  14646. Client cli(HOST, PORT);
  14647. auto res1 = cli.Get(std::string("/static/") + fname);
  14648. ASSERT_TRUE(res1);
  14649. ASSERT_EQ(200, res1->status);
  14650. bool has_last_modified = res1->has_header("Last-Modified");
  14651. std::string last_modified;
  14652. if (has_last_modified) {
  14653. last_modified = res1->get_header_value("Last-Modified");
  14654. }
  14655. if (set_negative) {
  14656. // If we successfully set a negative mtime, ensure server returns a
  14657. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  14658. // with an old date and ensure server handles it without crash.
  14659. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  14660. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  14661. ASSERT_TRUE(res2);
  14662. // Behavior may vary; at minimum ensure server responds (200 or 304).
  14663. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  14664. } else {
  14665. // Could not set negative mtime on this platform; fall back to verifying
  14666. // that normal invalid/malformed dates are treated safely (non-304).
  14667. Headers h_bad_date = {
  14668. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  14669. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  14670. ASSERT_TRUE(res_bad);
  14671. EXPECT_EQ(200, res_bad->status);
  14672. }
  14673. svr.stop();
  14674. t.join();
  14675. std::remove(fname);
  14676. }
  14677. //==============================================================================
  14678. // SSE Parsing Tests
  14679. //==============================================================================
  14680. class SSEParsingTest : public ::testing::Test {
  14681. protected:
  14682. // Test helper that mimics SSE parsing behavior
  14683. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  14684. int &retry_ms) {
  14685. // Blank line signals end of event
  14686. if (line.empty() || line == "\r") { return true; }
  14687. // Lines starting with ':' are comments (ignored)
  14688. if (!line.empty() && line[0] == ':') { return false; }
  14689. // Find the colon separator
  14690. auto colon_pos = line.find(':');
  14691. if (colon_pos == std::string::npos) {
  14692. // Line with no colon is treated as field name with empty value
  14693. return false;
  14694. }
  14695. std::string field = line.substr(0, colon_pos);
  14696. std::string value;
  14697. // Value starts after colon, skip optional single space
  14698. if (colon_pos + 1 < line.size()) {
  14699. size_t value_start = colon_pos + 1;
  14700. if (line[value_start] == ' ') { value_start++; }
  14701. value = line.substr(value_start);
  14702. // Remove trailing \r if present
  14703. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  14704. }
  14705. // Handle known fields
  14706. if (field == "event") {
  14707. msg.event = value;
  14708. } else if (field == "data") {
  14709. // Multiple data lines are concatenated with newlines
  14710. if (!msg.data.empty()) { msg.data += "\n"; }
  14711. msg.data += value;
  14712. } else if (field == "id") {
  14713. // Empty id is valid (clears the last event ID)
  14714. msg.id = value;
  14715. } else if (field == "retry") {
  14716. // Parse retry interval in milliseconds
  14717. {
  14718. int v = 0;
  14719. auto res =
  14720. detail::from_chars(value.data(), value.data() + value.size(), v);
  14721. if (res.ec == std::errc{}) { retry_ms = v; }
  14722. }
  14723. }
  14724. // Unknown fields are ignored per SSE spec
  14725. return false;
  14726. }
  14727. };
  14728. // Test: Single-line data
  14729. TEST_F(SSEParsingTest, SingleLineData) {
  14730. sse::SSEMessage msg;
  14731. int retry_ms = 3000;
  14732. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  14733. EXPECT_EQ(msg.data, "hello");
  14734. EXPECT_EQ(msg.event, "message");
  14735. // Blank line ends event
  14736. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  14737. }
  14738. // Test: Multi-line data
  14739. TEST_F(SSEParsingTest, MultiLineData) {
  14740. sse::SSEMessage msg;
  14741. int retry_ms = 3000;
  14742. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  14743. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  14744. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  14745. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  14746. }
  14747. // Test: Custom event types
  14748. TEST_F(SSEParsingTest, CustomEventType) {
  14749. sse::SSEMessage msg;
  14750. int retry_ms = 3000;
  14751. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  14752. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  14753. EXPECT_EQ(msg.event, "update");
  14754. EXPECT_EQ(msg.data, "payload");
  14755. }
  14756. // Test: Event ID handling
  14757. TEST_F(SSEParsingTest, EventIdHandling) {
  14758. sse::SSEMessage msg;
  14759. int retry_ms = 3000;
  14760. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  14761. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  14762. EXPECT_EQ(msg.id, "12345");
  14763. }
  14764. // Test: Empty event ID (clears last event ID)
  14765. TEST_F(SSEParsingTest, EmptyEventId) {
  14766. sse::SSEMessage msg;
  14767. msg.id = "previous";
  14768. int retry_ms = 3000;
  14769. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  14770. EXPECT_EQ(msg.id, "");
  14771. }
  14772. // Test: Retry field parsing
  14773. TEST_F(SSEParsingTest, RetryFieldParsing) {
  14774. sse::SSEMessage msg;
  14775. int retry_ms = 3000;
  14776. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  14777. EXPECT_EQ(retry_ms, 5000);
  14778. }
  14779. // Test: Invalid retry value
  14780. TEST_F(SSEParsingTest, InvalidRetryValue) {
  14781. sse::SSEMessage msg;
  14782. int retry_ms = 3000;
  14783. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  14784. EXPECT_EQ(retry_ms, 3000); // Unchanged
  14785. }
  14786. // Test: Comments (lines starting with :)
  14787. TEST_F(SSEParsingTest, CommentsIgnored) {
  14788. sse::SSEMessage msg;
  14789. int retry_ms = 3000;
  14790. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  14791. EXPECT_EQ(msg.data, "");
  14792. EXPECT_EQ(msg.event, "message");
  14793. }
  14794. // Test: Colon in value
  14795. TEST_F(SSEParsingTest, ColonInValue) {
  14796. sse::SSEMessage msg;
  14797. int retry_ms = 3000;
  14798. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  14799. EXPECT_EQ(msg.data, "hello:world:test");
  14800. }
  14801. // Test: Line with no colon (field name only)
  14802. TEST_F(SSEParsingTest, FieldNameOnly) {
  14803. sse::SSEMessage msg;
  14804. int retry_ms = 3000;
  14805. // According to SSE spec, this is treated as field name with empty value
  14806. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  14807. // Since we don't recognize "data" without colon, data should be empty
  14808. EXPECT_EQ(msg.data, "");
  14809. }
  14810. // Test: Trailing \r handling
  14811. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  14812. sse::SSEMessage msg;
  14813. int retry_ms = 3000;
  14814. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  14815. EXPECT_EQ(msg.data, "hello");
  14816. }
  14817. // Test: Unknown fields ignored
  14818. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  14819. sse::SSEMessage msg;
  14820. int retry_ms = 3000;
  14821. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  14822. EXPECT_EQ(msg.data, "");
  14823. EXPECT_EQ(msg.event, "message");
  14824. }
  14825. // Test: Space after colon is optional
  14826. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  14827. sse::SSEMessage msg1, msg2;
  14828. int retry_ms = 3000;
  14829. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  14830. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  14831. EXPECT_EQ(msg1.data, "hello");
  14832. EXPECT_EQ(msg2.data, "hello");
  14833. }
  14834. // Test: SSEMessage clear
  14835. TEST_F(SSEParsingTest, MessageClear) {
  14836. sse::SSEMessage msg;
  14837. msg.event = "custom";
  14838. msg.data = "some data";
  14839. msg.id = "123";
  14840. msg.clear();
  14841. EXPECT_EQ(msg.event, "message");
  14842. EXPECT_EQ(msg.data, "");
  14843. EXPECT_EQ(msg.id, "");
  14844. }
  14845. // Test: Complete event parsing
  14846. TEST_F(SSEParsingTest, CompleteEventParsing) {
  14847. sse::SSEMessage msg;
  14848. int retry_ms = 3000;
  14849. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  14850. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  14851. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  14852. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  14853. // Blank line ends event
  14854. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  14855. EXPECT_EQ(msg.event, "notification");
  14856. EXPECT_EQ(msg.id, "evt-42");
  14857. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  14858. EXPECT_EQ(retry_ms, 1000);
  14859. }
  14860. //==============================================================================
  14861. // Integration Tests with Server
  14862. //==============================================================================
  14863. class SSEIntegrationTest : public ::testing::Test {
  14864. protected:
  14865. void SetUp() override {
  14866. stop_server_.store(false);
  14867. events_.clear();
  14868. server_ = httplib::detail::make_unique<Server>();
  14869. setup_server();
  14870. start_server();
  14871. }
  14872. void TearDown() override {
  14873. stop_server_.store(true);
  14874. event_cv_.notify_all();
  14875. server_->stop();
  14876. if (server_thread_.joinable()) { server_thread_.join(); }
  14877. }
  14878. void setup_server() {
  14879. // Simple SSE endpoint
  14880. server_->Get("/events", [this](const Request &req, Response &res) {
  14881. auto last_id = req.get_header_value("Last-Event-ID");
  14882. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  14883. res.set_chunked_content_provider(
  14884. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  14885. std::unique_lock<std::mutex> lock(event_mutex_);
  14886. if (event_cv_.wait_for(
  14887. lock, std::chrono::milliseconds(200), [this] {
  14888. return !events_.empty() || stop_server_.load();
  14889. })) {
  14890. if (stop_server_.load()) { return false; }
  14891. if (!events_.empty()) {
  14892. std::string event = events_.front();
  14893. events_.erase(events_.begin());
  14894. sink.write(event.data(), event.size());
  14895. return true;
  14896. }
  14897. }
  14898. return !stop_server_.load();
  14899. });
  14900. });
  14901. // Endpoint that returns error
  14902. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  14903. res.status = 500;
  14904. res.set_content("Internal Server Error", "text/plain");
  14905. });
  14906. // Endpoint for custom event types
  14907. server_->Get("/custom-events", [](const Request &, Response &res) {
  14908. res.set_chunked_content_provider(
  14909. "text/event-stream", [](size_t offset, DataSink &sink) {
  14910. if (offset == 0) {
  14911. std::string event = "event: update\ndata: updated\n\n"
  14912. "event: delete\ndata: deleted\n\n";
  14913. sink.write(event.data(), event.size());
  14914. }
  14915. return false; // End stream after sending
  14916. });
  14917. });
  14918. }
  14919. void start_server() {
  14920. port_ = server_->bind_to_any_port(HOST);
  14921. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  14922. // Wait for server to start
  14923. while (!server_->is_running()) {
  14924. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  14925. }
  14926. }
  14927. int get_port() const { return port_; }
  14928. void send_event(const std::string &event) {
  14929. std::lock_guard<std::mutex> lock(event_mutex_);
  14930. events_.push_back(event);
  14931. event_cv_.notify_all();
  14932. }
  14933. std::unique_ptr<Server> server_;
  14934. std::thread server_thread_;
  14935. std::mutex event_mutex_;
  14936. std::condition_variable event_cv_;
  14937. std::vector<std::string> events_;
  14938. std::atomic<bool> stop_server_{false};
  14939. std::string last_received_event_id_;
  14940. int port_ = 0;
  14941. };
  14942. // Test: Successful connection and on_open callback
  14943. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  14944. // Add a simple endpoint that sends one event and closes
  14945. server_->Get("/simple-event", [](const Request &, Response &res) {
  14946. res.set_chunked_content_provider(
  14947. "text/event-stream", [](size_t offset, DataSink &sink) {
  14948. if (offset == 0) {
  14949. std::string event = "data: hello\n\n";
  14950. sink.write(event.data(), event.size());
  14951. }
  14952. return false; // Close stream after sending
  14953. });
  14954. });
  14955. Client client("localhost", get_port());
  14956. sse::SSEClient sse(client, "/simple-event");
  14957. std::atomic<bool> open_called{false};
  14958. std::atomic<bool> message_received{false};
  14959. sse.on_open([&open_called]() { open_called.store(true); });
  14960. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  14961. if (msg.data == "hello") { message_received.store(true); }
  14962. });
  14963. sse.set_reconnect_interval(100);
  14964. sse.set_max_reconnect_attempts(1);
  14965. // Start async
  14966. sse.start_async();
  14967. // Wait for message to be processed
  14968. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  14969. sse.stop();
  14970. EXPECT_TRUE(open_called.load());
  14971. EXPECT_TRUE(message_received.load());
  14972. }
  14973. // Test: on_message callback
  14974. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  14975. // Endpoint that sends multiple events then closes
  14976. server_->Get("/multi-event", [](const Request &, Response &res) {
  14977. res.set_chunked_content_provider(
  14978. "text/event-stream", [](size_t offset, DataSink &sink) {
  14979. if (offset == 0) {
  14980. std::string events = "data: message1\n\ndata: message2\n\n";
  14981. sink.write(events.data(), events.size());
  14982. }
  14983. return false;
  14984. });
  14985. });
  14986. Client client("localhost", get_port());
  14987. sse::SSEClient sse(client, "/multi-event");
  14988. std::vector<std::string> received_messages;
  14989. std::mutex messages_mutex;
  14990. sse.on_message([&](const sse::SSEMessage &msg) {
  14991. std::lock_guard<std::mutex> lock(messages_mutex);
  14992. received_messages.push_back(msg.data);
  14993. });
  14994. sse.set_reconnect_interval(100);
  14995. sse.set_max_reconnect_attempts(1);
  14996. sse.start_async();
  14997. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  14998. sse.stop();
  14999. std::lock_guard<std::mutex> lock(messages_mutex);
  15000. EXPECT_GE(received_messages.size(), 2u);
  15001. if (received_messages.size() >= 2) {
  15002. EXPECT_EQ(received_messages[0], "message1");
  15003. EXPECT_EQ(received_messages[1], "message2");
  15004. }
  15005. }
  15006. // Test: on_event for specific types
  15007. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  15008. Client client("localhost", get_port());
  15009. sse::SSEClient sse(client, "/custom-events");
  15010. std::atomic<bool> update_received{false};
  15011. std::atomic<bool> delete_received{false};
  15012. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  15013. if (msg.data == "updated") { update_received.store(true); }
  15014. });
  15015. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  15016. if (msg.data == "deleted") { delete_received.store(true); }
  15017. });
  15018. sse.set_max_reconnect_attempts(1);
  15019. sse.start_async();
  15020. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  15021. sse.stop();
  15022. EXPECT_TRUE(update_received.load());
  15023. EXPECT_TRUE(delete_received.load());
  15024. }
  15025. // Test: on_error callback on connection failure
  15026. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  15027. // Connect to a non-existent port
  15028. Client client("localhost", 59999);
  15029. sse::SSEClient sse(client, "/events");
  15030. std::atomic<bool> error_called{false};
  15031. Error received_error = Error::Success;
  15032. sse.on_error([&](Error err) {
  15033. error_called.store(true);
  15034. received_error = err;
  15035. });
  15036. sse.set_reconnect_interval(50);
  15037. sse.set_max_reconnect_attempts(1);
  15038. sse.start_async();
  15039. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  15040. sse.stop();
  15041. EXPECT_TRUE(error_called.load());
  15042. EXPECT_NE(received_error, Error::Success);
  15043. }
  15044. // Test: Last-Event-ID header sent on reconnect
  15045. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  15046. // Endpoint that sends event with ID
  15047. server_->Get("/event-with-id", [](const Request &, Response &res) {
  15048. res.set_chunked_content_provider(
  15049. "text/event-stream", [](size_t offset, DataSink &sink) {
  15050. if (offset == 0) {
  15051. std::string event = "id: evt-123\ndata: test\n\n";
  15052. sink.write(event.data(), event.size());
  15053. }
  15054. return false;
  15055. });
  15056. });
  15057. Client client("localhost", get_port());
  15058. sse::SSEClient sse(client, "/event-with-id");
  15059. std::atomic<bool> id_received{false};
  15060. sse.on_message([&](const sse::SSEMessage &msg) {
  15061. if (!msg.id.empty()) { id_received.store(true); }
  15062. });
  15063. sse.set_reconnect_interval(100);
  15064. sse.set_max_reconnect_attempts(1);
  15065. sse.start_async();
  15066. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  15067. sse.stop();
  15068. EXPECT_TRUE(id_received.load());
  15069. EXPECT_EQ(sse.last_event_id(), "evt-123");
  15070. }
  15071. // Test: Manual stop
  15072. TEST_F(SSEIntegrationTest, ManualStop) {
  15073. // Endpoint that sends one event and stays open briefly
  15074. std::atomic<bool> handler_running{true};
  15075. server_->Get("/stay-open", [&handler_running](const Request &,
  15076. Response &res) {
  15077. res.set_chunked_content_provider(
  15078. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  15079. if (offset == 0) {
  15080. std::string event = "data: connected\n\n";
  15081. sink.write(event.data(), event.size());
  15082. }
  15083. // Keep connection open while handler_running is true
  15084. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  15085. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  15086. }
  15087. return false;
  15088. });
  15089. });
  15090. Client client("localhost", get_port());
  15091. sse::SSEClient sse(client, "/stay-open");
  15092. std::atomic<bool> connected{false};
  15093. sse.on_open([&connected]() { connected.store(true); });
  15094. sse.set_reconnect_interval(100);
  15095. sse.set_max_reconnect_attempts(1);
  15096. sse.start_async();
  15097. // Wait for connection to establish
  15098. for (int i = 0; i < 20 && !connected.load(); ++i) {
  15099. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  15100. }
  15101. EXPECT_TRUE(connected.load());
  15102. EXPECT_TRUE(sse.is_connected());
  15103. // Signal handler to stop
  15104. handler_running.store(false);
  15105. // Stop SSE client
  15106. sse.stop();
  15107. EXPECT_FALSE(sse.is_connected());
  15108. }
  15109. // Test: SSEClient with custom headers
  15110. TEST_F(SSEIntegrationTest, CustomHeaders) {
  15111. // Setup a server endpoint that checks for custom header
  15112. std::atomic<bool> header_received{false};
  15113. server_->Get("/header-check", [&](const Request &req, Response &res) {
  15114. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  15115. header_received.store(true);
  15116. }
  15117. res.set_chunked_content_provider("text/event-stream",
  15118. [](size_t, DataSink &) { return false; });
  15119. });
  15120. Client client("localhost", get_port());
  15121. Headers headers = {{"X-Custom-Header", "custom-value"}};
  15122. sse::SSEClient sse(client, "/header-check", headers);
  15123. sse.set_max_reconnect_attempts(1);
  15124. sse.start_async();
  15125. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  15126. sse.stop();
  15127. EXPECT_TRUE(header_received.load());
  15128. }
  15129. // Test: Reconnect interval configuration
  15130. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  15131. Client client("localhost", get_port());
  15132. sse::SSEClient sse(client, "/events");
  15133. auto &result = sse.set_reconnect_interval(500);
  15134. // Builder pattern should return reference to self
  15135. EXPECT_EQ(&result, &sse);
  15136. }
  15137. // Test: Max reconnect attempts
  15138. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  15139. // Connect to non-existent port to force reconnects
  15140. Client client("localhost", 59998);
  15141. sse::SSEClient sse(client, "/events");
  15142. std::atomic<int> error_count{0};
  15143. sse.on_error([&](Error) { error_count.fetch_add(1); });
  15144. sse.set_reconnect_interval(50);
  15145. sse.set_max_reconnect_attempts(2);
  15146. auto start = std::chrono::steady_clock::now();
  15147. sse.start(); // Blocking call
  15148. auto end = std::chrono::steady_clock::now();
  15149. // Should have stopped after 2 failed attempts
  15150. EXPECT_GE(error_count.load(), 2);
  15151. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  15152. auto duration =
  15153. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  15154. #ifdef _WIN32
  15155. // Windows is much slower for socket connection failures
  15156. EXPECT_LT(duration.count(), 7000);
  15157. #else
  15158. EXPECT_LT(duration.count(), 1000);
  15159. #endif
  15160. }
  15161. // Test: Multi-line data in integration
  15162. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  15163. // Endpoint with multi-line data
  15164. server_->Get("/multiline-data", [](const Request &, Response &res) {
  15165. res.set_chunked_content_provider(
  15166. "text/event-stream", [](size_t offset, DataSink &sink) {
  15167. if (offset == 0) {
  15168. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  15169. sink.write(event.data(), event.size());
  15170. }
  15171. return false;
  15172. });
  15173. });
  15174. Client client("localhost", get_port());
  15175. sse::SSEClient sse(client, "/multiline-data");
  15176. std::string received_data;
  15177. std::mutex data_mutex;
  15178. sse.on_message([&](const sse::SSEMessage &msg) {
  15179. std::lock_guard<std::mutex> lock(data_mutex);
  15180. received_data = msg.data;
  15181. });
  15182. sse.set_reconnect_interval(100);
  15183. sse.set_max_reconnect_attempts(1);
  15184. sse.start_async();
  15185. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  15186. sse.stop();
  15187. std::lock_guard<std::mutex> lock(data_mutex);
  15188. EXPECT_EQ(received_data, "line1\nline2\nline3");
  15189. }
  15190. // Test: Auto-reconnect after server disconnection
  15191. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  15192. std::atomic<int> connection_count{0};
  15193. std::atomic<int> message_count{0};
  15194. // Endpoint that sends one event and closes, forcing reconnect
  15195. server_->Get("/reconnect-test",
  15196. [&connection_count](const Request &, Response &res) {
  15197. connection_count.fetch_add(1);
  15198. res.set_chunked_content_provider(
  15199. "text/event-stream", [](size_t offset, DataSink &sink) {
  15200. if (offset == 0) {
  15201. std::string event = "data: hello\n\n";
  15202. sink.write(event.data(), event.size());
  15203. }
  15204. return false; // Close connection after sending
  15205. });
  15206. });
  15207. Client client("localhost", get_port());
  15208. sse::SSEClient sse(client, "/reconnect-test");
  15209. sse.on_message([&message_count](const sse::SSEMessage &) {
  15210. message_count.fetch_add(1);
  15211. });
  15212. sse.set_reconnect_interval(100);
  15213. sse.set_max_reconnect_attempts(3);
  15214. sse.start_async();
  15215. // Wait long enough for multiple reconnects
  15216. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  15217. sse.stop();
  15218. // Should have connected multiple times (initial + reconnects)
  15219. EXPECT_GE(connection_count.load(), 2);
  15220. // Should have received messages from multiple connections
  15221. EXPECT_GE(message_count.load(), 2);
  15222. }
  15223. // Test: Last-Event-ID sent on reconnect
  15224. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  15225. std::atomic<int> connection_count{0};
  15226. std::vector<std::string> received_last_event_ids;
  15227. std::mutex id_mutex;
  15228. // Endpoint that checks Last-Event-ID header and sends event with ID
  15229. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  15230. int conn = connection_count.fetch_add(1);
  15231. // Capture the Last-Event-ID header from each connection
  15232. {
  15233. std::lock_guard<std::mutex> lock(id_mutex);
  15234. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  15235. }
  15236. res.set_chunked_content_provider(
  15237. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  15238. if (offset == 0) {
  15239. std::string event =
  15240. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  15241. sink.write(event.data(), event.size());
  15242. }
  15243. return false;
  15244. });
  15245. });
  15246. Client client("localhost", get_port());
  15247. sse::SSEClient sse(client, "/reconnect-with-id");
  15248. sse.set_reconnect_interval(100);
  15249. sse.set_max_reconnect_attempts(3);
  15250. sse.start_async();
  15251. // Wait for at least 2 connections
  15252. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  15253. sse.stop();
  15254. // Verify behavior
  15255. std::lock_guard<std::mutex> lock(id_mutex);
  15256. EXPECT_GE(received_last_event_ids.size(), 2u);
  15257. // First connection should have no Last-Event-ID
  15258. if (!received_last_event_ids.empty()) {
  15259. EXPECT_EQ(received_last_event_ids[0], "");
  15260. }
  15261. // Second connection should have Last-Event-ID from first connection
  15262. if (received_last_event_ids.size() >= 2) {
  15263. EXPECT_EQ(received_last_event_ids[1], "event-0");
  15264. }
  15265. }
  15266. // Test: set_headers updates headers used on reconnect
  15267. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  15268. std::vector<std::string> received_tokens;
  15269. std::mutex token_mutex;
  15270. // Endpoint that captures Authorization header
  15271. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  15272. {
  15273. std::lock_guard<std::mutex> lock(token_mutex);
  15274. received_tokens.push_back(req.get_header_value("Authorization"));
  15275. }
  15276. res.set_chunked_content_provider(
  15277. "text/event-stream", [](size_t offset, DataSink &sink) {
  15278. if (offset == 0) {
  15279. std::string event = "data: hello\n\n";
  15280. sink.write(event.data(), event.size());
  15281. }
  15282. return false; // Close connection to trigger reconnect
  15283. });
  15284. });
  15285. Client client("localhost", get_port());
  15286. Headers headers = {{"Authorization", "Bearer old-token"}};
  15287. sse::SSEClient sse(client, "/auth-check", headers);
  15288. // Update headers on each successful connection
  15289. sse.on_open(
  15290. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  15291. sse.set_reconnect_interval(100);
  15292. sse.set_max_reconnect_attempts(3);
  15293. sse.start_async();
  15294. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  15295. sse.stop();
  15296. std::lock_guard<std::mutex> lock(token_mutex);
  15297. ASSERT_GE(received_tokens.size(), 2u);
  15298. // First connection uses original header
  15299. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  15300. // Second connection uses updated header from set_headers
  15301. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  15302. }
  15303. // Test: 401 allows reconnection (so on_error can refresh headers)
  15304. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  15305. std::atomic<int> connection_count{0};
  15306. // Endpoint: returns 401 on first attempt, 200 on second
  15307. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  15308. int conn = connection_count.fetch_add(1);
  15309. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  15310. res.status = StatusCode::Unauthorized_401;
  15311. res.set_content("Unauthorized", "text/plain");
  15312. return;
  15313. }
  15314. res.set_chunked_content_provider(
  15315. "text/event-stream", [](size_t offset, DataSink &sink) {
  15316. if (offset == 0) {
  15317. std::string event = "data: authenticated\n\n";
  15318. sink.write(event.data(), event.size());
  15319. }
  15320. return false;
  15321. });
  15322. });
  15323. Client client("localhost", get_port());
  15324. Headers headers = {{"Authorization", "Bearer expired"}};
  15325. sse::SSEClient sse(client, "/auth-retry", headers);
  15326. std::atomic<bool> message_received{false};
  15327. // Refresh token on error
  15328. sse.on_error(
  15329. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  15330. sse.on_message([&](const sse::SSEMessage &msg) {
  15331. if (msg.data == "authenticated") { message_received.store(true); }
  15332. });
  15333. sse.set_reconnect_interval(100);
  15334. sse.set_max_reconnect_attempts(3);
  15335. sse.start_async();
  15336. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  15337. sse.stop();
  15338. // Should have reconnected after 401 and succeeded with new token
  15339. EXPECT_GE(connection_count.load(), 2);
  15340. EXPECT_TRUE(message_received.load());
  15341. }
  15342. TEST(Issue2318Test, EmptyHostString) {
  15343. {
  15344. httplib::Client cli_empty("", PORT);
  15345. auto res = cli_empty.Get("/");
  15346. ASSERT_FALSE(res);
  15347. EXPECT_EQ(httplib::Error::Connection, res.error());
  15348. }
  15349. {
  15350. httplib::Client cli(" ", PORT);
  15351. auto res = cli.Get("/");
  15352. ASSERT_FALSE(res);
  15353. EXPECT_EQ(httplib::Error::Connection, res.error());
  15354. }
  15355. }
  15356. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  15357. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  15358. Server svr;
  15359. // Set a small payload limit (1KB)
  15360. svr.set_payload_max_length(1024);
  15361. svr.Post("/test", [&](const Request &req, Response &res) {
  15362. res.set_content("Body size: " + std::to_string(req.body.size()),
  15363. "text/plain");
  15364. });
  15365. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15366. auto se = detail::scope_exit([&] {
  15367. svr.stop();
  15368. listen_thread.join();
  15369. });
  15370. svr.wait_until_ready();
  15371. // Create data that compresses well but exceeds limit when decompressed
  15372. // 8KB of repeated null bytes compresses to a very small size
  15373. std::string original_data(8 * 1024, '\0');
  15374. // Compress the data using gzip
  15375. std::string compressed_data;
  15376. detail::gzip_compressor compressor;
  15377. compressor.compress(original_data.data(), original_data.size(), true,
  15378. [&](const char *data, size_t size) {
  15379. compressed_data.append(data, size);
  15380. return true;
  15381. });
  15382. // Verify compression worked (compressed should be much smaller)
  15383. ASSERT_LT(compressed_data.size(), original_data.size());
  15384. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  15385. // Send compressed data with Content-Encoding: gzip
  15386. Client cli(HOST, PORT);
  15387. Headers headers = {{"Content-Encoding", "gzip"}};
  15388. auto res =
  15389. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  15390. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  15391. ASSERT_TRUE(res);
  15392. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  15393. }
  15394. #endif
  15395. // ============================================================================
  15396. // OpenSSL-Specific Tests
  15397. // ============================================================================
  15398. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  15399. X509 *readCertificate(const std::string &strFileName) {
  15400. std::ifstream inStream(strFileName);
  15401. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  15402. std::istreambuf_iterator<char>());
  15403. if (strCertPEM.empty()) return (nullptr);
  15404. BIO *pbCert = BIO_new(BIO_s_mem());
  15405. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  15406. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  15407. BIO_free(pbCert);
  15408. return (pCert);
  15409. }
  15410. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  15411. std::ifstream inStream(strFileName);
  15412. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  15413. std::istreambuf_iterator<char>());
  15414. if (strPrivateKeyPEM.empty()) return (nullptr);
  15415. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  15416. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  15417. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  15418. BIO_free(pbPrivKey);
  15419. return (pPrivateKey);
  15420. }
  15421. TEST(BindServerTest, UpdateCerts) {
  15422. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  15423. int port = svr.bind_to_any_port("0.0.0.0");
  15424. ASSERT_TRUE(svr.is_valid());
  15425. ASSERT_TRUE(port > 0);
  15426. X509 *cert = readCertificate(SERVER_CERT_FILE);
  15427. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  15428. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  15429. ASSERT_TRUE(cert != nullptr);
  15430. ASSERT_TRUE(ca_cert != nullptr);
  15431. ASSERT_TRUE(key != nullptr);
  15432. X509_STORE *cert_store = X509_STORE_new();
  15433. X509_STORE_add_cert(cert_store, ca_cert);
  15434. // svr.update_certs(cert, key, cert_store); // deprecated
  15435. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  15436. CLIENT_CA_CERT_FILE);
  15437. ASSERT_TRUE(svr.is_valid());
  15438. svr.stop();
  15439. X509_STORE_free(cert_store);
  15440. X509_free(cert);
  15441. X509_free(ca_cert);
  15442. EVP_PKEY_free(key);
  15443. }
  15444. // Test that update_certs() updates client CA list correctly
  15445. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  15446. // Start with file-based constructor
  15447. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15448. ASSERT_TRUE(svr.is_valid());
  15449. // Initially no client CA list should be set
  15450. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  15451. ASSERT_TRUE(ssl_ctx != nullptr);
  15452. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  15453. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  15454. EXPECT_EQ(0, count_before);
  15455. // Now update with client CA (PEM string)
  15456. std::string cert_pem, key_pem, ca_pem;
  15457. read_file(SERVER_CERT_FILE, cert_pem);
  15458. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  15459. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  15460. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  15461. ASSERT_TRUE(svr.is_valid());
  15462. // Now client CA list should be set
  15463. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  15464. ASSERT_TRUE(ca_list_after != nullptr);
  15465. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  15466. }
  15467. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  15468. // Test that the file-path SSLServer constructor properly sets the client CA
  15469. // list that is sent to clients during the TLS handshake (CertificateRequest)
  15470. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  15471. ASSERT_TRUE(svr.is_valid());
  15472. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  15473. ASSERT_TRUE(ssl_ctx != nullptr);
  15474. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  15475. ASSERT_TRUE(ca_list != nullptr);
  15476. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  15477. }
  15478. #endif
  15479. // ============================================================================
  15480. // MbedTLS-Specific Tests
  15481. // ============================================================================
  15482. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  15483. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  15484. using namespace httplib::tls;
  15485. // Track if callback was invoked
  15486. bool callback_invoked = false;
  15487. // The callback receives void* ctx which is actually MbedTlsContext*
  15488. // We can access the mbedtls_ssl_config via the context
  15489. auto setup_callback = [&callback_invoked](void *ctx) {
  15490. callback_invoked = true;
  15491. // Cast to MbedTlsContext* to access the ssl config
  15492. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  15493. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  15494. // Use static variables to hold certificate data (simplified for test)
  15495. static mbedtls_x509_crt own_cert;
  15496. static mbedtls_pk_context own_key;
  15497. static mbedtls_x509_crt ca_chain;
  15498. static bool initialized = false;
  15499. if (!initialized) {
  15500. mbedtls_x509_crt_init(&own_cert);
  15501. mbedtls_pk_init(&own_key);
  15502. mbedtls_x509_crt_init(&ca_chain);
  15503. // Load server certificate
  15504. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  15505. return false;
  15506. }
  15507. // Load server private key.
  15508. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  15509. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  15510. #if MBEDTLS_VERSION_MAJOR == 3
  15511. ,
  15512. mbedtls_ctr_drbg_random, nullptr
  15513. #endif
  15514. ) != 0) {
  15515. return false;
  15516. }
  15517. // Load CA chain for client verification
  15518. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  15519. return false;
  15520. }
  15521. initialized = true;
  15522. }
  15523. // Configure the SSL config
  15524. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  15525. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  15526. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  15527. // Set minimum TLS version using mbedTLS native API
  15528. #if MBEDTLS_VERSION_MAJOR >= 3
  15529. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  15530. #else
  15531. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  15532. MBEDTLS_SSL_MINOR_VERSION_3);
  15533. #endif
  15534. return true;
  15535. };
  15536. SSLServer svr(setup_callback);
  15537. ASSERT_TRUE(svr.is_valid());
  15538. ASSERT_TRUE(callback_invoked);
  15539. svr.Get("/test", [&](const Request &req, Response &res) {
  15540. res.set_content("test", "text/plain");
  15541. auto cert = req.peer_cert();
  15542. ASSERT_TRUE(static_cast<bool>(cert));
  15543. auto common_name = cert.subject_cn();
  15544. EXPECT_EQ("Common Name", common_name);
  15545. });
  15546. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15547. auto se = detail::scope_exit([&] {
  15548. svr.stop();
  15549. t.join();
  15550. ASSERT_FALSE(svr.is_running());
  15551. });
  15552. svr.wait_until_ready();
  15553. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15554. cli.enable_server_certificate_verification(false);
  15555. cli.set_connection_timeout(30);
  15556. auto res = cli.Get("/test");
  15557. ASSERT_TRUE(res);
  15558. ASSERT_EQ(StatusCode::OK_200, res->status);
  15559. }
  15560. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  15561. // context (owning mbedtls_ssl_config) before shutting down a still-open
  15562. // keep-alive SSL session, which reads through that config in
  15563. // mbedtls_ssl_close_notify.
  15564. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  15565. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15566. ASSERT_TRUE(svr.is_valid());
  15567. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  15568. res.set_content("test", "text/plain");
  15569. });
  15570. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15571. auto se = detail::scope_exit([&] {
  15572. svr.stop();
  15573. t.join();
  15574. ASSERT_FALSE(svr.is_running());
  15575. });
  15576. svr.wait_until_ready();
  15577. {
  15578. SSLClient cli(HOST, PORT);
  15579. cli.enable_server_certificate_verification(false);
  15580. cli.set_keep_alive(true);
  15581. auto res = cli.Get("/test");
  15582. ASSERT_TRUE(res);
  15583. ASSERT_EQ(StatusCode::OK_200, res->status);
  15584. // cli is destructed here with the keep-alive SSL session still open.
  15585. }
  15586. }
  15587. #endif
  15588. // WebSocket Tests
  15589. TEST(WebSocketTest, RSVBitsMustBeZero) {
  15590. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  15591. // defining the meaning of these bits has been negotiated.
  15592. auto make_frame = [](uint8_t first_byte) {
  15593. std::string frame;
  15594. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  15595. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  15596. frame += "Hello";
  15597. return frame;
  15598. };
  15599. // RSV1 set (0x40)
  15600. {
  15601. detail::BufferStream strm;
  15602. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  15603. ws::Opcode opcode;
  15604. std::string payload;
  15605. bool fin;
  15606. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15607. false, 1024));
  15608. }
  15609. // RSV2 set (0x20)
  15610. {
  15611. detail::BufferStream strm;
  15612. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  15613. ws::Opcode opcode;
  15614. std::string payload;
  15615. bool fin;
  15616. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15617. false, 1024));
  15618. }
  15619. // RSV3 set (0x10)
  15620. {
  15621. detail::BufferStream strm;
  15622. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  15623. ws::Opcode opcode;
  15624. std::string payload;
  15625. bool fin;
  15626. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15627. false, 1024));
  15628. }
  15629. // No RSV bits set - should succeed
  15630. {
  15631. detail::BufferStream strm;
  15632. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  15633. ws::Opcode opcode;
  15634. std::string payload;
  15635. bool fin;
  15636. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15637. false, 1024));
  15638. EXPECT_EQ(ws::Opcode::Text, opcode);
  15639. EXPECT_EQ("Hello", payload);
  15640. EXPECT_TRUE(fin);
  15641. }
  15642. }
  15643. TEST(WebSocketTest, ControlFrameValidation) {
  15644. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  15645. // payload length <= 125.
  15646. // Ping with FIN=0 - must be rejected
  15647. {
  15648. detail::BufferStream strm;
  15649. std::string frame;
  15650. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  15651. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  15652. strm.write(frame.data(), frame.size());
  15653. ws::Opcode opcode;
  15654. std::string payload;
  15655. bool fin;
  15656. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15657. false, 1024));
  15658. }
  15659. // Close with FIN=0 - must be rejected
  15660. {
  15661. detail::BufferStream strm;
  15662. std::string frame;
  15663. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  15664. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  15665. strm.write(frame.data(), frame.size());
  15666. ws::Opcode opcode;
  15667. std::string payload;
  15668. bool fin;
  15669. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15670. false, 1024));
  15671. }
  15672. // Ping with payload_len=126 (extended length) - must be rejected
  15673. {
  15674. detail::BufferStream strm;
  15675. std::string frame;
  15676. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  15677. frame += static_cast<char>(126); // payload_len=126 (>125)
  15678. frame += static_cast<char>(0x00); // extended length high byte
  15679. frame += static_cast<char>(126); // extended length low byte
  15680. frame += std::string(126, 'x');
  15681. strm.write(frame.data(), frame.size());
  15682. ws::Opcode opcode;
  15683. std::string payload;
  15684. bool fin;
  15685. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15686. false, 1024));
  15687. }
  15688. // Ping with FIN=1 and payload_len=125 - should succeed
  15689. {
  15690. detail::BufferStream strm;
  15691. std::string frame;
  15692. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  15693. frame += static_cast<char>(125); // payload_len=125
  15694. frame += std::string(125, 'x');
  15695. strm.write(frame.data(), frame.size());
  15696. ws::Opcode opcode;
  15697. std::string payload;
  15698. bool fin;
  15699. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15700. false, 1024));
  15701. EXPECT_EQ(ws::Opcode::Ping, opcode);
  15702. EXPECT_EQ(125u, payload.size());
  15703. EXPECT_TRUE(fin);
  15704. }
  15705. }
  15706. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  15707. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  15708. // length MUST be 0.
  15709. // MSB set - must be rejected
  15710. {
  15711. detail::BufferStream strm;
  15712. std::string frame;
  15713. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  15714. frame += static_cast<char>(127); // 64-bit extended length
  15715. frame += static_cast<char>(0x80); // MSB set (invalid)
  15716. frame += std::string(7, '\0'); // remaining 7 bytes of length
  15717. strm.write(frame.data(), frame.size());
  15718. ws::Opcode opcode;
  15719. std::string payload;
  15720. bool fin;
  15721. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15722. false, 1024));
  15723. }
  15724. // MSB clear - should pass length parsing (will be rejected by max_len,
  15725. // but that's a different check; use a small length to verify)
  15726. {
  15727. detail::BufferStream strm;
  15728. std::string frame;
  15729. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  15730. frame += static_cast<char>(127); // 64-bit extended length
  15731. frame += std::string(7, '\0'); // high bytes = 0
  15732. frame += static_cast<char>(0x03); // length = 3
  15733. frame += "abc";
  15734. strm.write(frame.data(), frame.size());
  15735. ws::Opcode opcode;
  15736. std::string payload;
  15737. bool fin;
  15738. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15739. false, 1024));
  15740. EXPECT_EQ(ws::Opcode::Text, opcode);
  15741. EXPECT_EQ("abc", payload);
  15742. }
  15743. }
  15744. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  15745. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  15746. // Valid UTF-8
  15747. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  15748. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  15749. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  15750. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  15751. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  15752. // Invalid UTF-8
  15753. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  15754. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  15755. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  15756. EXPECT_FALSE(
  15757. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  15758. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  15759. }
  15760. TEST(WebSocketTest, ConnectAndDisconnect) {
  15761. Server svr;
  15762. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  15763. std::string msg;
  15764. while (ws.read(msg)) {}
  15765. });
  15766. auto port = svr.bind_to_any_port(HOST);
  15767. std::thread t([&]() { svr.listen_after_bind(); });
  15768. svr.wait_until_ready();
  15769. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  15770. ASSERT_TRUE(client.connect());
  15771. EXPECT_TRUE(client.is_open());
  15772. client.close();
  15773. EXPECT_FALSE(client.is_open());
  15774. svr.stop();
  15775. t.join();
  15776. }
  15777. TEST(WebSocketTest, ValidURL) {
  15778. ws::WebSocketClient ws1("ws://localhost:8080/path");
  15779. EXPECT_TRUE(ws1.is_valid());
  15780. ws::WebSocketClient ws2("ws://example.com/path");
  15781. EXPECT_TRUE(ws2.is_valid());
  15782. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  15783. EXPECT_TRUE(ws3.is_valid());
  15784. #ifdef CPPHTTPLIB_SSL_ENABLED
  15785. ws::WebSocketClient wss1("wss://example.com/path");
  15786. EXPECT_TRUE(wss1.is_valid());
  15787. ws::WebSocketClient wss2("wss://example.com:443/path");
  15788. EXPECT_TRUE(wss2.is_valid());
  15789. #endif
  15790. }
  15791. TEST(WebSocketTest, InvalidURL) {
  15792. // No scheme
  15793. ws::WebSocketClient ws1("localhost:8080/path");
  15794. EXPECT_FALSE(ws1.is_valid());
  15795. // No path
  15796. ws::WebSocketClient ws2("ws://localhost:8080");
  15797. EXPECT_FALSE(ws2.is_valid());
  15798. // Empty string
  15799. ws::WebSocketClient ws3("");
  15800. EXPECT_FALSE(ws3.is_valid());
  15801. // Missing host
  15802. ws::WebSocketClient ws4("ws://:8080/path");
  15803. EXPECT_FALSE(ws4.is_valid());
  15804. // Port number overflow — should not crash
  15805. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  15806. EXPECT_FALSE(ws5.is_valid());
  15807. // Port out of range
  15808. ws::WebSocketClient ws6("ws://localhost:99999/path");
  15809. EXPECT_FALSE(ws6.is_valid());
  15810. }
  15811. TEST(WebSocketTest, UnsupportedScheme) {
  15812. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15813. ws::WebSocketClient ws1("http://localhost:8080/path");
  15814. EXPECT_FALSE(ws1.is_valid());
  15815. ws::WebSocketClient ws2("https://localhost:8080/path");
  15816. EXPECT_FALSE(ws2.is_valid());
  15817. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  15818. EXPECT_FALSE(ws3.is_valid());
  15819. #else
  15820. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  15821. std::invalid_argument);
  15822. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  15823. std::invalid_argument);
  15824. #endif
  15825. }
  15826. TEST(WebSocketTest, ConnectWhenInvalid) {
  15827. ws::WebSocketClient ws("not a valid url");
  15828. EXPECT_FALSE(ws.is_valid());
  15829. EXPECT_FALSE(ws.connect());
  15830. }
  15831. TEST(WebSocketTest, DefaultPort) {
  15832. ws::WebSocketClient ws1("ws://example.com/path");
  15833. EXPECT_TRUE(ws1.is_valid());
  15834. // ws:// defaults to port 80 (verified by successful parse)
  15835. #ifdef CPPHTTPLIB_SSL_ENABLED
  15836. ws::WebSocketClient ws2("wss://example.com/path");
  15837. EXPECT_TRUE(ws2.is_valid());
  15838. // wss:// defaults to port 443 (verified by successful parse)
  15839. #endif
  15840. }
  15841. TEST(WebSocketTest, IPv6LiteralAddress) {
  15842. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  15843. EXPECT_TRUE(ws1.is_valid());
  15844. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  15845. EXPECT_TRUE(ws2.is_valid());
  15846. }
  15847. TEST(WebSocketTest, ComplexPath) {
  15848. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  15849. EXPECT_TRUE(ws1.is_valid());
  15850. ws::WebSocketClient ws2("ws://localhost:8080/");
  15851. EXPECT_TRUE(ws2.is_valid());
  15852. }
  15853. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  15854. Server svr;
  15855. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  15856. std::string msg;
  15857. while (ws.read(msg)) {}
  15858. });
  15859. auto port = svr.bind_to_any_port(HOST);
  15860. std::thread t([&]() { svr.listen_after_bind(); });
  15861. svr.wait_until_ready();
  15862. auto another_host = "example.com";
  15863. auto wrong_ip = "192.0.2.1";
  15864. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  15865. client.set_hostname_addr_map({{another_host, wrong_ip}});
  15866. ASSERT_TRUE(client.connect());
  15867. EXPECT_TRUE(client.is_open());
  15868. client.close();
  15869. svr.stop();
  15870. t.join();
  15871. }
  15872. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  15873. Server svr;
  15874. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  15875. std::string msg;
  15876. while (ws.read(msg)) {}
  15877. });
  15878. auto port = svr.bind_to_any_port(HOST);
  15879. std::thread t([&]() { svr.listen_after_bind(); });
  15880. svr.wait_until_ready();
  15881. auto wrong_ip = "192.0.2.1";
  15882. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  15883. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  15884. client.set_connection_timeout(1);
  15885. client.set_read_timeout(1);
  15886. client.set_write_timeout(1);
  15887. EXPECT_FALSE(client.connect());
  15888. EXPECT_FALSE(client.is_open());
  15889. svr.stop();
  15890. t.join();
  15891. }
  15892. class WebSocketIntegrationTest : public ::testing::Test {
  15893. protected:
  15894. void SetUp() override {
  15895. server_ = httplib::detail::make_unique<Server>();
  15896. setup_server();
  15897. start_server();
  15898. }
  15899. void TearDown() override {
  15900. server_->stop();
  15901. if (server_thread_.joinable()) { server_thread_.join(); }
  15902. }
  15903. void setup_server() {
  15904. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  15905. std::string msg;
  15906. ws::ReadResult ret;
  15907. while ((ret = ws.read(msg))) {
  15908. if (ret == ws::Binary) {
  15909. ws.send(msg.data(), msg.size());
  15910. } else {
  15911. ws.send(msg);
  15912. }
  15913. }
  15914. });
  15915. server_->WebSocket("/ws-echo-string",
  15916. [](const Request &, ws::WebSocket &ws) {
  15917. std::string msg;
  15918. while (ws.read(msg)) {
  15919. ws.send("echo: " + msg);
  15920. }
  15921. });
  15922. server_->WebSocket(
  15923. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  15924. // Echo back request metadata
  15925. ws.send("path:" + req.path);
  15926. ws.send("header:" + req.get_header_value("X-Test-Header"));
  15927. std::string msg;
  15928. while (ws.read(msg)) {}
  15929. });
  15930. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  15931. std::string msg;
  15932. ws.read(msg); // wait for a message
  15933. ws.close();
  15934. });
  15935. server_->WebSocket("/ws-close-status",
  15936. [](const Request &, ws::WebSocket &ws) {
  15937. std::string msg;
  15938. ws.read(msg); // wait for a message
  15939. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  15940. });
  15941. server_->WebSocket(
  15942. "/ws-subprotocol",
  15943. [](const Request &, ws::WebSocket &ws) {
  15944. std::string msg;
  15945. while (ws.read(msg)) {
  15946. ws.send(msg);
  15947. }
  15948. },
  15949. [](const std::vector<std::string> &protocols) -> std::string {
  15950. for (const auto &p : protocols) {
  15951. if (p == "graphql-ws") { return p; }
  15952. }
  15953. return "";
  15954. });
  15955. }
  15956. void start_server() {
  15957. port_ = server_->bind_to_any_port(HOST);
  15958. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  15959. server_->wait_until_ready();
  15960. }
  15961. std::unique_ptr<Server> server_;
  15962. std::thread server_thread_;
  15963. int port_ = 0;
  15964. };
  15965. TEST_F(WebSocketIntegrationTest, TextEcho) {
  15966. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15967. "/ws-echo");
  15968. ASSERT_TRUE(client.connect());
  15969. ASSERT_TRUE(client.is_open());
  15970. ASSERT_TRUE(client.send("Hello WebSocket"));
  15971. std::string msg;
  15972. EXPECT_EQ(ws::Text, client.read(msg));
  15973. EXPECT_EQ("Hello WebSocket", msg);
  15974. client.close();
  15975. }
  15976. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  15977. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15978. "/ws-echo");
  15979. ASSERT_TRUE(client.connect());
  15980. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  15981. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  15982. std::string msg;
  15983. EXPECT_EQ(ws::Binary, client.read(msg));
  15984. EXPECT_EQ(binary_data, msg);
  15985. client.close();
  15986. }
  15987. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  15988. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15989. "/ws-echo");
  15990. ASSERT_TRUE(client.connect());
  15991. for (int i = 0; i < 10; i++) {
  15992. auto text = "message " + std::to_string(i);
  15993. ASSERT_TRUE(client.send(text));
  15994. std::string msg;
  15995. ASSERT_TRUE(client.read(msg));
  15996. EXPECT_EQ(text, msg);
  15997. }
  15998. client.close();
  15999. }
  16000. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  16001. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16002. "/ws-close");
  16003. ASSERT_TRUE(client.connect());
  16004. // Send a message to trigger the server to close
  16005. ASSERT_TRUE(client.send("trigger close"));
  16006. // The server will close, so read should return false
  16007. std::string msg;
  16008. EXPECT_FALSE(client.read(msg));
  16009. EXPECT_FALSE(client.is_open());
  16010. }
  16011. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  16012. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16013. "/ws-echo");
  16014. ASSERT_TRUE(client.connect());
  16015. // 128KB message
  16016. std::string large_data(128 * 1024, 'X');
  16017. ASSERT_TRUE(client.send(large_data));
  16018. std::string msg;
  16019. ASSERT_TRUE(client.read(msg));
  16020. EXPECT_EQ(large_data, msg);
  16021. client.close();
  16022. }
  16023. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  16024. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16025. "/ws-echo");
  16026. ASSERT_TRUE(client.connect());
  16027. const int num_threads = 4;
  16028. std::vector<std::thread> threads;
  16029. std::atomic<int> send_count{0};
  16030. for (int t = 0; t < num_threads; t++) {
  16031. threads.emplace_back([&client, &send_count, t]() {
  16032. for (int i = 0; i < 5; i++) {
  16033. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  16034. if (client.send(text)) { send_count++; }
  16035. }
  16036. });
  16037. }
  16038. for (auto &th : threads) {
  16039. th.join();
  16040. }
  16041. int received = 0;
  16042. std::string msg;
  16043. while (received < send_count.load()) {
  16044. if (!client.read(msg)) { break; }
  16045. received++;
  16046. }
  16047. EXPECT_EQ(send_count.load(), received);
  16048. client.close();
  16049. }
  16050. TEST_F(WebSocketIntegrationTest, ReadString) {
  16051. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16052. "/ws-echo-string");
  16053. ASSERT_TRUE(client.connect());
  16054. ASSERT_TRUE(client.send("hello"));
  16055. std::string msg;
  16056. ASSERT_TRUE(client.read(msg));
  16057. EXPECT_EQ("echo: hello", msg);
  16058. ASSERT_TRUE(client.send("world"));
  16059. ASSERT_TRUE(client.read(msg));
  16060. EXPECT_EQ("echo: world", msg);
  16061. client.close();
  16062. }
  16063. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  16064. Headers headers = {{"X-Test-Header", "test-value"}};
  16065. ws::WebSocketClient client(
  16066. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  16067. ASSERT_TRUE(client.connect());
  16068. std::string msg;
  16069. ASSERT_TRUE(client.read(msg));
  16070. EXPECT_EQ("path:/ws-request-info", msg);
  16071. ASSERT_TRUE(client.read(msg));
  16072. EXPECT_EQ("header:test-value", msg);
  16073. client.close();
  16074. }
  16075. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  16076. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16077. "/ws-echo");
  16078. client.set_read_timeout(1, 0); // 1 second
  16079. ASSERT_TRUE(client.connect());
  16080. // Don't send anything — server echo handler waits for a message,
  16081. // so read() should time out and return false.
  16082. std::string msg;
  16083. EXPECT_FALSE(client.read(msg));
  16084. }
  16085. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  16086. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16087. "/ws-echo");
  16088. client.set_read_timeout(5, 0);
  16089. ASSERT_TRUE(client.connect());
  16090. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  16091. // The server should reject it and close the connection.
  16092. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  16093. client.send(oversized);
  16094. // The server's read() should have failed due to payload limit,
  16095. // so our read() should return false (connection closed).
  16096. std::string msg;
  16097. EXPECT_FALSE(client.read(msg));
  16098. }
  16099. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  16100. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16101. "/ws-echo");
  16102. client.set_read_timeout(10, 0);
  16103. ASSERT_TRUE(client.connect());
  16104. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  16105. // This should succeed.
  16106. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  16107. ASSERT_TRUE(client.send(at_limit));
  16108. std::string msg;
  16109. ASSERT_TRUE(client.read(msg));
  16110. EXPECT_EQ(at_limit.size(), msg.size());
  16111. client.close();
  16112. }
  16113. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  16114. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16115. "/nonexistent");
  16116. EXPECT_FALSE(client.connect());
  16117. EXPECT_FALSE(client.is_open());
  16118. }
  16119. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  16120. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16121. "/ws-echo");
  16122. ASSERT_TRUE(client.connect());
  16123. ASSERT_TRUE(client.send(""));
  16124. std::string msg;
  16125. EXPECT_EQ(ws::Text, client.read(msg));
  16126. EXPECT_EQ("", msg);
  16127. client.close();
  16128. }
  16129. TEST_F(WebSocketIntegrationTest, Reconnect) {
  16130. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16131. "/ws-echo");
  16132. // First connection
  16133. ASSERT_TRUE(client.connect());
  16134. ASSERT_TRUE(client.send("first"));
  16135. std::string msg;
  16136. ASSERT_TRUE(client.read(msg));
  16137. EXPECT_EQ("first", msg);
  16138. client.close();
  16139. EXPECT_FALSE(client.is_open());
  16140. // Reconnect using the same client object
  16141. ASSERT_TRUE(client.connect());
  16142. ASSERT_TRUE(client.is_open());
  16143. ASSERT_TRUE(client.send("second"));
  16144. ASSERT_TRUE(client.read(msg));
  16145. EXPECT_EQ("second", msg);
  16146. client.close();
  16147. }
  16148. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  16149. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16150. "/ws-close-status");
  16151. ASSERT_TRUE(client.connect());
  16152. // Trigger the server to close with GoingAway status
  16153. ASSERT_TRUE(client.send("trigger"));
  16154. // read() should return false after receiving the close frame
  16155. std::string msg;
  16156. EXPECT_FALSE(client.read(msg));
  16157. EXPECT_FALSE(client.is_open());
  16158. }
  16159. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  16160. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16161. "/ws-echo");
  16162. ASSERT_TRUE(client.connect());
  16163. client.close(ws::CloseStatus::GoingAway, "client leaving");
  16164. EXPECT_FALSE(client.is_open());
  16165. }
  16166. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  16167. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  16168. ws::WebSocketClient client(
  16169. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  16170. ASSERT_TRUE(client.connect());
  16171. // Server should have selected graphql-ws
  16172. EXPECT_EQ("graphql-ws", client.subprotocol());
  16173. client.close();
  16174. }
  16175. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  16176. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  16177. ws::WebSocketClient client(
  16178. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  16179. ASSERT_TRUE(client.connect());
  16180. // Server should not have selected any subprotocol
  16181. EXPECT_TRUE(client.subprotocol().empty());
  16182. client.close();
  16183. }
  16184. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  16185. // Connect without requesting any subprotocol
  16186. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16187. "/ws-subprotocol");
  16188. ASSERT_TRUE(client.connect());
  16189. EXPECT_TRUE(client.subprotocol().empty());
  16190. client.close();
  16191. }
  16192. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  16193. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16194. "/ws-echo");
  16195. client.set_tcp_nodelay(true);
  16196. client.set_connection_timeout(3, 0);
  16197. bool socket_options_called = false;
  16198. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  16199. ASSERT_TRUE(client.connect());
  16200. ASSERT_TRUE(client.is_open());
  16201. EXPECT_TRUE(socket_options_called);
  16202. ASSERT_TRUE(client.send("hello"));
  16203. std::string msg;
  16204. auto result = client.read(msg);
  16205. EXPECT_EQ(result, ws::ReadResult::Text);
  16206. EXPECT_EQ(msg, "hello");
  16207. client.close();
  16208. }
  16209. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  16210. Server svr;
  16211. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  16212. if (!req.has_header("Authorization")) {
  16213. res.status = StatusCode::Unauthorized_401;
  16214. res.set_content("Unauthorized", "text/plain");
  16215. return Server::HandlerResponse::Handled;
  16216. }
  16217. return Server::HandlerResponse::Unhandled;
  16218. });
  16219. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  16220. std::string msg;
  16221. while (ws.read(msg)) {
  16222. ws.send(msg);
  16223. }
  16224. });
  16225. auto port = svr.bind_to_any_port("localhost");
  16226. std::thread t([&]() { svr.listen_after_bind(); });
  16227. svr.wait_until_ready();
  16228. // Without Authorization header - should be rejected before upgrade
  16229. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  16230. EXPECT_FALSE(client1.connect());
  16231. // With Authorization header - should succeed
  16232. Headers headers = {{"Authorization", "Bearer token123"}};
  16233. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  16234. headers);
  16235. ASSERT_TRUE(client2.connect());
  16236. ASSERT_TRUE(client2.send("hello"));
  16237. std::string msg;
  16238. ASSERT_TRUE(client2.read(msg));
  16239. EXPECT_EQ("hello", msg);
  16240. client2.close();
  16241. svr.stop();
  16242. t.join();
  16243. }
  16244. TEST(WebSocketTest, QueryStringInHandshake) {
  16245. Server svr;
  16246. std::mutex mtx;
  16247. std::string received_target;
  16248. std::string received_token;
  16249. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  16250. {
  16251. std::lock_guard<std::mutex> lock(mtx);
  16252. received_target = req.target;
  16253. if (req.has_param("token")) {
  16254. received_token = req.get_param_value("token");
  16255. }
  16256. }
  16257. std::string msg;
  16258. while (ws.read(msg)) {
  16259. ws.send(msg);
  16260. }
  16261. });
  16262. auto port = svr.bind_to_any_port("localhost");
  16263. std::thread t([&]() { svr.listen_after_bind(); });
  16264. svr.wait_until_ready();
  16265. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  16266. "/ws?token=ABC&session=123");
  16267. ASSERT_TRUE(client.connect());
  16268. // Round-trip ensures the handler has run and captured the request.
  16269. ASSERT_TRUE(client.send("hello"));
  16270. std::string msg;
  16271. ASSERT_TRUE(client.read(msg));
  16272. EXPECT_EQ("hello", msg);
  16273. client.close();
  16274. {
  16275. std::lock_guard<std::mutex> lock(mtx);
  16276. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  16277. EXPECT_EQ("ABC", received_token);
  16278. }
  16279. svr.stop();
  16280. t.join();
  16281. }
  16282. TEST(WebSocketTest, HostHeaderInHandshake) {
  16283. Server svr;
  16284. std::mutex mtx;
  16285. std::string received_host;
  16286. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  16287. {
  16288. std::lock_guard<std::mutex> lock(mtx);
  16289. received_host = req.get_header_value("Host");
  16290. }
  16291. std::string msg;
  16292. while (ws.read(msg)) {
  16293. ws.send(msg);
  16294. }
  16295. });
  16296. auto port = svr.bind_to_any_port("localhost");
  16297. std::thread t([&]() { svr.listen_after_bind(); });
  16298. svr.wait_until_ready();
  16299. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  16300. ASSERT_TRUE(client.connect());
  16301. // Round-trip ensures the handler has run and captured the request.
  16302. ASSERT_TRUE(client.send("hello"));
  16303. std::string msg;
  16304. ASSERT_TRUE(client.read(msg));
  16305. client.close();
  16306. {
  16307. std::lock_guard<std::mutex> lock(mtx);
  16308. // Non-default port must be present in the Host header. Default ports
  16309. // (80/443) are omitted; that logic is covered by
  16310. // MakeHostAndPortStringTest.
  16311. EXPECT_EQ("localhost:" + std::to_string(port), received_host);
  16312. }
  16313. svr.stop();
  16314. t.join();
  16315. }
  16316. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  16317. class WebSocketSSLIntegrationTest : public ::testing::Test {
  16318. protected:
  16319. void SetUp() override {
  16320. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  16321. SERVER_PRIVATE_KEY_FILE);
  16322. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  16323. std::string msg;
  16324. ws::ReadResult ret;
  16325. while ((ret = ws.read(msg))) {
  16326. if (ret == ws::Binary) {
  16327. ws.send(msg.data(), msg.size());
  16328. } else {
  16329. ws.send(msg);
  16330. }
  16331. }
  16332. });
  16333. port_ = server_->bind_to_any_port(HOST);
  16334. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  16335. server_->wait_until_ready();
  16336. }
  16337. void TearDown() override {
  16338. server_->stop();
  16339. if (server_thread_.joinable()) { server_thread_.join(); }
  16340. }
  16341. std::unique_ptr<SSLServer> server_;
  16342. std::thread server_thread_;
  16343. int port_ = 0;
  16344. };
  16345. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  16346. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  16347. "/ws-echo");
  16348. client.enable_server_certificate_verification(false);
  16349. ASSERT_TRUE(client.connect());
  16350. ASSERT_TRUE(client.is_open());
  16351. ASSERT_TRUE(client.send("Hello WSS"));
  16352. std::string msg;
  16353. EXPECT_EQ(ws::Text, client.read(msg));
  16354. EXPECT_EQ("Hello WSS", msg);
  16355. client.close();
  16356. }
  16357. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  16358. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  16359. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  16360. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  16361. // client (without calling close() first) is the only path that runs
  16362. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  16363. // bug exactly.
  16364. //
  16365. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  16366. // when linked against an instrumented libssl; run under Valgrind to catch it
  16367. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  16368. // suite (the freed session otherwise stalls on the close handshake) — this test
  16369. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  16370. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  16371. {
  16372. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  16373. "/ws-echo");
  16374. client.enable_server_certificate_verification(false);
  16375. client.set_read_timeout(2, 0);
  16376. client.set_write_timeout(2, 0);
  16377. ASSERT_TRUE(client.connect());
  16378. ASSERT_TRUE(client.is_open());
  16379. ASSERT_TRUE(client.send("still open"));
  16380. // Intentionally do NOT call client.close(): leaving scope runs
  16381. // shutdown_and_close() with the WebSocket still open, which must send the
  16382. // close frame while the TLS session is still alive.
  16383. }
  16384. }
  16385. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  16386. // shutdown_and_close() at the start of connect(), reproducing the same
  16387. // use-after-free within the test body rather than at scope exit. The second
  16388. // connect must succeed and echo, proving the close handshake ran over a live
  16389. // session. See the note above about memory-tool requirements.
  16390. TEST_F(WebSocketSSLIntegrationTest,
  16391. ReconnectWhileOpenSendsCloseOverLiveSession) {
  16392. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  16393. "/ws-echo");
  16394. client.enable_server_certificate_verification(false);
  16395. client.set_read_timeout(2, 0);
  16396. client.set_write_timeout(2, 0);
  16397. ASSERT_TRUE(client.connect());
  16398. ASSERT_TRUE(client.is_open());
  16399. ASSERT_TRUE(client.send("still open"));
  16400. // Reconnect without closing first: connect() calls shutdown_and_close() on
  16401. // the still-open connection, which must not touch a freed TLS session.
  16402. ASSERT_TRUE(client.connect());
  16403. ASSERT_TRUE(client.is_open());
  16404. ASSERT_TRUE(client.send("after reconnect"));
  16405. std::string msg;
  16406. EXPECT_EQ(ws::Text, client.read(msg));
  16407. EXPECT_EQ("after reconnect", msg);
  16408. client.close();
  16409. }
  16410. #endif
  16411. #ifdef CPPHTTPLIB_SSL_ENABLED
  16412. class WebSocketSSLCATest : public ::testing::Test {
  16413. protected:
  16414. void SetUp() override {
  16415. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  16416. SERVER_PRIVATE_KEY_FILE);
  16417. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  16418. std::string msg;
  16419. while (ws.read(msg)) {
  16420. ws.send(msg);
  16421. }
  16422. });
  16423. port_ = server_->bind_to_any_port("127.0.0.1");
  16424. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  16425. server_->wait_until_ready();
  16426. }
  16427. void TearDown() override {
  16428. server_->stop();
  16429. if (server_thread_.joinable()) { server_thread_.join(); }
  16430. }
  16431. std::string url() const {
  16432. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  16433. }
  16434. std::unique_ptr<SSLServer> server_;
  16435. std::thread server_thread_;
  16436. int port_ = 0;
  16437. };
  16438. // A custom CA loaded as PEM verifies the server with full certificate
  16439. // verification enabled
  16440. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  16441. ws::WebSocketClient client(url());
  16442. std::string cert;
  16443. read_file(SERVER_CERT2_FILE, cert);
  16444. client.load_ca_cert_store(cert.c_str(), cert.size());
  16445. ASSERT_TRUE(client.connect());
  16446. ASSERT_TRUE(client.send("hello"));
  16447. std::string msg;
  16448. EXPECT_EQ(ws::Text, client.read(msg));
  16449. EXPECT_EQ("hello", msg);
  16450. client.close();
  16451. }
  16452. // A custom CA that does not cover the server must fail verification (the
  16453. // custom CA is exclusive; system certs are not loaded alongside it)
  16454. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  16455. ws::WebSocketClient client(url());
  16456. std::string cert;
  16457. read_file(CLIENT_CA_CERT_FILE, cert);
  16458. client.load_ca_cert_store(cert.c_str(), cert.size());
  16459. ASSERT_FALSE(client.connect());
  16460. }
  16461. // Regression test: reconnecting with a native custom CA store used to reuse
  16462. // a store handle the previous TLS context had already freed (use-after-free
  16463. // under the OpenSSL backend). The context now lives as long as the client.
  16464. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  16465. ws::WebSocketClient client(url());
  16466. std::string cert;
  16467. read_file(SERVER_CERT2_FILE, cert);
  16468. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  16469. ASSERT_TRUE(client.connect());
  16470. client.close();
  16471. ASSERT_TRUE(client.connect());
  16472. ASSERT_TRUE(client.send("again"));
  16473. std::string msg;
  16474. EXPECT_EQ(ws::Text, client.read(msg));
  16475. EXPECT_EQ("again", msg);
  16476. client.close();
  16477. }
  16478. // Regression test: a certificate with a trusted chain but no identity match
  16479. // for the server IP must be rejected. The Mbed TLS backend used to skip
  16480. // verification entirely for IP hosts, so this connection succeeded there.
  16481. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  16482. // chain verification while the identity check must still fail.
  16483. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  16484. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16485. ASSERT_TRUE(svr.is_valid());
  16486. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  16487. std::string msg;
  16488. while (ws.read(msg)) {
  16489. ws.send(msg);
  16490. }
  16491. });
  16492. auto port = svr.bind_to_any_port("127.0.0.1");
  16493. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16494. auto se = detail::scope_exit([&] {
  16495. svr.stop();
  16496. t.join();
  16497. });
  16498. svr.wait_until_ready();
  16499. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  16500. "/echo");
  16501. std::string cert;
  16502. read_file(SERVER_CERT_FILE, cert);
  16503. client.load_ca_cert_store(cert.c_str(), cert.size());
  16504. ASSERT_FALSE(client.connect());
  16505. }
  16506. #endif
  16507. #if !defined(_WIN32)
  16508. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  16509. auto secret_dir = std::string("./symlink_test_secret");
  16510. auto served_dir = std::string("./symlink_test_served");
  16511. auto secret_file = secret_dir + "/secret.txt";
  16512. auto symlink_path = served_dir + "/escape";
  16513. // Setup: create directories and files
  16514. mkdir(secret_dir.c_str(), 0755);
  16515. mkdir(served_dir.c_str(), 0755);
  16516. {
  16517. std::ofstream ofs(secret_file);
  16518. ofs << "SECRET_DATA";
  16519. }
  16520. // Create symlink using absolute path so it resolves correctly
  16521. #ifdef PATH_MAX
  16522. char abs_secret[PATH_MAX];
  16523. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  16524. #else
  16525. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  16526. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  16527. ASSERT_NE(nullptr, abs_secret);
  16528. #endif
  16529. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  16530. auto se = detail::scope_exit([&] {
  16531. unlink(symlink_path.c_str());
  16532. unlink(secret_file.c_str());
  16533. rmdir(served_dir.c_str());
  16534. rmdir(secret_dir.c_str());
  16535. });
  16536. Server svr;
  16537. svr.set_mount_point("/", served_dir);
  16538. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  16539. auto se2 = detail::scope_exit([&] {
  16540. svr.stop();
  16541. listen_thread.join();
  16542. });
  16543. svr.wait_until_ready();
  16544. Client cli("localhost", PORT);
  16545. // Symlink pointing outside base dir should be blocked
  16546. auto res = cli.Get("/escape/secret.txt");
  16547. ASSERT_TRUE(res);
  16548. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  16549. }
  16550. #endif
  16551. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  16552. // A GET request with Content-Length to a static file handler must have its
  16553. // body drained before the keep-alive connection is reused. Otherwise the
  16554. // unread body bytes are interpreted as the next HTTP request.
  16555. //
  16556. // The body is sent AFTER receiving the first response (as in the original
  16557. // PoC) so that the stream_line_reader cannot buffer it together with the
  16558. // headers of the first request.
  16559. Server svr;
  16560. svr.set_mount_point("/", "./www");
  16561. std::atomic<int> smuggled_count(0);
  16562. svr.Get("/smuggled", [&](const Request &, Response &res) {
  16563. smuggled_count++;
  16564. res.set_content("oops", "text/plain");
  16565. });
  16566. auto port = svr.bind_to_any_port("localhost");
  16567. thread t = thread([&] { svr.listen_after_bind(); });
  16568. auto se = detail::scope_exit([&] {
  16569. svr.stop();
  16570. t.join();
  16571. });
  16572. svr.wait_until_ready();
  16573. auto error = Error::Success;
  16574. auto sock = detail::create_client_socket(
  16575. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  16576. /*connection_timeout_sec=*/2, 0,
  16577. /*read_timeout_sec=*/2, 0,
  16578. /*write_timeout_sec=*/2, 0, std::string(), error);
  16579. ASSERT_NE(INVALID_SOCKET, sock);
  16580. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  16581. // The "smuggled" request will be sent as the body of the outer GET
  16582. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  16583. "Host: localhost\r\n"
  16584. "Connection: close\r\n"
  16585. "\r\n";
  16586. // Step 1: Send only the outer request headers (no body yet)
  16587. std::string outer_headers = "GET /file HTTP/1.1\r\n"
  16588. "Host: localhost\r\n"
  16589. "Content-Length: " +
  16590. std::to_string(smuggled.size()) +
  16591. "\r\n"
  16592. "\r\n";
  16593. auto sent = send(sock, outer_headers.data(), outer_headers.size(), 0);
  16594. ASSERT_EQ(static_cast<ssize_t>(outer_headers.size()), sent);
  16595. // Step 2: Read the first response (server serves file without reading body)
  16596. std::string first_response;
  16597. char buf[4096];
  16598. for (;;) {
  16599. auto n = recv(sock, buf, sizeof(buf), 0);
  16600. if (n <= 0) break;
  16601. first_response.append(buf, static_cast<size_t>(n));
  16602. // Stop once we have a complete response (headers + body)
  16603. auto hdr_end = first_response.find("\r\n\r\n");
  16604. if (hdr_end != std::string::npos) {
  16605. // Check for Content-Length to know when the body is complete
  16606. auto cl_pos = first_response.find("Content-Length:");
  16607. if (cl_pos != std::string::npos) {
  16608. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  16609. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  16610. auto cl = std::stoul(
  16611. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  16612. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  16613. } else {
  16614. break; // No Content-Length, assume headers-only response
  16615. }
  16616. }
  16617. }
  16618. ASSERT_TRUE(first_response.find("HTTP/1.1 200") != std::string::npos);
  16619. // Step 3: Now send the body, which looks like a new HTTP request.
  16620. // On a vulnerable server the keep-alive loop reads this as a second request.
  16621. sent = send(sock, smuggled.data(), smuggled.size(), 0);
  16622. ASSERT_EQ(static_cast<ssize_t>(smuggled.size()), sent);
  16623. // Step 4: Try to read a second response (should NOT exist after fix)
  16624. std::string second_response;
  16625. for (;;) {
  16626. auto n = recv(sock, buf, sizeof(buf), 0);
  16627. if (n <= 0) break;
  16628. second_response.append(buf, static_cast<size_t>(n));
  16629. }
  16630. // The smuggled request must NOT have been processed
  16631. EXPECT_EQ(0, smuggled_count.load());
  16632. }
  16633. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  16634. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  16635. // must be rejected with 400 Bad Request.
  16636. Server svr;
  16637. svr.Post("/test", [&](const Request &, Response &res) {
  16638. res.set_content("ok", "text/plain");
  16639. });
  16640. thread t = thread([&] { svr.listen(HOST, PORT); });
  16641. auto se = detail::scope_exit([&] {
  16642. svr.stop();
  16643. t.join();
  16644. ASSERT_FALSE(svr.is_running());
  16645. });
  16646. svr.wait_until_ready();
  16647. // Exact "chunked"
  16648. {
  16649. auto req = "POST /test HTTP/1.1\r\n"
  16650. "Host: localhost\r\n"
  16651. "Content-Length: 5\r\n"
  16652. "Transfer-Encoding: chunked\r\n"
  16653. "Connection: close\r\n"
  16654. "\r\n"
  16655. "hello";
  16656. std::string response;
  16657. ASSERT_TRUE(send_request(1, req, &response));
  16658. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  16659. response.substr(0, response.find("\r\n")));
  16660. }
  16661. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  16662. {
  16663. auto req = "POST /test HTTP/1.1\r\n"
  16664. "Host: localhost\r\n"
  16665. "Content-Length: 5\r\n"
  16666. "Transfer-Encoding: gzip, chunked\r\n"
  16667. "Connection: close\r\n"
  16668. "\r\n"
  16669. "hello";
  16670. std::string response;
  16671. ASSERT_TRUE(send_request(1, req, &response));
  16672. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  16673. response.substr(0, response.find("\r\n")));
  16674. }
  16675. }
  16676. // Regression for issue #2450: a DELETE without Content-Length on a
  16677. // keep-alive connection must not let the post-response drain consume the
  16678. // next request's bytes.
  16679. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  16680. Server svr;
  16681. std::atomic<int> delete_count(0);
  16682. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  16683. delete_count++;
  16684. res.status = StatusCode::NoContent_204;
  16685. });
  16686. auto port = svr.bind_to_any_port(HOST);
  16687. thread t = thread([&] { svr.listen_after_bind(); });
  16688. auto se = detail::scope_exit([&] {
  16689. svr.stop();
  16690. t.join();
  16691. });
  16692. svr.wait_until_ready();
  16693. auto error = Error::Success;
  16694. auto sock = detail::create_client_socket(
  16695. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  16696. /*connection_timeout_sec=*/2, 0,
  16697. /*read_timeout_sec=*/2, 0,
  16698. /*write_timeout_sec=*/2, 0, std::string(), error);
  16699. ASSERT_NE(INVALID_SOCKET, sock);
  16700. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  16701. auto send_request_and_read_response = [&](const std::string &req,
  16702. std::string &out) -> bool {
  16703. auto sent = send(sock, req.data(), req.size(), 0);
  16704. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  16705. char buf[4096];
  16706. for (;;) {
  16707. auto n = recv(sock, buf, sizeof(buf), 0);
  16708. if (n <= 0) { return !out.empty(); }
  16709. out.append(buf, static_cast<size_t>(n));
  16710. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  16711. }
  16712. };
  16713. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  16714. "Host: localhost\r\n"
  16715. "\r\n";
  16716. std::string resp1;
  16717. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  16718. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  16719. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  16720. "Host: localhost\r\n"
  16721. "Connection: close\r\n"
  16722. "\r\n";
  16723. std::string resp2;
  16724. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  16725. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  16726. EXPECT_EQ(2, delete_count.load());
  16727. }
  16728. namespace no_proxy_test {
  16729. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  16730. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  16731. // calling listen().
  16732. class ScopedServer {
  16733. public:
  16734. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  16735. ~ScopedServer() {
  16736. svr_.stop();
  16737. if (th_.joinable()) { th_.join(); }
  16738. }
  16739. Server &svr() { return svr_; }
  16740. int port() const { return port_; }
  16741. void listen() {
  16742. th_ = std::thread([this] { svr_.listen_after_bind(); });
  16743. svr_.wait_until_ready();
  16744. }
  16745. private:
  16746. Server svr_;
  16747. std::thread th_;
  16748. int port_ = 0;
  16749. };
  16750. class ProxyAndTargetServers {
  16751. public:
  16752. ProxyAndTargetServers() {
  16753. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  16754. proxy_hits_++;
  16755. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  16756. res.set_content("via-proxy", "text/plain");
  16757. });
  16758. target_.Get(".*", [this](const Request &req, Response &res) {
  16759. target_hits_++;
  16760. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  16761. res.set_content("direct", "text/plain");
  16762. });
  16763. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  16764. target_port_ = target_.bind_to_any_port("127.0.0.1");
  16765. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  16766. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  16767. proxy_mock_.wait_until_ready();
  16768. target_.wait_until_ready();
  16769. }
  16770. ~ProxyAndTargetServers() {
  16771. proxy_mock_.stop();
  16772. target_.stop();
  16773. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  16774. if (target_thread_.joinable()) { target_thread_.join(); }
  16775. }
  16776. Server &proxy_mock() { return proxy_mock_; }
  16777. Server &target() { return target_; }
  16778. int proxy_port() const { return proxy_port_; }
  16779. int target_port() const { return target_port_; }
  16780. int proxy_hits() const { return proxy_hits_.load(); }
  16781. int target_hits() const { return target_hits_.load(); }
  16782. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  16783. void reset_counters() {
  16784. proxy_hits_ = 0;
  16785. target_hits_ = 0;
  16786. last_had_proxy_authz_ = false;
  16787. }
  16788. private:
  16789. Server proxy_mock_;
  16790. Server target_;
  16791. std::thread proxy_thread_;
  16792. std::thread target_thread_;
  16793. int proxy_port_ = 0;
  16794. int target_port_ = 0;
  16795. std::atomic<int> proxy_hits_{0};
  16796. std::atomic<int> target_hits_{0};
  16797. std::atomic<bool> last_had_proxy_authz_{false};
  16798. };
  16799. inline std::unique_ptr<Client> make_client(const std::string &host,
  16800. ProxyAndTargetServers &s) {
  16801. auto cli = detail::make_unique<Client>(host, s.target_port());
  16802. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  16803. cli->set_proxy("127.0.0.1", s.proxy_port());
  16804. return cli;
  16805. }
  16806. } // namespace no_proxy_test
  16807. using no_proxy_test::make_client;
  16808. using no_proxy_test::ProxyAndTargetServers;
  16809. TEST(NoProxyTest, ExactHostnameBypasses) {
  16810. ProxyAndTargetServers s;
  16811. auto cli = make_client("example.com", s);
  16812. cli->set_no_proxy({"example.com"});
  16813. auto res = cli->Get("/");
  16814. ASSERT_TRUE(res);
  16815. EXPECT_EQ(0, s.proxy_hits());
  16816. EXPECT_EQ(1, s.target_hits());
  16817. }
  16818. TEST(NoProxyTest, SubdomainBypasses) {
  16819. ProxyAndTargetServers s;
  16820. auto cli = make_client("foo.example.com", s);
  16821. cli->set_no_proxy({"example.com"});
  16822. auto res = cli->Get("/");
  16823. ASSERT_TRUE(res);
  16824. EXPECT_EQ(0, s.proxy_hits());
  16825. EXPECT_EQ(1, s.target_hits());
  16826. }
  16827. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  16828. // Regression guard: "evilexample.com" must not be considered a subdomain
  16829. // of "example.com". Without the dot-boundary rule, a naive endsWith
  16830. // check would let traffic bypass the proxy and leak credentials direct
  16831. // to the attacker host.
  16832. ProxyAndTargetServers s;
  16833. auto cli = make_client("evilexample.com", s);
  16834. cli->set_no_proxy({"example.com"});
  16835. auto res = cli->Get("/");
  16836. ASSERT_TRUE(res);
  16837. EXPECT_GE(s.proxy_hits(), 1);
  16838. EXPECT_EQ(0, s.target_hits());
  16839. }
  16840. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  16841. ProxyAndTargetServers s;
  16842. auto cli = make_client("example.com.evil.com", s);
  16843. cli->set_no_proxy({"example.com"});
  16844. auto res = cli->Get("/");
  16845. ASSERT_TRUE(res);
  16846. EXPECT_GE(s.proxy_hits(), 1);
  16847. EXPECT_EQ(0, s.target_hits());
  16848. }
  16849. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  16850. ProxyAndTargetServers s;
  16851. auto cli = make_client("example.com", s);
  16852. cli->set_no_proxy({".example.com"});
  16853. auto res = cli->Get("/");
  16854. ASSERT_TRUE(res);
  16855. EXPECT_EQ(0, s.proxy_hits());
  16856. EXPECT_EQ(1, s.target_hits());
  16857. }
  16858. TEST(NoProxyTest, CaseInsensitiveHostname) {
  16859. ProxyAndTargetServers s;
  16860. auto cli = make_client("Example.COM", s);
  16861. cli->set_no_proxy({"EXAMPLE.com"});
  16862. auto res = cli->Get("/");
  16863. ASSERT_TRUE(res);
  16864. EXPECT_EQ(0, s.proxy_hits());
  16865. EXPECT_EQ(1, s.target_hits());
  16866. }
  16867. TEST(NoProxyTest, TrailingDotIsNormalized) {
  16868. ProxyAndTargetServers s;
  16869. auto cli = make_client("example.com.", s);
  16870. cli->set_no_proxy({"example.com"});
  16871. auto res = cli->Get("/");
  16872. ASSERT_TRUE(res);
  16873. EXPECT_EQ(0, s.proxy_hits());
  16874. EXPECT_EQ(1, s.target_hits());
  16875. }
  16876. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  16877. // Trailing dots must be normalized on BOTH sides — host and entry.
  16878. // An implementation that only strips the host-side trailing dot would
  16879. // fail to match host "example.com" against entry "example.com." because
  16880. // a literal substring search would compare 11 chars against 12.
  16881. ProxyAndTargetServers s;
  16882. auto cli = make_client("example.com", s);
  16883. cli->set_no_proxy({"example.com."});
  16884. auto res = cli->Get("/");
  16885. ASSERT_TRUE(res);
  16886. EXPECT_EQ(0, s.proxy_hits());
  16887. EXPECT_EQ(1, s.target_hits());
  16888. }
  16889. TEST(NoProxyTest, WildcardBypassesEverything) {
  16890. ProxyAndTargetServers s;
  16891. auto cli = make_client("anything.invalid.test", s);
  16892. cli->set_no_proxy({"*"});
  16893. auto res = cli->Get("/");
  16894. ASSERT_TRUE(res);
  16895. EXPECT_EQ(0, s.proxy_hits());
  16896. EXPECT_EQ(1, s.target_hits());
  16897. }
  16898. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  16899. ProxyAndTargetServers s;
  16900. Client cli("127.0.0.1", s.target_port());
  16901. cli.set_proxy("127.0.0.1", s.proxy_port());
  16902. cli.set_no_proxy({"127.0.0.1"});
  16903. auto res = cli.Get("/");
  16904. ASSERT_TRUE(res);
  16905. EXPECT_EQ(0, s.proxy_hits());
  16906. EXPECT_EQ(1, s.target_hits());
  16907. }
  16908. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  16909. ProxyAndTargetServers s;
  16910. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  16911. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  16912. cli.set_proxy("127.0.0.1", s.proxy_port());
  16913. cli.set_no_proxy({"::1"});
  16914. auto res = cli.Get("/");
  16915. ASSERT_TRUE(res);
  16916. EXPECT_EQ(0, s.proxy_hits());
  16917. EXPECT_EQ(1, s.target_hits());
  16918. }
  16919. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  16920. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  16921. // must still be recognized as IPv6 for CIDR matching. Implementations
  16922. // that detect IPv6 only when the host begins with '[' would parse the
  16923. // host as a hostname and miss the match.
  16924. ProxyAndTargetServers s;
  16925. Client cli("fe80::1", s.target_port());
  16926. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  16927. cli.set_proxy("127.0.0.1", s.proxy_port());
  16928. cli.set_no_proxy({"fe80::/10"});
  16929. auto res = cli.Get("/");
  16930. ASSERT_TRUE(res);
  16931. EXPECT_EQ(0, s.proxy_hits());
  16932. EXPECT_EQ(1, s.target_hits());
  16933. }
  16934. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  16935. ProxyAndTargetServers s;
  16936. Client cli("::1", s.target_port());
  16937. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  16938. cli.set_proxy("127.0.0.1", s.proxy_port());
  16939. cli.set_no_proxy({"[::1]"});
  16940. auto res = cli.Get("/");
  16941. ASSERT_TRUE(res);
  16942. EXPECT_EQ(0, s.proxy_hits());
  16943. EXPECT_EQ(1, s.target_hits());
  16944. }
  16945. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  16946. ProxyAndTargetServers s;
  16947. Client cli("fe80::1", s.target_port());
  16948. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  16949. cli.set_proxy("127.0.0.1", s.proxy_port());
  16950. cli.set_no_proxy({"[fe80::]/10"});
  16951. auto res = cli.Get("/");
  16952. ASSERT_TRUE(res);
  16953. EXPECT_EQ(0, s.proxy_hits());
  16954. EXPECT_EQ(1, s.target_hits());
  16955. }
  16956. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  16957. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  16958. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  16959. // tricks via address-family conversion.
  16960. ProxyAndTargetServers s;
  16961. Client cli("::ffff:127.0.0.1", s.target_port());
  16962. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  16963. cli.set_proxy("127.0.0.1", s.proxy_port());
  16964. cli.set_no_proxy({"127.0.0.1"});
  16965. auto res = cli.Get("/");
  16966. ASSERT_TRUE(res);
  16967. EXPECT_GE(s.proxy_hits(), 1);
  16968. EXPECT_EQ(0, s.target_hits());
  16969. }
  16970. TEST(NoProxyTest, IPv4CidrMatch) {
  16971. ProxyAndTargetServers s;
  16972. Client cli("127.0.0.1", s.target_port());
  16973. cli.set_proxy("127.0.0.1", s.proxy_port());
  16974. cli.set_no_proxy({"127.0.0.0/8"});
  16975. auto res = cli.Get("/");
  16976. ASSERT_TRUE(res);
  16977. EXPECT_EQ(0, s.proxy_hits());
  16978. EXPECT_EQ(1, s.target_hits());
  16979. }
  16980. TEST(NoProxyTest, IPv4CidrNonMatch) {
  16981. ProxyAndTargetServers s;
  16982. Client cli("127.0.0.1", s.target_port());
  16983. cli.set_proxy("127.0.0.1", s.proxy_port());
  16984. cli.set_no_proxy({"10.0.0.0/8"});
  16985. auto res = cli.Get("/");
  16986. ASSERT_TRUE(res);
  16987. EXPECT_GE(s.proxy_hits(), 1);
  16988. EXPECT_EQ(0, s.target_hits());
  16989. }
  16990. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  16991. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  16992. // IPv4 target matches.
  16993. ProxyAndTargetServers s;
  16994. Client cli("127.0.0.1", s.target_port());
  16995. cli.set_proxy("127.0.0.1", s.proxy_port());
  16996. cli.set_no_proxy({"0.0.0.0/0"});
  16997. auto res = cli.Get("/");
  16998. ASSERT_TRUE(res);
  16999. EXPECT_EQ(0, s.proxy_hits());
  17000. EXPECT_EQ(1, s.target_hits());
  17001. }
  17002. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  17003. ProxyAndTargetServers s;
  17004. Client cli("127.0.0.1", s.target_port());
  17005. cli.set_proxy("127.0.0.1", s.proxy_port());
  17006. cli.set_no_proxy({"127.0.0.1"});
  17007. auto res = cli.Get("/");
  17008. ASSERT_TRUE(res);
  17009. EXPECT_EQ(0, s.proxy_hits());
  17010. EXPECT_EQ(1, s.target_hits());
  17011. }
  17012. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  17013. ProxyAndTargetServers s;
  17014. Client cli("127.0.0.1", s.target_port());
  17015. cli.set_proxy("127.0.0.1", s.proxy_port());
  17016. cli.set_no_proxy({"127.0.0.0/33"});
  17017. auto res = cli.Get("/");
  17018. ASSERT_TRUE(res);
  17019. EXPECT_GE(s.proxy_hits(), 1);
  17020. EXPECT_EQ(0, s.target_hits());
  17021. }
  17022. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  17023. // Empty prefix after the slash must be rejected, not silently treated as /32.
  17024. ProxyAndTargetServers s;
  17025. Client cli("127.0.0.1", s.target_port());
  17026. cli.set_proxy("127.0.0.1", s.proxy_port());
  17027. cli.set_no_proxy({"127.0.0.1/"});
  17028. auto res = cli.Get("/");
  17029. ASSERT_TRUE(res);
  17030. EXPECT_GE(s.proxy_hits(), 1);
  17031. EXPECT_EQ(0, s.target_hits());
  17032. }
  17033. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  17034. ProxyAndTargetServers s;
  17035. auto cli = make_client("internal.corp", s);
  17036. cli->set_proxy_basic_auth("u", "p");
  17037. cli->set_no_proxy({"internal.corp"});
  17038. auto res = cli->Get("/");
  17039. ASSERT_TRUE(res);
  17040. EXPECT_EQ(1, s.target_hits());
  17041. EXPECT_EQ(0, s.proxy_hits());
  17042. EXPECT_FALSE(s.last_had_proxy_authz())
  17043. << "Proxy-Authorization must not be sent direct to the target";
  17044. }
  17045. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  17046. ProxyAndTargetServers s;
  17047. auto cli = make_client("public.example", s);
  17048. cli->set_proxy_basic_auth("u", "p");
  17049. cli->set_no_proxy({"internal.corp"}); // does not match
  17050. auto res = cli->Get("/");
  17051. ASSERT_TRUE(res);
  17052. EXPECT_GE(s.proxy_hits(), 1);
  17053. EXPECT_TRUE(s.last_had_proxy_authz());
  17054. }
  17055. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  17056. ProxyAndTargetServers s;
  17057. auto cli = make_client("anything.test", s);
  17058. auto res = cli->Get("/");
  17059. ASSERT_TRUE(res);
  17060. EXPECT_GE(s.proxy_hits(), 1);
  17061. EXPECT_EQ(0, s.target_hits());
  17062. }
  17063. TEST(NoProxyTest, PortSpecificEntryRejected) {
  17064. ProxyAndTargetServers s;
  17065. auto cli = make_client("example.com", s);
  17066. cli->set_no_proxy({"example.com:8080"});
  17067. auto res = cli->Get("/");
  17068. ASSERT_TRUE(res);
  17069. EXPECT_GE(s.proxy_hits(), 1);
  17070. EXPECT_EQ(0, s.target_hits());
  17071. }
  17072. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  17073. ProxyAndTargetServers s;
  17074. auto cli = make_client("anything.test", s);
  17075. cli->set_no_proxy({"", " ", "\t"});
  17076. auto res = cli->Get("/");
  17077. ASSERT_TRUE(res);
  17078. EXPECT_GE(s.proxy_hits(), 1);
  17079. EXPECT_EQ(0, s.target_hits());
  17080. }
  17081. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  17082. // An entry with leading/trailing whitespace must still match — env-style
  17083. // values are commonly pasted with stray spaces and an implementation
  17084. // that feeds the raw token directly to inet_pton would fail to match
  17085. // valid CIDRs because of the spaces.
  17086. ProxyAndTargetServers s;
  17087. Client cli("127.0.0.1", s.target_port());
  17088. cli.set_proxy("127.0.0.1", s.proxy_port());
  17089. cli.set_no_proxy({" 127.0.0.0/8 "});
  17090. auto res = cli.Get("/");
  17091. ASSERT_TRUE(res);
  17092. EXPECT_EQ(0, s.proxy_hits());
  17093. EXPECT_EQ(1, s.target_hits());
  17094. }
  17095. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  17096. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  17097. // go direct and must NOT carry Proxy-Authorization.
  17098. std::atomic<int> proxy_hits{0};
  17099. std::atomic<int> target_hits{0};
  17100. std::atomic<bool> target_saw_authz{false};
  17101. no_proxy_test::ScopedServer proxy_mock, target;
  17102. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  17103. proxy_hits++;
  17104. res.status = 302;
  17105. res.set_header("Location", "http://127.0.0.1:" +
  17106. std::to_string(target.port()) + "/landed");
  17107. });
  17108. target.svr().Get(".*", [&](const Request &req, Response &res) {
  17109. target_hits++;
  17110. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  17111. res.set_content("direct", "text/plain");
  17112. });
  17113. proxy_mock.listen();
  17114. target.listen();
  17115. Client cli("public.example", target.port());
  17116. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  17117. cli.set_proxy("127.0.0.1", proxy_mock.port());
  17118. cli.set_proxy_basic_auth("u", "p");
  17119. cli.set_no_proxy({"127.0.0.1"});
  17120. cli.set_follow_location(true);
  17121. auto res = cli.Get("/redir");
  17122. ASSERT_TRUE(res);
  17123. EXPECT_GE(proxy_hits.load(), 1);
  17124. EXPECT_GE(target_hits.load(), 1);
  17125. EXPECT_FALSE(target_saw_authz.load());
  17126. }
  17127. #ifdef CPPHTTPLIB_SSL_ENABLED
  17128. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  17129. // Direct origin replying 407 must not trigger the digest retry; otherwise
  17130. // proxy creds would be sent to the (possibly hostile) origin.
  17131. std::atomic<int> target_hits{0};
  17132. std::atomic<bool> target_saw_proxy_authz{false};
  17133. no_proxy_test::ScopedServer target;
  17134. target.svr().Get(".*", [&](const Request &req, Response &res) {
  17135. target_hits++;
  17136. if (req.has_header("Proxy-Authorization")) {
  17137. target_saw_proxy_authz = true;
  17138. }
  17139. res.status = StatusCode::ProxyAuthenticationRequired_407;
  17140. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  17141. "nonce=\"abc\", algorithm=MD5");
  17142. });
  17143. target.listen();
  17144. // The proxy address is set to the target's port: the bypass MUST kick in;
  17145. // if it doesn't, the test still routes "via proxy" to the same server and
  17146. // the Proxy-Authorization assertion below catches the leak.
  17147. Client cli("evil.example", target.port());
  17148. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  17149. cli.set_proxy("127.0.0.1", target.port());
  17150. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  17151. cli.set_no_proxy({"evil.example"});
  17152. auto res = cli.Get("/x");
  17153. ASSERT_TRUE(res);
  17154. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  17155. EXPECT_EQ(1, target_hits.load());
  17156. EXPECT_FALSE(target_saw_proxy_authz.load());
  17157. }
  17158. #endif
  17159. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  17160. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  17161. std::atomic<int> proxy_hits{0};
  17162. std::atomic<int> bypass_hits{0};
  17163. std::atomic<bool> proxy_saw_c_url{false};
  17164. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  17165. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  17166. proxy_hits++;
  17167. if (req.path.find("/start") != std::string::npos) {
  17168. res.status = 302;
  17169. res.set_header("Location", "http://127.0.0.1:" +
  17170. std::to_string(bypass_server.port()) +
  17171. "/middle");
  17172. return;
  17173. }
  17174. if (req.path.find("/end") != std::string::npos) {
  17175. proxy_saw_c_url = true;
  17176. res.set_content("c-via-proxy", "text/plain");
  17177. return;
  17178. }
  17179. res.set_content("unexpected", "text/plain");
  17180. });
  17181. // public.example's "advertised" port is arbitrary (the request never lands
  17182. // there — it goes through the proxy), but use a dynamic value to stay
  17183. // friendly with sharded parallel runs.
  17184. int public_port = bypass_server.port();
  17185. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  17186. bypass_hits++;
  17187. res.status = 302;
  17188. res.set_header("Location", "http://public.example:" +
  17189. std::to_string(public_port) + "/end");
  17190. });
  17191. proxy_mock.listen();
  17192. bypass_server.listen();
  17193. Client cli("public.example", public_port);
  17194. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  17195. cli.set_proxy("127.0.0.1", proxy_mock.port());
  17196. cli.set_no_proxy({"127.0.0.1"});
  17197. cli.set_follow_location(true);
  17198. auto res = cli.Get("/start");
  17199. ASSERT_TRUE(res);
  17200. EXPECT_EQ(StatusCode::OK_200, res->status);
  17201. EXPECT_EQ("c-via-proxy", res->body);
  17202. EXPECT_GE(proxy_hits.load(), 2);
  17203. EXPECT_GE(bypass_hits.load(), 1);
  17204. EXPECT_TRUE(proxy_saw_c_url.load());
  17205. }
  17206. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  17207. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  17208. // request reconnects to the correct endpoint.
  17209. std::atomic<int> proxy_hits{0};
  17210. std::atomic<int> target_hits{0};
  17211. no_proxy_test::ScopedServer proxy_mock, target;
  17212. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  17213. proxy_hits++;
  17214. res.set_content("via-proxy", "text/plain");
  17215. });
  17216. target.svr().Get(".*", [&](const Request &, Response &res) {
  17217. target_hits++;
  17218. res.set_content("direct", "text/plain");
  17219. });
  17220. proxy_mock.listen();
  17221. target.listen();
  17222. Client cli("public.example", target.port());
  17223. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  17224. cli.set_proxy("127.0.0.1", proxy_mock.port());
  17225. cli.set_keep_alive(true);
  17226. auto res1 = cli.Get("/a");
  17227. ASSERT_TRUE(res1);
  17228. EXPECT_EQ("via-proxy", res1->body);
  17229. EXPECT_EQ(1, proxy_hits.load());
  17230. EXPECT_EQ(0, target_hits.load());
  17231. cli.set_no_proxy({"public.example"});
  17232. auto res2 = cli.Get("/b");
  17233. ASSERT_TRUE(res2);
  17234. EXPECT_EQ("direct", res2->body);
  17235. EXPECT_EQ(1, proxy_hits.load());
  17236. EXPECT_EQ(1, target_hits.load());
  17237. }
  17238. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  17239. namespace proxy_tunnel_test {
  17240. // SSLServer counterpart to no_proxy_test::ScopedServer.
  17241. class ScopedSSLServer {
  17242. public:
  17243. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  17244. port_ = svr_.bind_to_any_port("127.0.0.1");
  17245. }
  17246. ~ScopedSSLServer() {
  17247. svr_.stop();
  17248. if (th_.joinable()) { th_.join(); }
  17249. }
  17250. SSLServer &svr() { return svr_; }
  17251. int port() const { return port_; }
  17252. void listen() {
  17253. th_ = std::thread([this] { svr_.listen_after_bind(); });
  17254. svr_.wait_until_ready();
  17255. }
  17256. private:
  17257. SSLServer svr_;
  17258. std::thread th_;
  17259. int port_ = 0;
  17260. };
  17261. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  17262. class ScopedConnectProxy {
  17263. public:
  17264. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  17265. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  17266. if (listen_fd_ < 0) { return; }
  17267. int yes = 1;
  17268. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  17269. sockaddr_in a{};
  17270. a.sin_family = AF_INET;
  17271. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  17272. a.sin_port = 0;
  17273. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  17274. return;
  17275. }
  17276. socklen_t alen = sizeof(a);
  17277. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  17278. 0) {
  17279. return;
  17280. }
  17281. port_ = ntohs(a.sin_port);
  17282. if (::listen(listen_fd_, 1) != 0) { return; }
  17283. th_ = std::thread([this] { run(); });
  17284. }
  17285. ~ScopedConnectProxy() {
  17286. stop_ = true;
  17287. if (listen_fd_ >= 0) {
  17288. ::shutdown(listen_fd_, SHUT_RDWR);
  17289. ::close(listen_fd_);
  17290. }
  17291. if (th_.joinable()) { th_.join(); }
  17292. }
  17293. int port() const { return port_; }
  17294. int connect_hits() const { return connect_hits_.load(); }
  17295. private:
  17296. void run() {
  17297. while (!stop_.load()) {
  17298. fd_set rfds;
  17299. FD_ZERO(&rfds);
  17300. FD_SET(listen_fd_, &rfds);
  17301. timeval tv{0, 100 * 1000};
  17302. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  17303. if (sel <= 0) { continue; }
  17304. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  17305. if (client_fd < 0) { continue; }
  17306. std::string req;
  17307. char buf[2048];
  17308. while (req.find("\r\n\r\n") == std::string::npos) {
  17309. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  17310. if (n <= 0) { break; }
  17311. req.append(buf, static_cast<size_t>(n));
  17312. }
  17313. if (req.compare(0, 7, "CONNECT") != 0) {
  17314. ::close(client_fd);
  17315. continue;
  17316. }
  17317. connect_hits_++;
  17318. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  17319. ::send(client_fd, ok, std::strlen(ok), 0);
  17320. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  17321. sockaddr_in o{};
  17322. o.sin_family = AF_INET;
  17323. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  17324. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  17325. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  17326. 0) {
  17327. ::close(client_fd);
  17328. ::close(origin_fd);
  17329. continue;
  17330. }
  17331. auto forward = [](int from, int to) {
  17332. char b[8192];
  17333. for (;;) {
  17334. ssize_t n = ::recv(from, b, sizeof(b), 0);
  17335. if (n <= 0) { break; }
  17336. ssize_t off = 0;
  17337. while (off < n) {
  17338. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  17339. if (s <= 0) {
  17340. off = n;
  17341. break;
  17342. }
  17343. off += s;
  17344. }
  17345. }
  17346. ::shutdown(to, SHUT_WR);
  17347. };
  17348. std::thread t1([&] { forward(client_fd, origin_fd); });
  17349. std::thread t2([&] { forward(origin_fd, client_fd); });
  17350. t1.join();
  17351. t2.join();
  17352. ::close(client_fd);
  17353. ::close(origin_fd);
  17354. }
  17355. }
  17356. int forward_port_ = -1;
  17357. int listen_fd_ = -1;
  17358. int port_ = 0;
  17359. std::thread th_;
  17360. std::atomic<bool> stop_{false};
  17361. std::atomic<int> connect_hits_{0};
  17362. };
  17363. } // namespace proxy_tunnel_test
  17364. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  17365. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  17366. // retry; otherwise proxy creds would be sent to the origin.
  17367. std::atomic<int> origin_hits{0};
  17368. std::atomic<bool> origin_saw_proxy_authz{false};
  17369. proxy_tunnel_test::ScopedSSLServer origin;
  17370. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  17371. origin_hits++;
  17372. if (req.has_header("Proxy-Authorization")) {
  17373. origin_saw_proxy_authz = true;
  17374. }
  17375. res.status = StatusCode::ProxyAuthenticationRequired_407;
  17376. res.set_header("Proxy-Authenticate",
  17377. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  17378. "algorithm=MD5");
  17379. });
  17380. origin.listen();
  17381. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  17382. ASSERT_NE(0, proxy.port());
  17383. SSLClient cli(HOST, origin.port());
  17384. cli.enable_server_certificate_verification(false);
  17385. cli.set_proxy(HOST, proxy.port());
  17386. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  17387. auto res = cli.Get("/x");
  17388. ASSERT_TRUE(res);
  17389. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  17390. EXPECT_EQ(1, origin_hits.load());
  17391. EXPECT_FALSE(origin_saw_proxy_authz.load());
  17392. EXPECT_EQ(1, proxy.connect_hits());
  17393. }
  17394. #endif