test.cc 670 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117
  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) << "Error: " << to_string(res.error());
  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) << "Error: " << to_string(res.error());
  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) << "Error: " << to_string(res.error());
  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) << "Error: " << to_string(res.error());
  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) << "Error: " << to_string(res.error());
  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) << "Error: " << to_string(res.error());
  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) << "Error: " << to_string(res.error());
  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) << "Error: " << to_string(res.error());
  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) << "Error: " << to_string(res.error());
  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) << "Error: " << to_string(res.error());
  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) << "Error: " << to_string(res.error());
  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) << "Error: " << to_string(res.error());
  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) << "Error: " << to_string(res.error());
  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) << "Error: " << to_string(res.error());
  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) << "Error: " << to_string(res.error());
  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) << "Error: " << to_string(res.error());
  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) << "Error: " << to_string(res.error());
  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) << "Error: " << to_string(res.error());
  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) << "Error: " << to_string(res.error());
  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) << "Error: " << to_string(res.error());
  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) << "Error: " << to_string(res.error());
  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) << "Error: " << to_string(res.error());
  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) << "Error: " << to_string(res.error());
  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) << "Error: " << to_string(res.error());
  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) << "Error: " << to_string(res.error());
  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) << "Error: " << to_string(res.error());
  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) << "Error: " << to_string(res.error());
  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) << "Error: " << to_string(res.error());
  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) << "Error: " << to_string(res.error());
  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) << "Error: " << to_string(res.error());
  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) << "Error: " << to_string(res.error());
  2183. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  2184. cli.set_follow_location(true);
  2185. res = cli.Get("/");
  2186. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  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) << "Error: " << to_string(res.error());
  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) << "Error: " << to_string(res.error());
  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) << "Error: " << to_string(res.error());
  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) << "Error: " << to_string(res.error());
  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) << "Error: " << to_string(res.error());
  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) << "Error: " << to_string(res.error());
  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) << "Error: " << to_string(res.error());
  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) << "Error: " << to_string(res.error());
  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) << "Error: " << to_string(res.error());
  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) << "Error: " << to_string(res.error());
  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) << "Error: " << to_string(res.error());
  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) << "Error: " << to_string(res.error());
  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) << "Error: " << to_string(res.error());
  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) << "Error: " << to_string(res.error());
  2590. EXPECT_EQ(StatusCode::OK_200, res->status);
  2591. }
  2592. }
  2593. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  2594. // `open_stream()` used to skip the path encoding that the buffered send
  2595. // path applies, so the same `path` produced different bytes in the request
  2596. // line depending on which API was used. Assert the two agree.
  2597. Server svr;
  2598. std::string target;
  2599. svr.Get(".*", [&](const Request &req, Response &res) {
  2600. target = req.target;
  2601. res.status = StatusCode::OK_200;
  2602. });
  2603. auto port = svr.bind_to_any_port(HOST);
  2604. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2605. auto se = detail::scope_exit([&] {
  2606. svr.stop();
  2607. thread.join();
  2608. ASSERT_FALSE(svr.is_running());
  2609. });
  2610. svr.wait_until_ready();
  2611. struct {
  2612. const char *path;
  2613. const char *expected;
  2614. } cases[] = {
  2615. {"/a b?x=1", "/a%20b?x=1"},
  2616. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  2617. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  2618. };
  2619. for (const auto &c : cases) {
  2620. Client cli(HOST, port);
  2621. target.clear();
  2622. auto res = cli.Get(c.path);
  2623. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2624. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  2625. auto buffered_target = target;
  2626. target.clear();
  2627. auto handle = cli.open_stream("GET", c.path);
  2628. EXPECT_TRUE(handle.is_valid())
  2629. << "streaming path: " << c.path << ", " << to_string(handle.error);
  2630. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  2631. }
  2632. }
  2633. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  2634. // The `set_path_encode(false)` contract — transmit the supplied target
  2635. // verbatim — must hold for the streaming API too.
  2636. Server svr;
  2637. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  2638. std::string target;
  2639. svr.Get("/foo", [&](const Request &req, Response &res) {
  2640. target = req.target;
  2641. res.status = StatusCode::OK_200;
  2642. });
  2643. auto port = svr.bind_to_any_port(HOST);
  2644. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2645. auto se = detail::scope_exit([&] {
  2646. svr.stop();
  2647. thread.join();
  2648. ASSERT_FALSE(svr.is_running());
  2649. });
  2650. svr.wait_until_ready();
  2651. {
  2652. Client cli(HOST, port);
  2653. cli.set_path_encode(false);
  2654. auto handle = cli.open_stream("GET", expected_target);
  2655. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  2656. EXPECT_EQ(expected_target, target);
  2657. }
  2658. }
  2659. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  2660. // With path encoding enabled a CR/LF in the target is percent-encoded
  2661. // rather than rejected, matching the buffered send path. The CR/LF guard in
  2662. // write_request_line still backstops `set_path_encode(false)`, which is
  2663. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  2664. Server svr;
  2665. // Captured before routing: the decoded path contains a newline, which a
  2666. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  2667. std::string target;
  2668. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  2669. target = req.target;
  2670. res.status = StatusCode::OK_200;
  2671. return Server::HandlerResponse::Handled;
  2672. });
  2673. auto port = svr.bind_to_any_port(HOST);
  2674. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2675. auto se = detail::scope_exit([&] {
  2676. svr.stop();
  2677. thread.join();
  2678. ASSERT_FALSE(svr.is_running());
  2679. });
  2680. svr.wait_until_ready();
  2681. {
  2682. Client cli(HOST, port);
  2683. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  2684. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  2685. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  2686. }
  2687. }
  2688. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  2689. // Nothing may reach the wire: a raw CR/LF target would split the request
  2690. // line and inject headers.
  2691. Server svr;
  2692. // Pre-routing so that "not called" means nothing reached the server at all,
  2693. // rather than merely failing to match a handler pattern.
  2694. auto handler_called = false;
  2695. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  2696. handler_called = true;
  2697. res.status = StatusCode::OK_200;
  2698. return Server::HandlerResponse::Handled;
  2699. });
  2700. auto port = svr.bind_to_any_port(HOST);
  2701. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2702. auto se = detail::scope_exit([&] {
  2703. svr.stop();
  2704. thread.join();
  2705. ASSERT_FALSE(svr.is_running());
  2706. });
  2707. svr.wait_until_ready();
  2708. {
  2709. Client cli(HOST, port);
  2710. cli.set_path_encode(false);
  2711. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  2712. EXPECT_FALSE(handle.is_valid());
  2713. EXPECT_EQ(Error::Write, handle.error);
  2714. EXPECT_FALSE(handler_called);
  2715. }
  2716. }
  2717. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  2718. // Which of the two branches runs is decided by whether the query component
  2719. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  2720. // an empty query and must still fall back to building one from
  2721. // `req.params`, while a non-empty query must win over `req.params`.
  2722. Server svr;
  2723. std::string target;
  2724. svr.Get("/foo", [&](const Request &req, Response &res) {
  2725. target = req.target;
  2726. res.status = StatusCode::OK_200;
  2727. });
  2728. auto port = svr.bind_to_any_port(HOST);
  2729. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  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. // Trailing `?` -> empty query component -> `req.params` is used.
  2738. Client cli(HOST, port);
  2739. Request req;
  2740. req.method = "GET";
  2741. req.path = "/foo?";
  2742. req.params.emplace("a", "1");
  2743. target.clear();
  2744. auto res = cli.send(req);
  2745. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2746. EXPECT_EQ("/foo?a=1", target);
  2747. }
  2748. {
  2749. // Non-empty query in `req.path` -> `req.params` is not appended.
  2750. Client cli(HOST, port);
  2751. Request req;
  2752. req.method = "GET";
  2753. req.path = "/foo?b=2";
  2754. req.params.emplace("a", "1");
  2755. target.clear();
  2756. auto res = cli.send(req);
  2757. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2758. EXPECT_EQ("/foo?b=2", target);
  2759. }
  2760. }
  2761. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  2762. Server svr;
  2763. svr.Get("/", [](const Request &req, Response &) {
  2764. EXPECT_EQ("\x0A", req.get_param_value("something"));
  2765. });
  2766. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2767. auto se = detail::scope_exit([&] {
  2768. svr.stop();
  2769. thread.join();
  2770. ASSERT_FALSE(svr.is_running());
  2771. });
  2772. svr.wait_until_ready();
  2773. {
  2774. Client cli(HOST, PORT);
  2775. cli.set_path_encode(false);
  2776. auto res = cli.Get("/?something=%0A");
  2777. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2778. EXPECT_EQ(StatusCode::OK_200, res->status);
  2779. }
  2780. }
  2781. TEST(BindServerTest, BindDualStack) {
  2782. Server svr;
  2783. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2784. res.set_content("Hello World!", "text/plain");
  2785. });
  2786. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  2787. auto se = detail::scope_exit([&] {
  2788. svr.stop();
  2789. thread.join();
  2790. ASSERT_FALSE(svr.is_running());
  2791. });
  2792. svr.wait_until_ready();
  2793. {
  2794. Client cli("127.0.0.1", PORT);
  2795. auto res = cli.Get("/1");
  2796. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2797. EXPECT_EQ(StatusCode::OK_200, res->status);
  2798. EXPECT_EQ("Hello World!", res->body);
  2799. }
  2800. {
  2801. Client cli("::1", PORT);
  2802. auto res = cli.Get("/1");
  2803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2804. EXPECT_EQ(StatusCode::OK_200, res->status);
  2805. EXPECT_EQ("Hello World!", res->body);
  2806. }
  2807. }
  2808. TEST(BindServerTest, BindAndListenSeparately) {
  2809. Server svr;
  2810. int port = svr.bind_to_any_port("0.0.0.0");
  2811. ASSERT_TRUE(svr.is_valid());
  2812. ASSERT_TRUE(port > 0);
  2813. svr.stop();
  2814. }
  2815. #ifdef CPPHTTPLIB_SSL_ENABLED
  2816. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  2817. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  2818. CLIENT_CA_CERT_DIR);
  2819. int port = svr.bind_to_any_port("0.0.0.0");
  2820. ASSERT_TRUE(svr.is_valid());
  2821. ASSERT_TRUE(port > 0);
  2822. svr.stop();
  2823. }
  2824. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  2825. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  2826. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  2827. int port = svr.bind_to_any_port("0.0.0.0");
  2828. ASSERT_TRUE(svr.is_valid());
  2829. ASSERT_TRUE(port > 0);
  2830. svr.stop();
  2831. }
  2832. TEST(BindServerTest, UpdateCertsPem) {
  2833. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2834. int port = svr.bind_to_any_port("0.0.0.0");
  2835. ASSERT_TRUE(svr.is_valid());
  2836. ASSERT_TRUE(port > 0);
  2837. // Read PEM files
  2838. std::string cert_pem, key_pem, ca_pem;
  2839. read_file(SERVER_CERT_FILE, cert_pem);
  2840. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2841. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2842. // Update server certificates using PEM API
  2843. ASSERT_TRUE(
  2844. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2845. ASSERT_TRUE(svr.is_valid());
  2846. svr.stop();
  2847. }
  2848. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  2849. // Start server with client CA (enables client auth)
  2850. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2851. ASSERT_TRUE(svr.is_valid());
  2852. bool handler_called = false;
  2853. svr.Get("/test", [&](const Request &req, Response &res) {
  2854. handler_called = true;
  2855. // Verify client certificate is present
  2856. auto cert = req.peer_cert();
  2857. EXPECT_TRUE(static_cast<bool>(cert));
  2858. res.set_content("ok", "text/plain");
  2859. });
  2860. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  2861. auto se = detail::scope_exit([&] {
  2862. svr.stop();
  2863. t.join();
  2864. ASSERT_FALSE(svr.is_running());
  2865. });
  2866. svr.wait_until_ready();
  2867. // Read PEM files
  2868. std::string cert_pem, key_pem, ca_pem;
  2869. read_file(SERVER_CERT_FILE, cert_pem);
  2870. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2871. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2872. // Update server certificates and client CA using PEM API while server running
  2873. ASSERT_TRUE(
  2874. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2875. // Connect with client certificate
  2876. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  2877. cli.enable_server_certificate_verification(false);
  2878. cli.set_connection_timeout(30);
  2879. auto res = cli.Get("/test");
  2880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2881. ASSERT_EQ(StatusCode::OK_200, res->status);
  2882. ASSERT_TRUE(handler_called);
  2883. EXPECT_EQ("ok", res->body);
  2884. }
  2885. #endif
  2886. TEST(ErrorHandlerTest, ContentLength) {
  2887. Server svr;
  2888. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2889. res.status = StatusCode::OK_200;
  2890. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2891. "text/html"); // <= Content-Length still 13
  2892. });
  2893. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2894. res.set_content("Hello World!\n", "text/plain");
  2895. res.status = 524;
  2896. });
  2897. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2898. auto se = detail::scope_exit([&] {
  2899. svr.stop();
  2900. thread.join();
  2901. ASSERT_FALSE(svr.is_running());
  2902. });
  2903. svr.wait_until_ready();
  2904. {
  2905. Client cli(HOST, PORT);
  2906. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  2907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2908. EXPECT_EQ(StatusCode::OK_200, res->status);
  2909. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2910. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2911. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2912. }
  2913. }
  2914. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2915. TEST(ExceptionTest, WithoutExceptionHandler) {
  2916. Server svr;
  2917. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  2918. throw std::runtime_error("exception...");
  2919. });
  2920. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  2921. throw std::runtime_error("exception\r\n...");
  2922. });
  2923. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2924. auto se = detail::scope_exit([&] {
  2925. svr.stop();
  2926. listen_thread.join();
  2927. ASSERT_FALSE(svr.is_running());
  2928. });
  2929. svr.wait_until_ready();
  2930. Client cli("localhost", PORT);
  2931. {
  2932. auto res = cli.Get("/exception");
  2933. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2934. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2935. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2936. }
  2937. {
  2938. auto res = cli.Get("/unknown");
  2939. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2940. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2941. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2942. }
  2943. }
  2944. TEST(ExceptionTest, WithExceptionHandler) {
  2945. Server svr;
  2946. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  2947. std::exception_ptr ep) {
  2948. EXPECT_FALSE(ep == nullptr);
  2949. try {
  2950. std::rethrow_exception(ep);
  2951. } catch (std::exception &e) {
  2952. EXPECT_EQ("abc", std::string(e.what()));
  2953. } catch (...) {}
  2954. res.status = StatusCode::InternalServerError_500;
  2955. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2956. "text/html"); // <= Content-Length still 13 at this point
  2957. });
  2958. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2959. res.set_content("Hello World!\n", "text/plain");
  2960. throw std::runtime_error("abc");
  2961. });
  2962. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2963. auto se = detail::scope_exit([&] {
  2964. svr.stop();
  2965. thread.join();
  2966. ASSERT_FALSE(svr.is_running());
  2967. });
  2968. svr.wait_until_ready();
  2969. for (size_t i = 0; i < 10; i++) {
  2970. Client cli(HOST, PORT);
  2971. for (size_t j = 0; j < 100; j++) {
  2972. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  2973. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2974. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2975. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2976. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2977. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2978. }
  2979. cli.set_keep_alive(true);
  2980. for (size_t j = 0; j < 100; j++) {
  2981. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  2982. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2983. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2984. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2985. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2986. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2987. }
  2988. }
  2989. }
  2990. TEST(ExceptionTest, AndErrorHandler) {
  2991. Server svr;
  2992. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2993. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  2994. });
  2995. svr.set_exception_handler(
  2996. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  2997. EXPECT_FALSE(ep == nullptr);
  2998. try {
  2999. std::rethrow_exception(ep);
  3000. } catch (std::exception &e) {
  3001. res.set_content(e.what(), "text/html");
  3002. } catch (...) {}
  3003. res.status = StatusCode::InternalServerError_500;
  3004. });
  3005. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  3006. throw std::runtime_error("EXCEPTION");
  3007. });
  3008. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  3009. res.set_content("ERROR", "text/html");
  3010. res.status = StatusCode::InternalServerError_500;
  3011. });
  3012. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3013. auto se = detail::scope_exit([&] {
  3014. svr.stop();
  3015. thread.join();
  3016. ASSERT_FALSE(svr.is_running());
  3017. });
  3018. svr.wait_until_ready();
  3019. Client cli(HOST, PORT);
  3020. {
  3021. auto res = cli.Get("/exception");
  3022. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3023. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3024. EXPECT_EQ("EXCEPTION", res->body);
  3025. }
  3026. {
  3027. auto res = cli.Get("/error");
  3028. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3029. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3030. EXPECT_EQ("ERROR", res->body);
  3031. }
  3032. {
  3033. auto res = cli.Get("/invalid");
  3034. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3035. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3036. EXPECT_EQ("NOT_FOUND", res->body);
  3037. }
  3038. }
  3039. #endif
  3040. TEST(NoContentTest, ContentLength) {
  3041. Server svr;
  3042. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3043. res.status = StatusCode::NoContent_204;
  3044. });
  3045. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3046. auto se = detail::scope_exit([&] {
  3047. svr.stop();
  3048. thread.join();
  3049. ASSERT_FALSE(svr.is_running());
  3050. });
  3051. svr.wait_until_ready();
  3052. {
  3053. Client cli(HOST, PORT);
  3054. auto res = cli.Get("/hi");
  3055. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3056. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  3057. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3058. }
  3059. }
  3060. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  3061. #ifdef CPPHTTPLIB_SSL_ENABLED
  3062. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  3063. ASSERT_TRUE(svr.is_valid());
  3064. #else
  3065. Server svr;
  3066. #endif
  3067. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  3068. if (req.path == "/routing_handler") {
  3069. res.set_header("PRE_ROUTING", "on");
  3070. res.set_content("Routing Handler", "text/plain");
  3071. return httplib::Server::HandlerResponse::Handled;
  3072. }
  3073. return httplib::Server::HandlerResponse::Unhandled;
  3074. });
  3075. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3076. res.set_content("Error", "text/html");
  3077. });
  3078. svr.set_post_routing_handler([](const Request &req, Response &res) {
  3079. if (req.path == "/routing_handler") {
  3080. res.set_header("POST_ROUTING", "on");
  3081. }
  3082. });
  3083. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3084. res.set_content("Hello World!\n", "text/plain");
  3085. });
  3086. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3087. auto se = detail::scope_exit([&] {
  3088. svr.stop();
  3089. thread.join();
  3090. ASSERT_FALSE(svr.is_running());
  3091. });
  3092. svr.wait_until_ready();
  3093. {
  3094. #ifdef CPPHTTPLIB_SSL_ENABLED
  3095. SSLClient cli(HOST, PORT);
  3096. cli.enable_server_certificate_verification(false);
  3097. #else
  3098. Client cli(HOST, PORT);
  3099. #endif
  3100. auto res = cli.Get("/routing_handler");
  3101. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3102. EXPECT_EQ(StatusCode::OK_200, res->status);
  3103. EXPECT_EQ("Routing Handler", res->body);
  3104. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  3105. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  3106. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  3107. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  3108. }
  3109. {
  3110. #ifdef CPPHTTPLIB_SSL_ENABLED
  3111. SSLClient cli(HOST, PORT);
  3112. cli.enable_server_certificate_verification(false);
  3113. #else
  3114. Client cli(HOST, PORT);
  3115. #endif
  3116. auto res = cli.Get("/hi");
  3117. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3118. EXPECT_EQ(StatusCode::OK_200, res->status);
  3119. EXPECT_EQ("Hello World!\n", res->body);
  3120. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  3121. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  3122. }
  3123. {
  3124. #ifdef CPPHTTPLIB_SSL_ENABLED
  3125. SSLClient cli(HOST, PORT);
  3126. cli.enable_server_certificate_verification(false);
  3127. #else
  3128. Client cli(HOST, PORT);
  3129. #endif
  3130. auto res = cli.Get("/aaa");
  3131. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3132. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3133. EXPECT_EQ("Error", res->body);
  3134. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  3135. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  3136. }
  3137. }
  3138. TEST(RequestHandlerTest, PreRequestHandler) {
  3139. auto route_path = "/user/:user";
  3140. Server svr;
  3141. svr.Get("/hi", [](const Request &, Response &res) {
  3142. res.set_content("hi", "text/plain");
  3143. });
  3144. svr.Get(route_path, [](const Request &req, Response &res) {
  3145. res.set_content(req.path_params.at("user"), "text/plain");
  3146. });
  3147. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  3148. if (req.matched_route == route_path) {
  3149. auto user = req.path_params.at("user");
  3150. if (user != "john") {
  3151. res.status = StatusCode::Forbidden_403;
  3152. res.set_content("error", "text/html");
  3153. return Server::HandlerResponse::Handled;
  3154. }
  3155. }
  3156. return Server::HandlerResponse::Unhandled;
  3157. });
  3158. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3159. auto se = detail::scope_exit([&] {
  3160. svr.stop();
  3161. thread.join();
  3162. ASSERT_FALSE(svr.is_running());
  3163. });
  3164. svr.wait_until_ready();
  3165. Client cli(HOST, PORT);
  3166. {
  3167. auto res = cli.Get("/hi");
  3168. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3169. EXPECT_EQ(StatusCode::OK_200, res->status);
  3170. EXPECT_EQ("hi", res->body);
  3171. }
  3172. {
  3173. auto res = cli.Get("/user/john");
  3174. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3175. EXPECT_EQ(StatusCode::OK_200, res->status);
  3176. EXPECT_EQ("john", res->body);
  3177. }
  3178. {
  3179. auto res = cli.Get("/user/invalid-user");
  3180. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3181. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  3182. EXPECT_EQ("error", res->body);
  3183. }
  3184. }
  3185. // The pre-request handler must run before the request body is read, so a
  3186. // rejected request never forces the server to buffer a (potentially large)
  3187. // body. Here the posted body is larger than the payload limit: if the body
  3188. // were read first the server would answer 413, but because the pre-request
  3189. // handler runs first it answers 403 and the body is never read.
  3190. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  3191. Server svr;
  3192. svr.set_payload_max_length(8);
  3193. auto handler_ran = false;
  3194. svr.Post("/reject", [&](const Request &req, Response &res) {
  3195. handler_ran = true;
  3196. res.set_content(req.body, "text/plain");
  3197. });
  3198. svr.Post("/accept", [](const Request &req, Response &res) {
  3199. res.set_content(req.body, "text/plain");
  3200. });
  3201. svr.set_pre_request_handler([](const Request &req, Response &res) {
  3202. if (req.matched_route == "/reject") {
  3203. res.status = StatusCode::Forbidden_403;
  3204. res.set_content("denied", "text/plain");
  3205. return Server::HandlerResponse::Handled;
  3206. }
  3207. return Server::HandlerResponse::Unhandled;
  3208. });
  3209. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3210. auto se = detail::scope_exit([&] {
  3211. svr.stop();
  3212. thread.join();
  3213. ASSERT_FALSE(svr.is_running());
  3214. });
  3215. svr.wait_until_ready();
  3216. Client cli(HOST, PORT);
  3217. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  3218. // rejects with 403 before the body is read, so 413 is never reached.
  3219. {
  3220. auto res = cli.Post("/reject", "0123456789", "text/plain");
  3221. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3222. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  3223. EXPECT_EQ("denied", res->body);
  3224. EXPECT_FALSE(handler_ran);
  3225. }
  3226. // An approved route still reads the body and enforces the payload limit.
  3227. {
  3228. auto res = cli.Post("/accept", "0123456789", "text/plain");
  3229. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3230. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  3231. }
  3232. }
  3233. TEST(UserDataTest, BasicOperations) {
  3234. httplib::UserData ud;
  3235. // Initially empty
  3236. EXPECT_FALSE(ud.has("key"));
  3237. EXPECT_EQ(nullptr, ud.get<int>("key"));
  3238. // set and get
  3239. ud.set("key", 42);
  3240. EXPECT_TRUE(ud.has("key"));
  3241. auto *p = ud.get<int>("key");
  3242. ASSERT_NE(nullptr, p);
  3243. EXPECT_EQ(42, *p);
  3244. // Type mismatch → nullptr
  3245. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  3246. // Overwrite with different type
  3247. ud.set("key", std::string("hello"));
  3248. EXPECT_EQ(nullptr, ud.get<int>("key"));
  3249. auto *s = ud.get<std::string>("key");
  3250. ASSERT_NE(nullptr, s);
  3251. EXPECT_EQ("hello", *s);
  3252. // erase
  3253. ud.erase("key");
  3254. EXPECT_FALSE(ud.has("key"));
  3255. // clear
  3256. ud.set("a", 1);
  3257. ud.set("b", 2);
  3258. ud.clear();
  3259. EXPECT_FALSE(ud.has("a"));
  3260. EXPECT_FALSE(ud.has("b"));
  3261. }
  3262. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  3263. struct AuthCtx {
  3264. std::string user_id;
  3265. };
  3266. Server svr;
  3267. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  3268. res.user_data.set("auth", AuthCtx{"alice"});
  3269. return Server::HandlerResponse::Unhandled;
  3270. });
  3271. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  3272. auto *ctx = res.user_data.get<AuthCtx>("auth");
  3273. ASSERT_NE(nullptr, ctx);
  3274. res.set_content("Hello " + ctx->user_id, "text/plain");
  3275. });
  3276. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3277. auto se = detail::scope_exit([&] {
  3278. svr.stop();
  3279. thread.join();
  3280. ASSERT_FALSE(svr.is_running());
  3281. });
  3282. svr.wait_until_ready();
  3283. Client cli(HOST, PORT);
  3284. auto res = cli.Get("/me");
  3285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3286. EXPECT_EQ(StatusCode::OK_200, res->status);
  3287. EXPECT_EQ("Hello alice", res->body);
  3288. }
  3289. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  3290. struct RoleCtx {
  3291. std::string role;
  3292. };
  3293. Server svr;
  3294. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  3295. res.user_data.set("role", RoleCtx{"admin"});
  3296. return Server::HandlerResponse::Unhandled;
  3297. });
  3298. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  3299. auto *ctx = res.user_data.get<RoleCtx>("role");
  3300. ASSERT_NE(nullptr, ctx);
  3301. res.set_content(ctx->role, "text/plain");
  3302. });
  3303. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3304. auto se = detail::scope_exit([&] {
  3305. svr.stop();
  3306. thread.join();
  3307. ASSERT_FALSE(svr.is_running());
  3308. });
  3309. svr.wait_until_ready();
  3310. Client cli(HOST, PORT);
  3311. auto res = cli.Get("/role");
  3312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3313. EXPECT_EQ(StatusCode::OK_200, res->status);
  3314. EXPECT_EQ("admin", res->body);
  3315. }
  3316. TEST(InvalidFormatTest, StatusCode) {
  3317. Server svr;
  3318. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3319. res.set_content("Hello World!\n", "text/plain");
  3320. res.status = 9999; // Status should be a three-digit code...
  3321. });
  3322. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3323. auto se = detail::scope_exit([&] {
  3324. svr.stop();
  3325. thread.join();
  3326. ASSERT_FALSE(svr.is_running());
  3327. });
  3328. svr.wait_until_ready();
  3329. {
  3330. Client cli(HOST, PORT);
  3331. auto res = cli.Get("/hi");
  3332. ASSERT_FALSE(res);
  3333. }
  3334. }
  3335. TEST(URLFragmentTest, WithFragment) {
  3336. Server svr;
  3337. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  3338. EXPECT_TRUE(req.target == "/hi");
  3339. });
  3340. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3341. auto se = detail::scope_exit([&] {
  3342. svr.stop();
  3343. thread.join();
  3344. ASSERT_FALSE(svr.is_running());
  3345. });
  3346. svr.wait_until_ready();
  3347. {
  3348. Client cli(HOST, PORT);
  3349. auto res = cli.Get("/hi#key1=val1=key2=val2");
  3350. EXPECT_TRUE(res);
  3351. EXPECT_EQ(StatusCode::OK_200, res->status);
  3352. res = cli.Get("/hi%23key1=val1=key2=val2");
  3353. EXPECT_TRUE(res);
  3354. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3355. }
  3356. }
  3357. TEST(HeaderWriter, SetHeaderWriter) {
  3358. Server svr;
  3359. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  3360. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  3361. return detail::write_headers(strm, hdrs);
  3362. });
  3363. svr.Get("/hi", [](const Request &req, Response &res) {
  3364. auto it = req.headers.find("CustomClientHeader");
  3365. EXPECT_TRUE(it != req.headers.end());
  3366. EXPECT_EQ(it->second, "CustomClientValue");
  3367. res.set_content("Hello World!\n", "text/plain");
  3368. });
  3369. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3370. auto se = detail::scope_exit([&] {
  3371. svr.stop();
  3372. thread.join();
  3373. ASSERT_FALSE(svr.is_running());
  3374. });
  3375. svr.wait_until_ready();
  3376. {
  3377. Client cli(HOST, PORT);
  3378. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  3379. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  3380. return detail::write_headers(strm, hdrs);
  3381. });
  3382. auto res = cli.Get("/hi");
  3383. EXPECT_TRUE(res);
  3384. EXPECT_EQ(StatusCode::OK_200, res->status);
  3385. auto it = res->headers.find("CustomServerHeader");
  3386. EXPECT_TRUE(it != res->headers.end());
  3387. EXPECT_EQ(it->second, "CustomServerValue");
  3388. }
  3389. }
  3390. class ServerTest : public ::testing::Test {
  3391. protected:
  3392. ServerTest()
  3393. : cli_(HOST, PORT)
  3394. #ifdef CPPHTTPLIB_SSL_ENABLED
  3395. ,
  3396. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  3397. #endif
  3398. {
  3399. #ifdef CPPHTTPLIB_SSL_ENABLED
  3400. cli_.enable_server_certificate_verification(false);
  3401. #endif
  3402. // Allow LARGE_DATA (100MB) responses
  3403. cli_.set_payload_max_length(200 * 1024 * 1024);
  3404. }
  3405. virtual void SetUp() {
  3406. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  3407. svr_.set_payload_max_length(200 * 1024 * 1024);
  3408. svr_.set_mount_point("/", "./www");
  3409. svr_.set_mount_point("/mount", "./www2");
  3410. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  3411. svr_.Get("/hi",
  3412. [&](const Request & /*req*/, Response &res) {
  3413. res.set_content("Hello World!", "text/plain");
  3414. })
  3415. .Get("/file_content",
  3416. [&](const Request & /*req*/, Response &res) {
  3417. res.set_file_content("./www/dir/test.html");
  3418. })
  3419. .Get("/file_content_with_content_type",
  3420. [&](const Request & /*req*/, Response &res) {
  3421. res.set_file_content("./www/file", "text/plain");
  3422. })
  3423. .Get("/invalid_file_content",
  3424. [&](const Request & /*req*/, Response &res) {
  3425. res.set_file_content("./www/dir/invalid_file_path");
  3426. })
  3427. .Get("/http_response_splitting",
  3428. [&](const Request & /*req*/, Response &res) {
  3429. res.set_header("a", "1\r\nSet-Cookie: a=1");
  3430. EXPECT_EQ(0U, res.headers.size());
  3431. EXPECT_FALSE(res.has_header("a"));
  3432. res.set_header("a", "1\nSet-Cookie: a=1");
  3433. EXPECT_EQ(0U, res.headers.size());
  3434. EXPECT_FALSE(res.has_header("a"));
  3435. res.set_header("a", "1\rSet-Cookie: a=1");
  3436. EXPECT_EQ(0U, res.headers.size());
  3437. EXPECT_FALSE(res.has_header("a"));
  3438. res.set_header("a\r\nb", "0");
  3439. EXPECT_EQ(0U, res.headers.size());
  3440. EXPECT_FALSE(res.has_header("a"));
  3441. res.set_header("a\rb", "0");
  3442. EXPECT_EQ(0U, res.headers.size());
  3443. EXPECT_FALSE(res.has_header("a"));
  3444. res.set_header("a\nb", "0");
  3445. EXPECT_EQ(0U, res.headers.size());
  3446. EXPECT_FALSE(res.has_header("a"));
  3447. res.set_redirect("1\r\nSet-Cookie: a=1");
  3448. EXPECT_EQ(0U, res.headers.size());
  3449. EXPECT_FALSE(res.has_header("Location"));
  3450. })
  3451. .Get("/slow",
  3452. [&](const Request & /*req*/, Response &res) {
  3453. std::this_thread::sleep_for(std::chrono::seconds(4));
  3454. res.set_content("slow", "text/plain");
  3455. })
  3456. #if 0
  3457. .Post("/slowpost",
  3458. [&](const Request & /*req*/, Response &res) {
  3459. std::this_thread::sleep_for(std::chrono::seconds(2));
  3460. res.set_content("slow", "text/plain");
  3461. })
  3462. #endif
  3463. .Get("/remote_addr",
  3464. [&](const Request &req, Response &res) {
  3465. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  3466. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  3467. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3468. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  3469. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  3470. #endif
  3471. res.set_content(req.remote_addr, "text/plain");
  3472. })
  3473. .Get("/local_addr",
  3474. [&](const Request &req, Response &res) {
  3475. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  3476. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  3477. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3478. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  3479. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  3480. #endif
  3481. auto local_addr = req.local_addr;
  3482. auto local_port = std::to_string(req.local_port);
  3483. res.set_content(local_addr.append(":").append(local_port),
  3484. "text/plain");
  3485. })
  3486. .Get("/endwith%",
  3487. [&](const Request & /*req*/, Response &res) {
  3488. res.set_content("Hello World!", "text/plain");
  3489. })
  3490. .Get("/a\\+\\+b",
  3491. [&](const Request &req, Response &res) {
  3492. ASSERT_TRUE(req.has_param("a +b"));
  3493. auto val = req.get_param_value("a +b");
  3494. res.set_content(val, "text/plain");
  3495. })
  3496. .Get("/", [&](const Request & /*req*/,
  3497. Response &res) { res.set_redirect("/hi"); })
  3498. .Post("/1",
  3499. [](const Request & /*req*/, Response &res) {
  3500. res.set_redirect("/2", StatusCode::SeeOther_303);
  3501. })
  3502. .Get("/2",
  3503. [](const Request & /*req*/, Response &res) {
  3504. res.set_content("redirected.", "text/plain");
  3505. res.status = StatusCode::OK_200;
  3506. })
  3507. .Post("/person",
  3508. [&](const Request &req, Response &res) {
  3509. if (req.has_param("name") && req.has_param("note")) {
  3510. persons_[req.get_param_value("name")] =
  3511. req.get_param_value("note");
  3512. } else {
  3513. res.status = StatusCode::BadRequest_400;
  3514. }
  3515. })
  3516. .Put("/person",
  3517. [&](const Request &req, Response &res) {
  3518. if (req.has_param("name") && req.has_param("note")) {
  3519. persons_[req.get_param_value("name")] =
  3520. req.get_param_value("note");
  3521. } else {
  3522. res.status = StatusCode::BadRequest_400;
  3523. }
  3524. })
  3525. .Get("/person/(.*)",
  3526. [&](const Request &req, Response &res) {
  3527. string name = req.matches[1];
  3528. if (persons_.find(name) != persons_.end()) {
  3529. auto note = persons_[name];
  3530. res.set_content(note, "text/plain");
  3531. } else {
  3532. res.status = StatusCode::NotFound_404;
  3533. }
  3534. })
  3535. .Delete("/person",
  3536. [&](const Request &req, Response &res) {
  3537. if (req.has_param("name")) {
  3538. string name = req.get_param_value("name");
  3539. if (persons_.find(name) != persons_.end()) {
  3540. persons_.erase(name);
  3541. res.set_content("DELETED", "text/plain");
  3542. } else {
  3543. res.status = StatusCode::NotFound_404;
  3544. }
  3545. } else {
  3546. res.status = StatusCode::BadRequest_400;
  3547. }
  3548. })
  3549. .Post("/x-www-form-urlencoded-json",
  3550. [&](const Request &req, Response &res) {
  3551. auto json = req.get_param_value("json");
  3552. ASSERT_EQ(JSON_DATA, json);
  3553. res.set_content(json, "appliation/json");
  3554. res.status = StatusCode::OK_200;
  3555. })
  3556. .Get("/streamed-chunked",
  3557. [&](const Request & /*req*/, Response &res) {
  3558. res.set_chunked_content_provider(
  3559. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  3560. sink.os << "123";
  3561. sink.os << "456";
  3562. sink.os << "789";
  3563. sink.done();
  3564. return true;
  3565. });
  3566. })
  3567. .Get("/streamed-chunked-with-prohibited-trailer",
  3568. [&](const Request & /*req*/, Response &res) {
  3569. auto i = new int(0);
  3570. // Declare both a prohibited trailer (Content-Length) and an
  3571. // allowed one
  3572. res.set_header("Trailer", "Content-Length, X-Allowed");
  3573. res.set_chunked_content_provider(
  3574. "text/plain",
  3575. [i](size_t /*offset*/, DataSink &sink) {
  3576. switch (*i) {
  3577. case 0: sink.os << "123"; break;
  3578. case 1: sink.os << "456"; break;
  3579. case 2: sink.os << "789"; break;
  3580. case 3: {
  3581. sink.done_with_trailer(
  3582. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  3583. } break;
  3584. }
  3585. (*i)++;
  3586. return true;
  3587. },
  3588. [i](bool success) {
  3589. EXPECT_TRUE(success);
  3590. delete i;
  3591. });
  3592. })
  3593. .Get("/streamed-chunked2",
  3594. [&](const Request & /*req*/, Response &res) {
  3595. auto i = new int(0);
  3596. res.set_chunked_content_provider(
  3597. "text/plain",
  3598. [i](size_t /*offset*/, DataSink &sink) {
  3599. switch (*i) {
  3600. case 0: sink.os << "123"; break;
  3601. case 1: sink.os << "456"; break;
  3602. case 2: sink.os << "789"; break;
  3603. case 3: sink.done(); break;
  3604. }
  3605. (*i)++;
  3606. return true;
  3607. },
  3608. [i](bool success) {
  3609. EXPECT_TRUE(success);
  3610. delete i;
  3611. });
  3612. })
  3613. .Get("/streamed-chunked-with-trailer",
  3614. [&](const Request & /*req*/, Response &res) {
  3615. auto i = new int(0);
  3616. res.set_header("Trailer", "Dummy1, Dummy2");
  3617. res.set_chunked_content_provider(
  3618. "text/plain",
  3619. [i](size_t /*offset*/, DataSink &sink) {
  3620. switch (*i) {
  3621. case 0: sink.os << "123"; break;
  3622. case 1: sink.os << "456"; break;
  3623. case 2: sink.os << "789"; break;
  3624. case 3: {
  3625. sink.done_with_trailer(
  3626. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  3627. } break;
  3628. }
  3629. (*i)++;
  3630. return true;
  3631. },
  3632. [i](bool success) {
  3633. EXPECT_TRUE(success);
  3634. delete i;
  3635. });
  3636. })
  3637. .Get("/streamed",
  3638. [&](const Request & /*req*/, Response &res) {
  3639. res.set_content_provider(
  3640. 6, "text/plain",
  3641. [](size_t offset, size_t /*length*/, DataSink &sink) {
  3642. sink.os << (offset < 3 ? "a" : "b");
  3643. return true;
  3644. });
  3645. })
  3646. .Get("/streamed-without-length",
  3647. [&](const Request & /*req*/, Response &res) {
  3648. auto data = new std::string("abcdefg");
  3649. res.set_content_provider(
  3650. "text/plain",
  3651. [data](size_t offset, DataSink &sink) {
  3652. if (offset < data->size()) {
  3653. sink.os << data->substr(offset);
  3654. }
  3655. sink.done();
  3656. return true;
  3657. },
  3658. [data](bool success) {
  3659. EXPECT_TRUE(success);
  3660. delete data;
  3661. });
  3662. })
  3663. .Get("/streamed-with-range",
  3664. [&](const Request &req, Response &res) {
  3665. auto data = new std::string("abcdefg");
  3666. res.set_content_provider(
  3667. data->size(), "text/plain",
  3668. [data](size_t offset, size_t length, DataSink &sink) {
  3669. size_t DATA_CHUNK_SIZE = 4;
  3670. const auto &d = *data;
  3671. auto out_len =
  3672. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  3673. auto ret =
  3674. sink.write(&d[static_cast<size_t>(offset)], out_len);
  3675. EXPECT_TRUE(ret);
  3676. return true;
  3677. },
  3678. [data, &req](bool success) {
  3679. EXPECT_EQ(success, !req.has_param("error"));
  3680. delete data;
  3681. });
  3682. })
  3683. .Get("/streamed-cancel",
  3684. [&](const Request & /*req*/, Response &res) {
  3685. res.set_content_provider(
  3686. size_t(-1), "text/plain",
  3687. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  3688. sink.os << "data_chunk";
  3689. return true;
  3690. });
  3691. })
  3692. .Get("/regex-with-delimiter",
  3693. [&](const Request &req, Response & /*res*/) {
  3694. ASSERT_TRUE(req.has_param("key"));
  3695. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  3696. })
  3697. .Get("/with-range",
  3698. [&](const Request & /*req*/, Response &res) {
  3699. res.set_content("abcdefg", "text/plain");
  3700. })
  3701. .Get("/test-start-time",
  3702. [&](const Request &req, Response & /*res*/) {
  3703. EXPECT_NE(req.start_time_,
  3704. std::chrono::steady_clock::time_point::min());
  3705. })
  3706. .Get("/with-range-customized-response",
  3707. [&](const Request & /*req*/, Response &res) {
  3708. res.status = StatusCode::BadRequest_400;
  3709. res.set_content(JSON_DATA, "application/json");
  3710. })
  3711. .Post("/chunked",
  3712. [&](const Request &req, Response & /*res*/) {
  3713. EXPECT_EQ(req.body, "dechunked post body");
  3714. })
  3715. .Post("/large-chunked",
  3716. [&](const Request &req, Response & /*res*/) {
  3717. std::string expected(6 * 30 * 1024u, 'a');
  3718. EXPECT_EQ(req.body, expected);
  3719. })
  3720. .Post("/multipart",
  3721. [&](const Request &req, Response & /*res*/) {
  3722. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  3723. req.form.get_field_count("text2") +
  3724. req.form.get_field_count("file3") +
  3725. req.form.get_field_count("file4"));
  3726. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  3727. req.form.get_file_count("file2"));
  3728. ASSERT_TRUE(!req.form.has_file("???"));
  3729. ASSERT_TRUE(!req.form.has_field("???"));
  3730. ASSERT_TRUE(req.body.empty());
  3731. {
  3732. const auto &text = req.form.get_field("text1");
  3733. EXPECT_EQ("text default", text);
  3734. }
  3735. {
  3736. const auto &text = req.form.get_field("text2");
  3737. EXPECT_EQ("aωb", text);
  3738. }
  3739. {
  3740. const auto &file = req.form.get_file("file1");
  3741. EXPECT_EQ("hello.txt", file.filename);
  3742. EXPECT_EQ("text/plain", file.content_type);
  3743. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3744. }
  3745. {
  3746. const auto &file = req.form.get_file("file2");
  3747. EXPECT_EQ("world.json", file.filename);
  3748. EXPECT_EQ("application/json", file.content_type);
  3749. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  3750. }
  3751. {
  3752. const auto &text = req.form.get_field("file3");
  3753. EXPECT_EQ(0u, text.size());
  3754. }
  3755. {
  3756. const auto &text = req.form.get_field("file4");
  3757. EXPECT_EQ(0u, text.size());
  3758. }
  3759. })
  3760. .Post("/multipart/multi_file_values",
  3761. [&](const Request &req, Response & /*res*/) {
  3762. EXPECT_EQ(3u, req.form.get_field_count("text") +
  3763. req.form.get_field_count("multi_text1"));
  3764. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  3765. ASSERT_TRUE(!req.form.has_file("???"));
  3766. ASSERT_TRUE(!req.form.has_field("???"));
  3767. ASSERT_TRUE(req.body.empty());
  3768. {
  3769. const auto &text = req.form.get_field("text");
  3770. EXPECT_EQ("default text", text);
  3771. }
  3772. {
  3773. const auto &text1_values = req.form.get_fields("multi_text1");
  3774. EXPECT_EQ(2u, text1_values.size());
  3775. EXPECT_EQ("aaaaa", text1_values[0]);
  3776. EXPECT_EQ("bbbbb", text1_values[1]);
  3777. }
  3778. {
  3779. const auto &file1_values = req.form.get_files("multi_file1");
  3780. EXPECT_EQ(2u, file1_values.size());
  3781. auto file1 = file1_values[0];
  3782. EXPECT_EQ(file1.filename, "hello.txt");
  3783. EXPECT_EQ(file1.content_type, "text/plain");
  3784. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  3785. auto file2 = file1_values[1];
  3786. EXPECT_EQ(file2.filename, "world.json");
  3787. EXPECT_EQ(file2.content_type, "application/json");
  3788. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  3789. }
  3790. })
  3791. .Post("/empty",
  3792. [&](const Request &req, Response &res) {
  3793. EXPECT_EQ(req.body, "");
  3794. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  3795. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3796. res.set_content("empty", "text/plain");
  3797. })
  3798. .Post("/empty-no-content-type",
  3799. [&](const Request &req, Response &res) {
  3800. EXPECT_EQ(req.body, "");
  3801. EXPECT_FALSE(req.has_header("Content-Type"));
  3802. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3803. res.set_content("empty-no-content-type", "text/plain");
  3804. })
  3805. .Post("/path-only",
  3806. [&](const Request &req, Response &res) {
  3807. EXPECT_EQ(req.body, "");
  3808. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3809. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3810. res.set_content("path-only", "text/plain");
  3811. })
  3812. .Post("/path-headers-only",
  3813. [&](const Request &req, Response &res) {
  3814. EXPECT_EQ(req.body, "");
  3815. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3816. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3817. EXPECT_EQ("world", req.get_header_value("hello"));
  3818. EXPECT_EQ("world2", req.get_header_value("hello2"));
  3819. res.set_content("path-headers-only", "text/plain");
  3820. })
  3821. .Post("/post-large",
  3822. [&](const Request &req, Response &res) {
  3823. EXPECT_EQ(req.body, LARGE_DATA);
  3824. res.set_content(req.body, "text/plain");
  3825. })
  3826. .Post("/post-loopback",
  3827. [&](const Request &, Response &res,
  3828. ContentReader const &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. res.set_content(body, "text/plain");
  3835. })
  3836. .Put("/put-loopback",
  3837. [&](const Request &, Response &res,
  3838. ContentReader const &content_reader) {
  3839. std::string body;
  3840. content_reader([&](const char *data, size_t data_length) {
  3841. body.append(data, data_length);
  3842. return true;
  3843. });
  3844. res.set_content(body, "text/plain");
  3845. })
  3846. .Patch("/patch-loopback",
  3847. [&](const Request &, Response &res,
  3848. ContentReader const &content_reader) {
  3849. std::string body;
  3850. content_reader([&](const char *data, size_t data_length) {
  3851. body.append(data, data_length);
  3852. return true;
  3853. });
  3854. res.set_content(body, "text/plain");
  3855. })
  3856. .Put("/empty-no-content-type",
  3857. [&](const Request &req, Response &res) {
  3858. EXPECT_EQ(req.body, "");
  3859. EXPECT_FALSE(req.has_header("Content-Type"));
  3860. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3861. res.set_content("empty-no-content-type", "text/plain");
  3862. })
  3863. .Put("/put",
  3864. [&](const Request &req, Response &res) {
  3865. EXPECT_EQ(req.body, "PUT");
  3866. res.set_content(req.body, "text/plain");
  3867. })
  3868. .Put("/put-large",
  3869. [&](const Request &req, Response &res) {
  3870. EXPECT_EQ(req.body, LARGE_DATA);
  3871. res.set_content(req.body, "text/plain");
  3872. })
  3873. .Patch("/patch",
  3874. [&](const Request &req, Response &res) {
  3875. EXPECT_EQ(req.body, "PATCH");
  3876. res.set_content(req.body, "text/plain");
  3877. })
  3878. .Delete("/delete",
  3879. [&](const Request & /*req*/, Response &res) {
  3880. res.set_content("DELETE", "text/plain");
  3881. })
  3882. .Delete("/delete-body",
  3883. [&](const Request &req, Response &res) {
  3884. EXPECT_EQ(req.body, "content");
  3885. res.set_content(req.body, "text/plain");
  3886. })
  3887. .Options(R"(\*)",
  3888. [&](const Request & /*req*/, Response &res) {
  3889. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  3890. })
  3891. .Get("/request-target",
  3892. [&](const Request &req, Response & /*res*/) {
  3893. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  3894. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  3895. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  3896. })
  3897. .Get("/long-query-value",
  3898. [&](const Request &req, Response & /*res*/) {
  3899. EXPECT_EQ(LONG_QUERY_URL, req.target);
  3900. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  3901. })
  3902. .Get("/too-long-query-value",
  3903. [&](const Request &req, Response & /*res*/) {
  3904. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  3905. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  3906. })
  3907. .Get("/array-param",
  3908. [&](const Request &req, Response & /*res*/) {
  3909. EXPECT_EQ(3u, req.get_param_value_count("array"));
  3910. EXPECT_EQ("value1", req.get_param_value("array", 0));
  3911. EXPECT_EQ("value2", req.get_param_value("array", 1));
  3912. EXPECT_EQ("value3", req.get_param_value("array", 2));
  3913. })
  3914. .Get("/array-param-values",
  3915. [&](const Request &req, Response & /*res*/) {
  3916. auto values = req.get_param_values("array");
  3917. EXPECT_EQ(3u, values.size());
  3918. EXPECT_EQ("value1", values[0]);
  3919. EXPECT_EQ("value2", values[1]);
  3920. EXPECT_EQ("value3", values[2]);
  3921. auto empty = req.get_param_values("nonexistent");
  3922. EXPECT_TRUE(empty.empty());
  3923. })
  3924. .Post("/validate-no-multiple-headers",
  3925. [&](const Request &req, Response & /*res*/) {
  3926. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  3927. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  3928. })
  3929. .Post("/content_receiver",
  3930. [&](const Request &req, Response &res,
  3931. const ContentReader &content_reader) {
  3932. if (req.is_multipart_form_data()) {
  3933. std::vector<FormData> items;
  3934. content_reader(
  3935. [&](const FormData &file) {
  3936. items.push_back(file);
  3937. return true;
  3938. },
  3939. [&](const char *data, size_t data_length) {
  3940. items.back().content.append(data, data_length);
  3941. return true;
  3942. });
  3943. EXPECT_EQ(5u, items.size());
  3944. {
  3945. const auto &file = get_file_value(items, "text1");
  3946. EXPECT_TRUE(file.filename.empty());
  3947. EXPECT_EQ("text default", file.content);
  3948. }
  3949. {
  3950. const auto &file = get_file_value(items, "text2");
  3951. EXPECT_TRUE(file.filename.empty());
  3952. EXPECT_EQ("aωb", file.content);
  3953. }
  3954. {
  3955. const auto &file = get_file_value(items, "file1");
  3956. EXPECT_EQ("hello.txt", file.filename);
  3957. EXPECT_EQ("text/plain", file.content_type);
  3958. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3959. }
  3960. {
  3961. const auto &file = get_file_value(items, "file2");
  3962. EXPECT_EQ("world.json", file.filename);
  3963. EXPECT_EQ("application/json", file.content_type);
  3964. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  3965. }
  3966. {
  3967. const auto &file = get_file_value(items, "file3");
  3968. EXPECT_TRUE(file.filename.empty());
  3969. EXPECT_EQ("application/octet-stream", file.content_type);
  3970. EXPECT_EQ(0u, file.content.size());
  3971. }
  3972. } else {
  3973. std::string body;
  3974. content_reader([&](const char *data, size_t data_length) {
  3975. EXPECT_EQ(7U, data_length);
  3976. body.append(data, data_length);
  3977. return true;
  3978. });
  3979. EXPECT_EQ(body, "content");
  3980. res.set_content(body, "text/plain");
  3981. }
  3982. })
  3983. .Put("/content_receiver",
  3984. [&](const Request & /*req*/, Response &res,
  3985. const ContentReader &content_reader) {
  3986. std::string body;
  3987. content_reader([&](const char *data, size_t data_length) {
  3988. body.append(data, data_length);
  3989. return true;
  3990. });
  3991. EXPECT_EQ(body, "content");
  3992. res.set_content(body, "text/plain");
  3993. })
  3994. .Patch("/content_receiver",
  3995. [&](const Request & /*req*/, Response &res,
  3996. const ContentReader &content_reader) {
  3997. std::string body;
  3998. content_reader([&](const char *data, size_t data_length) {
  3999. body.append(data, data_length);
  4000. return true;
  4001. });
  4002. EXPECT_EQ(body, "content");
  4003. res.set_content(body, "text/plain");
  4004. })
  4005. .Post("/query-string-and-body",
  4006. [&](const Request &req, Response & /*res*/) {
  4007. ASSERT_TRUE(req.has_param("key"));
  4008. EXPECT_EQ(req.get_param_value("key"), "value");
  4009. EXPECT_EQ(req.body, "content");
  4010. })
  4011. .Get("/last-request",
  4012. [&](const Request &req, Response & /*res*/) {
  4013. EXPECT_EQ("close", req.get_header_value("Connection"));
  4014. })
  4015. .Get(R"(/redirect/(\d+))",
  4016. [&](const Request &req, Response &res) {
  4017. auto num = std::stoi(req.matches[1]) + 1;
  4018. std::string url = "/redirect/" + std::to_string(num);
  4019. res.set_redirect(url);
  4020. })
  4021. .Post("/binary",
  4022. [&](const Request &req, Response &res) {
  4023. EXPECT_EQ(4U, req.body.size());
  4024. EXPECT_EQ("application/octet-stream",
  4025. req.get_header_value("Content-Type"));
  4026. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4027. res.set_content(req.body, "application/octet-stream");
  4028. })
  4029. .Put("/binary",
  4030. [&](const Request &req, Response &res) {
  4031. EXPECT_EQ(4U, req.body.size());
  4032. EXPECT_EQ("application/octet-stream",
  4033. req.get_header_value("Content-Type"));
  4034. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4035. res.set_content(req.body, "application/octet-stream");
  4036. })
  4037. .Patch("/binary",
  4038. [&](const Request &req, Response &res) {
  4039. EXPECT_EQ(4U, req.body.size());
  4040. EXPECT_EQ("application/octet-stream",
  4041. req.get_header_value("Content-Type"));
  4042. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4043. res.set_content(req.body, "application/octet-stream");
  4044. })
  4045. .Delete("/binary",
  4046. [&](const Request &req, Response &res) {
  4047. EXPECT_EQ(4U, req.body.size());
  4048. EXPECT_EQ("application/octet-stream",
  4049. req.get_header_value("Content-Type"));
  4050. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4051. res.set_content(req.body, "application/octet-stream");
  4052. })
  4053. .Get("/issue1772",
  4054. [&](const Request & /*req*/, Response &res) {
  4055. res.status = 401;
  4056. res.set_header("WWW-Authenticate", "Basic realm=123456");
  4057. })
  4058. .Delete("/issue609",
  4059. [](const httplib::Request &, httplib::Response &res,
  4060. const httplib::ContentReader &) {
  4061. res.set_content("ok", "text/plain");
  4062. })
  4063. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  4064. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  4065. .Get("/compress",
  4066. [&](const Request & /*req*/, Response &res) {
  4067. res.set_content(
  4068. "12345678901234567890123456789012345678901234567890123456789"
  4069. "01234567890123456789012345678901234567890",
  4070. "text/plain");
  4071. })
  4072. .Get("/compress-with-charset",
  4073. [&](const Request & /*req*/, Response &res) {
  4074. res.set_content(
  4075. "12345678901234567890123456789012345678901234567890123456789"
  4076. "01234567890123456789012345678901234567890",
  4077. "application/json; charset=utf-8");
  4078. })
  4079. .Get("/nocompress",
  4080. [&](const Request & /*req*/, Response &res) {
  4081. res.set_content(
  4082. "12345678901234567890123456789012345678901234567890123456789"
  4083. "01234567890123456789012345678901234567890",
  4084. "application/octet-stream");
  4085. })
  4086. .Post("/compress-multipart",
  4087. [&](const Request &req, Response & /*res*/) {
  4088. EXPECT_EQ(2u, req.form.fields.size());
  4089. ASSERT_TRUE(!req.form.has_field("???"));
  4090. {
  4091. const auto &text = req.form.get_field("key1");
  4092. EXPECT_EQ("test", text);
  4093. }
  4094. {
  4095. const auto &text = req.form.get_field("key2");
  4096. EXPECT_EQ("--abcdefg123", text);
  4097. }
  4098. })
  4099. #endif
  4100. ;
  4101. persons_["john"] = "programmer";
  4102. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  4103. svr_.wait_until_ready();
  4104. }
  4105. virtual void TearDown() {
  4106. svr_.stop();
  4107. if (!request_threads_.empty()) {
  4108. std::this_thread::sleep_for(std::chrono::seconds(1));
  4109. for (auto &t : request_threads_) {
  4110. t.join();
  4111. }
  4112. }
  4113. t_.join();
  4114. }
  4115. map<string, string> persons_;
  4116. #ifdef CPPHTTPLIB_SSL_ENABLED
  4117. SSLClient cli_;
  4118. SSLServer svr_;
  4119. #else
  4120. Client cli_;
  4121. Server svr_;
  4122. #endif
  4123. thread t_;
  4124. std::vector<thread> request_threads_;
  4125. };
  4126. TEST_F(ServerTest, GetMethod200) {
  4127. auto res = cli_.Get("/hi");
  4128. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4129. EXPECT_EQ("HTTP/1.1", res->version);
  4130. EXPECT_EQ(StatusCode::OK_200, res->status);
  4131. EXPECT_EQ("OK", res->reason);
  4132. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4133. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  4134. EXPECT_EQ("Hello World!", res->body);
  4135. }
  4136. TEST_F(ServerTest, GetEmptyFile) {
  4137. auto res = cli_.Get("/empty_file");
  4138. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4139. EXPECT_EQ(StatusCode::OK_200, res->status);
  4140. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  4141. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  4142. EXPECT_EQ("", res->body);
  4143. }
  4144. TEST_F(ServerTest, GetFileContent) {
  4145. auto res = cli_.Get("/file_content");
  4146. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4147. EXPECT_EQ(StatusCode::OK_200, res->status);
  4148. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4149. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  4150. EXPECT_EQ("test.html", res->body);
  4151. }
  4152. TEST_F(ServerTest, GetFileContentWithRange) {
  4153. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  4154. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4155. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4156. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4157. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  4158. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  4159. EXPECT_EQ("est", res->body);
  4160. }
  4161. TEST_F(ServerTest, GetFileContentWithContentType) {
  4162. auto res = cli_.Get("/file_content_with_content_type");
  4163. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4164. EXPECT_EQ(StatusCode::OK_200, res->status);
  4165. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4166. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  4167. EXPECT_EQ("file\n", res->body);
  4168. }
  4169. TEST_F(ServerTest, GetInvalidFileContent) {
  4170. auto res = cli_.Get("/invalid_file_content");
  4171. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4172. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4173. }
  4174. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  4175. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  4176. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4177. EXPECT_EQ("HTTP/1.1", res->version);
  4178. EXPECT_EQ(StatusCode::OK_200, res->status);
  4179. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4180. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  4181. EXPECT_EQ("Hello World!", res->body);
  4182. }
  4183. TEST_F(ServerTest, GetMethod302) {
  4184. auto res = cli_.Get("/");
  4185. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4186. EXPECT_EQ(StatusCode::Found_302, res->status);
  4187. EXPECT_EQ("/hi", res->get_header_value("Location"));
  4188. }
  4189. TEST_F(ServerTest, GetMethod302Redirect) {
  4190. cli_.set_follow_location(true);
  4191. auto res = cli_.Get("/");
  4192. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4193. EXPECT_EQ(StatusCode::OK_200, res->status);
  4194. EXPECT_EQ("Hello World!", res->body);
  4195. EXPECT_EQ("/hi", res->location);
  4196. }
  4197. TEST_F(ServerTest, GetMethod404) {
  4198. auto res = cli_.Get("/invalid");
  4199. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4200. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4201. }
  4202. TEST_F(ServerTest, HeadMethod200) {
  4203. auto res = cli_.Head("/hi");
  4204. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4205. EXPECT_EQ(StatusCode::OK_200, res->status);
  4206. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4207. EXPECT_TRUE(res->body.empty());
  4208. }
  4209. TEST_F(ServerTest, HeadMethod200Static) {
  4210. auto res = cli_.Head("/mount/dir/index.html");
  4211. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4212. EXPECT_EQ(StatusCode::OK_200, res->status);
  4213. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4214. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  4215. EXPECT_TRUE(res->body.empty());
  4216. }
  4217. TEST_F(ServerTest, HeadMethod404) {
  4218. auto res = cli_.Head("/invalid");
  4219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4220. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4221. EXPECT_TRUE(res->body.empty());
  4222. }
  4223. TEST_F(ServerTest, GetMethodPersonJohn) {
  4224. auto res = cli_.Get("/person/john");
  4225. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4226. EXPECT_EQ(StatusCode::OK_200, res->status);
  4227. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4228. EXPECT_EQ("programmer", res->body);
  4229. }
  4230. TEST_F(ServerTest, PostMethod1) {
  4231. auto res = cli_.Get("/person/john1");
  4232. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4233. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4234. res = cli_.Post("/person", "name=john1&note=coder",
  4235. "application/x-www-form-urlencoded");
  4236. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4237. ASSERT_EQ(StatusCode::OK_200, res->status);
  4238. res = cli_.Get("/person/john1");
  4239. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4240. ASSERT_EQ(StatusCode::OK_200, res->status);
  4241. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4242. ASSERT_EQ("coder", res->body);
  4243. }
  4244. TEST_F(ServerTest, PostMethod2) {
  4245. auto res = cli_.Get("/person/john2");
  4246. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4247. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4248. Params params;
  4249. params.emplace("name", "john2");
  4250. params.emplace("note", "coder");
  4251. res = cli_.Post("/person", params);
  4252. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4253. ASSERT_EQ(StatusCode::OK_200, res->status);
  4254. res = cli_.Get("/person/john2");
  4255. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4256. ASSERT_EQ(StatusCode::OK_200, res->status);
  4257. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4258. ASSERT_EQ("coder", res->body);
  4259. }
  4260. TEST_F(ServerTest, PutMethod3) {
  4261. auto res = cli_.Get("/person/john3");
  4262. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4263. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4264. Params params;
  4265. params.emplace("name", "john3");
  4266. params.emplace("note", "coder");
  4267. res = cli_.Put("/person", params);
  4268. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4269. ASSERT_EQ(StatusCode::OK_200, res->status);
  4270. res = cli_.Get("/person/john3");
  4271. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4272. ASSERT_EQ(StatusCode::OK_200, res->status);
  4273. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4274. ASSERT_EQ("coder", res->body);
  4275. }
  4276. TEST_F(ServerTest, DeleteMethod1) {
  4277. auto res = cli_.Get("/person/john4");
  4278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4279. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4280. Params params;
  4281. params.emplace("name", "john4");
  4282. params.emplace("note", "coder");
  4283. res = cli_.Post("/person", params);
  4284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4285. ASSERT_EQ(StatusCode::OK_200, res->status);
  4286. res = cli_.Get("/person/john4");
  4287. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4288. ASSERT_EQ(StatusCode::OK_200, res->status);
  4289. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4290. ASSERT_EQ("coder", res->body);
  4291. Params delete_params;
  4292. delete_params.emplace("name", "john4");
  4293. res = cli_.Delete("/person", delete_params);
  4294. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4295. ASSERT_EQ(StatusCode::OK_200, res->status);
  4296. ASSERT_EQ("DELETED", res->body);
  4297. res = cli_.Get("/person/john4");
  4298. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4299. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4300. }
  4301. TEST_F(ServerTest, DeleteMethod2) {
  4302. auto res = cli_.Get("/person/john5");
  4303. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4304. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4305. Params params;
  4306. params.emplace("name", "john5");
  4307. params.emplace("note", "developer");
  4308. res = cli_.Post("/person", params);
  4309. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4310. ASSERT_EQ(StatusCode::OK_200, res->status);
  4311. res = cli_.Get("/person/john5");
  4312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4313. ASSERT_EQ(StatusCode::OK_200, res->status);
  4314. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4315. ASSERT_EQ("developer", res->body);
  4316. Params delete_params;
  4317. delete_params.emplace("name", "john5");
  4318. Headers headers;
  4319. headers.emplace("Custom-Header", "test-value");
  4320. res = cli_.Delete("/person", headers, delete_params);
  4321. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4322. ASSERT_EQ(StatusCode::OK_200, res->status);
  4323. ASSERT_EQ("DELETED", res->body);
  4324. res = cli_.Get("/person/john5");
  4325. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4326. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4327. }
  4328. TEST_F(ServerTest, DeleteMethod3) {
  4329. auto res = cli_.Get("/person/john6");
  4330. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4331. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4332. Params params;
  4333. params.emplace("name", "john6");
  4334. params.emplace("note", "tester");
  4335. res = cli_.Post("/person", params);
  4336. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4337. ASSERT_EQ(StatusCode::OK_200, res->status);
  4338. res = cli_.Get("/person/john6");
  4339. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4340. ASSERT_EQ(StatusCode::OK_200, res->status);
  4341. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4342. ASSERT_EQ("tester", res->body);
  4343. Params delete_params;
  4344. delete_params.emplace("name", "john6");
  4345. Headers headers;
  4346. headers.emplace("Custom-Header", "test-value");
  4347. res = cli_.Delete("/person", headers, delete_params, nullptr);
  4348. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4349. ASSERT_EQ(StatusCode::OK_200, res->status);
  4350. ASSERT_EQ("DELETED", res->body);
  4351. res = cli_.Get("/person/john6");
  4352. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4353. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4354. }
  4355. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  4356. Params params;
  4357. params.emplace("json", JSON_DATA);
  4358. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  4359. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4360. ASSERT_EQ(StatusCode::OK_200, res->status);
  4361. ASSERT_EQ(JSON_DATA, res->body);
  4362. }
  4363. TEST_F(ServerTest, PostEmptyContent) {
  4364. auto res = cli_.Post("/empty", "", "text/plain");
  4365. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4366. ASSERT_EQ(StatusCode::OK_200, res->status);
  4367. ASSERT_EQ("empty", res->body);
  4368. }
  4369. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  4370. auto res = cli_.Post("/empty-no-content-type");
  4371. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4372. ASSERT_EQ(StatusCode::OK_200, res->status);
  4373. ASSERT_EQ("empty-no-content-type", res->body);
  4374. }
  4375. TEST_F(ServerTest, PostPathOnly) {
  4376. auto res = cli_.Post("/path-only");
  4377. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4378. ASSERT_EQ(StatusCode::OK_200, res->status);
  4379. ASSERT_EQ("path-only", res->body);
  4380. }
  4381. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  4382. auto res = cli_.Post("/path-headers-only",
  4383. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  4384. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4385. ASSERT_EQ(StatusCode::OK_200, res->status);
  4386. ASSERT_EQ("path-headers-only", res->body);
  4387. }
  4388. TEST_F(ServerTest, PostLarge) {
  4389. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  4390. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4391. ASSERT_EQ(StatusCode::OK_200, res->status);
  4392. EXPECT_EQ(LARGE_DATA, res->body);
  4393. }
  4394. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  4395. auto res = cli_.Put("/empty-no-content-type");
  4396. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4397. ASSERT_EQ(StatusCode::OK_200, res->status);
  4398. ASSERT_EQ("empty-no-content-type", res->body);
  4399. }
  4400. TEST_F(ServerTest, GetMethodDir) {
  4401. auto res = cli_.Get("/dir/");
  4402. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4403. EXPECT_EQ(StatusCode::OK_200, res->status);
  4404. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4405. auto body = R"(<html>
  4406. <head>
  4407. </head>
  4408. <body>
  4409. <a href="/dir/test.html">Test</a>
  4410. <a href="/hi">hi</a>
  4411. </body>
  4412. </html>
  4413. )";
  4414. EXPECT_EQ(body, res->body);
  4415. }
  4416. TEST_F(ServerTest, GetMethodDirTest) {
  4417. auto res = cli_.Get("/dir/test.html");
  4418. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4419. EXPECT_EQ(StatusCode::OK_200, res->status);
  4420. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4421. EXPECT_EQ("test.html", res->body);
  4422. }
  4423. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  4424. auto res = cli_.Get("/dir/../dir/test.html");
  4425. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4426. EXPECT_EQ(StatusCode::OK_200, res->status);
  4427. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4428. EXPECT_EQ("test.html", res->body);
  4429. }
  4430. TEST_F(ServerTest, GetMethodInvalidPath) {
  4431. auto res = cli_.Get("/dir/../test.html");
  4432. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4433. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4434. }
  4435. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  4436. auto res = cli_.Get("/../www/dir/test.html");
  4437. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4438. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4439. }
  4440. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  4441. auto res = cli_.Get("/dir/../../www/dir/test.html");
  4442. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4443. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4444. }
  4445. TEST_F(ServerTest, GetMethodDirMountTest) {
  4446. auto res = cli_.Get("/mount/dir/test.html");
  4447. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4448. EXPECT_EQ(StatusCode::OK_200, res->status);
  4449. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4450. EXPECT_EQ("test.html", res->body);
  4451. }
  4452. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  4453. auto res = cli_.Get("/mount/dir/../dir/test.html");
  4454. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4455. EXPECT_EQ(StatusCode::OK_200, res->status);
  4456. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4457. EXPECT_EQ("test.html", res->body);
  4458. }
  4459. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  4460. auto res = cli_.Get("/mount/dir/../test.html");
  4461. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4462. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4463. }
  4464. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  4465. auto res = cli_.Get("/mount/dir/test.html%00.js");
  4466. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4467. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4468. }
  4469. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  4470. auto res = cli_.Get("/mount/../www2/dir/test.html");
  4471. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4472. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4473. }
  4474. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  4475. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  4476. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4477. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4478. }
  4479. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  4480. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  4481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4482. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4483. }
  4484. TEST_F(ServerTest, PostMethod303) {
  4485. auto res = cli_.Post("/1", "body", "text/plain");
  4486. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4487. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  4488. EXPECT_EQ("/2", res->get_header_value("Location"));
  4489. }
  4490. TEST_F(ServerTest, PostMethod303Redirect) {
  4491. cli_.set_follow_location(true);
  4492. auto res = cli_.Post("/1", "body", "text/plain");
  4493. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4494. EXPECT_EQ(StatusCode::OK_200, res->status);
  4495. EXPECT_EQ("redirected.", res->body);
  4496. EXPECT_EQ("/2", res->location);
  4497. }
  4498. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  4499. auto res = cli_.Get("/dir/test.abcde");
  4500. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4501. EXPECT_EQ(StatusCode::OK_200, res->status);
  4502. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4503. EXPECT_EQ("abcde", res->body);
  4504. }
  4505. TEST_F(ServerTest, StaticFileRange) {
  4506. auto res =
  4507. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  4508. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4509. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4510. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4511. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4512. EXPECT_EQ(true, res->has_header("Content-Range"));
  4513. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  4514. EXPECT_EQ(std::string("cd"), res->body);
  4515. }
  4516. TEST_F(ServerTest, StaticFileRanges) {
  4517. auto res = cli_.Get("/dir/test.abcde",
  4518. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  4519. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4520. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4521. EXPECT_TRUE(
  4522. res->get_header_value("Content-Type")
  4523. .find(
  4524. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  4525. 0);
  4526. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  4527. }
  4528. TEST_F(ServerTest, StaticFileRangeHead) {
  4529. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  4530. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4531. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4532. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4533. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4534. EXPECT_EQ(true, res->has_header("Content-Range"));
  4535. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  4536. }
  4537. TEST_F(ServerTest, StaticFileRangeBigFile) {
  4538. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  4539. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4540. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4541. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4542. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  4543. EXPECT_EQ(true, res->has_header("Content-Range"));
  4544. EXPECT_EQ("bytes 1048571-1048575/1048576",
  4545. res->get_header_value("Content-Range"));
  4546. EXPECT_EQ("LAST\n", res->body);
  4547. }
  4548. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  4549. auto res =
  4550. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  4551. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4552. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4553. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4554. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  4555. EXPECT_EQ(true, res->has_header("Content-Range"));
  4556. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  4557. }
  4558. TEST_F(ServerTest, StaticFileBigFile) {
  4559. auto res = cli_.Get("/dir/1MB.txt");
  4560. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4561. EXPECT_EQ(StatusCode::OK_200, res->status);
  4562. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4563. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  4564. }
  4565. TEST_F(ServerTest, InvalidBaseDirMount) {
  4566. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  4567. }
  4568. TEST_F(ServerTest, Binary) {
  4569. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  4570. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  4571. "application/octet-stream");
  4572. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4573. ASSERT_EQ(StatusCode::OK_200, res->status);
  4574. ASSERT_EQ(4U, res->body.size());
  4575. res = cli_.Put("/binary", binary.data(), binary.size(),
  4576. "application/octet-stream");
  4577. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4578. ASSERT_EQ(StatusCode::OK_200, res->status);
  4579. ASSERT_EQ(4U, res->body.size());
  4580. res = cli_.Patch("/binary", binary.data(), binary.size(),
  4581. "application/octet-stream");
  4582. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4583. ASSERT_EQ(StatusCode::OK_200, res->status);
  4584. ASSERT_EQ(4U, res->body.size());
  4585. res = cli_.Delete("/binary", binary.data(), binary.size(),
  4586. "application/octet-stream");
  4587. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4588. ASSERT_EQ(StatusCode::OK_200, res->status);
  4589. ASSERT_EQ(4U, res->body.size());
  4590. }
  4591. TEST_F(ServerTest, BinaryString) {
  4592. auto binary = std::string("\x00\x01\x02\x03", 4);
  4593. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  4594. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4595. ASSERT_EQ(StatusCode::OK_200, res->status);
  4596. ASSERT_EQ(4U, res->body.size());
  4597. res = cli_.Put("/binary", binary, "application/octet-stream");
  4598. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4599. ASSERT_EQ(StatusCode::OK_200, res->status);
  4600. ASSERT_EQ(4U, res->body.size());
  4601. res = cli_.Patch("/binary", binary, "application/octet-stream");
  4602. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4603. ASSERT_EQ(StatusCode::OK_200, res->status);
  4604. ASSERT_EQ(4U, res->body.size());
  4605. res = cli_.Delete("/binary", binary, "application/octet-stream");
  4606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4607. ASSERT_EQ(StatusCode::OK_200, res->status);
  4608. ASSERT_EQ(4U, res->body.size());
  4609. }
  4610. TEST_F(ServerTest, EmptyRequest) {
  4611. auto res = cli_.Get("");
  4612. ASSERT_TRUE(!res);
  4613. EXPECT_EQ(Error::Connection, res.error());
  4614. }
  4615. TEST_F(ServerTest, LongRequest) {
  4616. std::string request;
  4617. for (size_t i = 0; i < 545; i++) {
  4618. request += "/TooLongRequest";
  4619. }
  4620. request += "OK";
  4621. auto res = cli_.Get(request.c_str());
  4622. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4623. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4624. }
  4625. TEST_F(ServerTest, TooLongRequest) {
  4626. std::string request;
  4627. for (size_t i = 0; i < 546; i++) {
  4628. request += "/TooLongRequest";
  4629. }
  4630. request += "_NG";
  4631. auto start = std::chrono::high_resolution_clock::now();
  4632. cli_.set_keep_alive(true);
  4633. auto res = cli_.Get(request.c_str());
  4634. auto end = std::chrono::high_resolution_clock::now();
  4635. auto elapsed =
  4636. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  4637. .count();
  4638. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4639. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  4640. EXPECT_LE(elapsed, 1000);
  4641. EXPECT_EQ("close", res->get_header_value("Connection"));
  4642. EXPECT_FALSE(cli_.is_socket_open());
  4643. }
  4644. TEST_F(ServerTest, AlmostTooLongRequest) {
  4645. // test for #2046 - URI length check shouldn't include other content on req
  4646. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  4647. // leading /, space, HTTP/1.1)
  4648. std::string request =
  4649. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  4650. auto res = cli_.Get(request.c_str());
  4651. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4652. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4653. }
  4654. TEST_F(ServerTest, LongHeader) {
  4655. Request req;
  4656. req.method = "GET";
  4657. req.path = "/hi";
  4658. std::string host_and_port;
  4659. host_and_port += HOST;
  4660. host_and_port += ":";
  4661. host_and_port += std::to_string(PORT);
  4662. req.headers.emplace("Host", host_and_port.c_str());
  4663. req.headers.emplace("Accept", "*/*");
  4664. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4665. req.headers.emplace(
  4666. "Header-Name",
  4667. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4668. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4669. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4670. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4671. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4672. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4673. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4674. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4675. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4676. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4677. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4678. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4679. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4680. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4681. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4682. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4683. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4684. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4685. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4686. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4687. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4688. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4689. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4690. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4691. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4692. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4693. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4694. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4695. "@@@@@@@@@@@@@@@@");
  4696. auto res = std::make_shared<Response>();
  4697. auto error = Error::Success;
  4698. auto ret = cli_.send(req, *res, error);
  4699. ASSERT_TRUE(ret);
  4700. EXPECT_EQ(StatusCode::OK_200, res->status);
  4701. }
  4702. TEST_F(ServerTest, LongQueryValue) {
  4703. auto start = std::chrono::high_resolution_clock::now();
  4704. cli_.set_keep_alive(true);
  4705. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  4706. auto end = std::chrono::high_resolution_clock::now();
  4707. auto elapsed =
  4708. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  4709. .count();
  4710. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4711. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  4712. EXPECT_LE(elapsed, 1000);
  4713. EXPECT_EQ("close", res->get_header_value("Connection"));
  4714. EXPECT_FALSE(cli_.is_socket_open());
  4715. }
  4716. TEST_F(ServerTest, TooLongQueryValue) {
  4717. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  4718. ASSERT_FALSE(res);
  4719. EXPECT_EQ(Error::Read, res.error());
  4720. }
  4721. TEST_F(ServerTest, TooLongHeader) {
  4722. Request req;
  4723. req.method = "GET";
  4724. req.path = "/hi";
  4725. std::string host_and_port;
  4726. host_and_port += HOST;
  4727. host_and_port += ":";
  4728. host_and_port += std::to_string(PORT);
  4729. req.headers.emplace("Host", host_and_port.c_str());
  4730. req.headers.emplace("Accept", "*/*");
  4731. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4732. req.headers.emplace(
  4733. "Header-Name",
  4734. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4735. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4736. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4737. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4738. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4739. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4740. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4741. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4742. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4743. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4744. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4745. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4746. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4747. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4748. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4749. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4750. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4751. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4752. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4753. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4754. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4755. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4756. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4757. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4758. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4759. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4760. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4761. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4762. "@@@@@@@@@@@@@@@@@");
  4763. auto res = std::make_shared<Response>();
  4764. auto error = Error::Success;
  4765. auto ret = cli_.send(req, *res, error);
  4766. ASSERT_TRUE(ret);
  4767. EXPECT_EQ(StatusCode::OK_200, res->status);
  4768. }
  4769. TEST_F(ServerTest, HeaderCountAtLimit) {
  4770. // Test with headers just under the 100 limit
  4771. httplib::Headers headers;
  4772. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  4773. // This should keep us just under the 100 header limit
  4774. for (int i = 0; i < 95; i++) {
  4775. std::string name = "X-Test-Header-" + std::to_string(i);
  4776. std::string value = "value" + std::to_string(i);
  4777. headers.emplace(name, value);
  4778. }
  4779. // This should work fine as we're under the limit
  4780. auto res = cli_.Get("/hi", headers);
  4781. EXPECT_TRUE(res);
  4782. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  4783. }
  4784. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  4785. // Test with many headers to exceed the 100 limit
  4786. httplib::Headers headers;
  4787. // Add 150 headers to definitely exceed the 100 limit
  4788. for (int i = 0; i < 150; i++) {
  4789. std::string name = "X-Test-Header-" + std::to_string(i);
  4790. std::string value = "value" + std::to_string(i);
  4791. headers.emplace(name, value);
  4792. }
  4793. // This should fail due to exceeding header count limit
  4794. cli_.set_keep_alive(true);
  4795. auto res = cli_.Get("/hi", headers);
  4796. // The server should respond with 400 Bad Request
  4797. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4798. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4799. EXPECT_EQ("close", res->get_header_value("Connection"));
  4800. EXPECT_FALSE(cli_.is_socket_open());
  4801. }
  4802. TEST_F(ServerTest, PercentEncoding) {
  4803. auto res = cli_.Get("/e%6edwith%");
  4804. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4805. EXPECT_EQ(StatusCode::OK_200, res->status);
  4806. }
  4807. TEST_F(ServerTest, PercentEncodingUnicode) {
  4808. auto res = cli_.Get("/e%u006edwith%");
  4809. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4810. EXPECT_EQ(StatusCode::OK_200, res->status);
  4811. }
  4812. TEST_F(ServerTest, InvalidPercentEncoding) {
  4813. auto res = cli_.Get("/%endwith%");
  4814. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4815. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4816. }
  4817. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  4818. auto res = cli_.Get("/%uendwith%");
  4819. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4820. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4821. }
  4822. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  4823. auto res = cli_.Get("/hello?aaa=bbb%");
  4824. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4825. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4826. }
  4827. TEST_F(ServerTest, PlusSignEncoding) {
  4828. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  4829. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4830. EXPECT_EQ(StatusCode::OK_200, res->status);
  4831. EXPECT_EQ("a +b", res->body);
  4832. }
  4833. TEST_F(ServerTest, HeaderCountSecurityTest) {
  4834. // This test simulates a potential DoS attack using many headers
  4835. // to verify our security fix prevents memory exhaustion
  4836. httplib::Headers attack_headers;
  4837. // Attempt to add many headers like an attacker would (200 headers to far
  4838. // exceed limit)
  4839. for (int i = 0; i < 200; i++) {
  4840. std::string name = "X-Attack-Header-" + std::to_string(i);
  4841. std::string value = "attack_payload_" + std::to_string(i);
  4842. attack_headers.emplace(name, value);
  4843. }
  4844. // Try to POST with excessive headers
  4845. cli_.set_keep_alive(true);
  4846. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  4847. // Should either fail or return 400 Bad Request due to security limit
  4848. if (res) {
  4849. // If we get a response, it should be 400 Bad Request
  4850. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4851. EXPECT_EQ("close", res->get_header_value("Connection"));
  4852. }
  4853. EXPECT_FALSE(cli_.is_socket_open());
  4854. }
  4855. TEST_F(ServerTest, MultipartFormData) {
  4856. UploadFormDataItems items = {
  4857. {"text1", "text default", "", ""},
  4858. {"text2", "aωb", "", ""},
  4859. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4860. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  4861. {"file3", "", "", "application/octet-stream"},
  4862. {"file4", "", "", " application/json tmp-string "}};
  4863. auto res = cli_.Post("/multipart", items);
  4864. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4865. EXPECT_EQ(StatusCode::OK_200, res->status);
  4866. }
  4867. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  4868. UploadFormDataItems items = {
  4869. {"text", "default text", "", ""},
  4870. {"multi_text1", "aaaaa", "", ""},
  4871. {"multi_text1", "bbbbb", "", ""},
  4872. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4873. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  4874. "application/json"},
  4875. };
  4876. auto res = cli_.Post("/multipart/multi_file_values", items);
  4877. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4878. EXPECT_EQ(StatusCode::OK_200, res->status);
  4879. }
  4880. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  4881. auto res = cli_.Get("/hi");
  4882. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4883. EXPECT_EQ(StatusCode::OK_200, res->status);
  4884. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  4885. EXPECT_EQ("Hello World!", res->body);
  4886. }
  4887. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  4888. Request req;
  4889. req.method = "POST";
  4890. req.path = "/chunked";
  4891. std::string host_and_port;
  4892. host_and_port += HOST;
  4893. host_and_port += ":";
  4894. host_and_port += std::to_string(PORT);
  4895. req.headers.emplace("Host", host_and_port.c_str());
  4896. req.headers.emplace("Accept", "*/*");
  4897. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4898. req.headers.emplace("Content-Type", "text/plain");
  4899. req.headers.emplace("Content-Length", "0");
  4900. req.headers.emplace(
  4901. "Transfer-Encoding",
  4902. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  4903. // Client does not chunk, so make a chunked body manually.
  4904. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  4905. auto res = std::make_shared<Response>();
  4906. auto error = Error::Success;
  4907. auto ret = cli_.send(req, *res, error);
  4908. ASSERT_TRUE(ret);
  4909. EXPECT_EQ(StatusCode::OK_200, res->status);
  4910. }
  4911. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  4912. // rather than treat them as valid lengths.
  4913. template <typename ClientT>
  4914. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  4915. Request req;
  4916. req.method = "POST";
  4917. req.path = "/chunked";
  4918. std::string host_and_port;
  4919. host_and_port += HOST;
  4920. host_and_port += ":";
  4921. host_and_port += std::to_string(PORT);
  4922. req.headers.emplace("Host", host_and_port.c_str());
  4923. req.headers.emplace("Content-Length", "0");
  4924. req.headers.emplace("Transfer-Encoding", "chunked");
  4925. req.body = body;
  4926. auto res = std::make_shared<Response>();
  4927. auto error = Error::Success;
  4928. ASSERT_TRUE(cli.send(req, *res, error));
  4929. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4930. }
  4931. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  4932. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  4933. }
  4934. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  4935. expect_chunked_body_rejected(
  4936. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  4937. }
  4938. TEST_F(ServerTest, GetStreamed2) {
  4939. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  4940. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4941. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4942. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4943. EXPECT_EQ(true, res->has_header("Content-Range"));
  4944. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  4945. EXPECT_EQ(std::string("ab"), res->body);
  4946. }
  4947. TEST_F(ServerTest, GetStreamed) {
  4948. auto res = cli_.Get("/streamed");
  4949. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4950. EXPECT_EQ(StatusCode::OK_200, res->status);
  4951. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4952. EXPECT_EQ(std::string("aaabbb"), res->body);
  4953. }
  4954. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  4955. auto res = cli_.Get("/streamed-without-length",
  4956. Headers{make_range_header({{0, -1}})});
  4957. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4958. EXPECT_EQ(StatusCode::OK_200, res->status);
  4959. EXPECT_EQ(false, res->has_header("Content-Length"));
  4960. EXPECT_EQ(false, res->has_header("Content-Range"));
  4961. EXPECT_EQ(std::string("abcdefg"), res->body);
  4962. }
  4963. TEST_F(ServerTest, GetStreamedWithRange1) {
  4964. auto res =
  4965. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  4966. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4967. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4968. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4969. EXPECT_EQ(true, res->has_header("Content-Range"));
  4970. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4971. EXPECT_EQ(std::string("def"), res->body);
  4972. }
  4973. TEST_F(ServerTest, GetStreamedWithRange2) {
  4974. auto res =
  4975. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  4976. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4977. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4978. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4979. EXPECT_EQ(true, res->has_header("Content-Range"));
  4980. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4981. EXPECT_EQ(std::string("bcdefg"), res->body);
  4982. }
  4983. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  4984. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  4985. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4986. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4987. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4988. EXPECT_EQ(true, res->has_header("Content-Range"));
  4989. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  4990. EXPECT_EQ(std::string("efg"), res->body);
  4991. }
  4992. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  4993. auto res =
  4994. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-9999"}});
  4995. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4996. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4997. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4998. EXPECT_EQ(false, res->has_header("Content-Range"));
  4999. EXPECT_EQ(0U, res->body.size());
  5000. }
  5001. TEST_F(ServerTest, GetStreamedWithRangeError) {
  5002. auto res =
  5003. cli_.Get("/streamed-with-range",
  5004. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  5005. "92233720368547758079223372036854775807"}});
  5006. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5007. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5008. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5009. EXPECT_EQ(false, res->has_header("Content-Range"));
  5010. EXPECT_EQ(0U, res->body.size());
  5011. }
  5012. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  5013. auto res = cli_.Get(
  5014. "/with-range",
  5015. Headers{{"Range",
  5016. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  5017. {"Accept-Encoding", ""}});
  5018. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5019. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5020. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  5021. EXPECT_EQ(true, res->has_header("Content-Range"));
  5022. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  5023. EXPECT_EQ(std::string("abcdefg"), res->body);
  5024. }
  5025. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  5026. auto res = cli_.Get("/with-range", Headers{
  5027. {"Range", "bytes=0-"},
  5028. {"Accept-Encoding", ""},
  5029. });
  5030. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5031. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5032. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  5033. EXPECT_EQ(true, res->has_header("Content-Range"));
  5034. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  5035. EXPECT_EQ(std::string("abcdefg"), res->body);
  5036. }
  5037. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  5038. auto res = cli_.Get("/streamed-with-range",
  5039. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5040. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5041. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5042. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  5043. EXPECT_EQ(false, res->has_header("Content-Range"));
  5044. EXPECT_EQ(267U, res->body.size());
  5045. // Check that both range contents are present
  5046. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  5047. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  5048. // Check that Content-Range headers are present for both ranges
  5049. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  5050. std::string::npos);
  5051. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  5052. std::string::npos);
  5053. }
  5054. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  5055. Ranges ranges;
  5056. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  5057. ranges.emplace_back(0, -1);
  5058. }
  5059. auto res = cli_.Get("/streamed-with-range?error",
  5060. Headers{{make_range_header(ranges)}});
  5061. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5062. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5063. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5064. EXPECT_EQ(false, res->has_header("Content-Range"));
  5065. EXPECT_EQ(0U, res->body.size());
  5066. }
  5067. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  5068. auto res = cli_.Get("/streamed-with-range",
  5069. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  5070. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5071. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5072. EXPECT_EQ(5U, res->body.size());
  5073. // Check that overlapping ranges are coalesced into a single range
  5074. EXPECT_EQ("bcdef", res->body);
  5075. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  5076. // Should be single range, not multipart
  5077. EXPECT_TRUE(res->has_header("Content-Range"));
  5078. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5079. }
  5080. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  5081. auto res = cli_.Get("/streamed-with-range",
  5082. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  5083. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5084. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5085. EXPECT_EQ(268U, res->body.size());
  5086. // Check that both range contents are present
  5087. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  5088. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  5089. // Check that Content-Range headers are present for both ranges
  5090. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  5091. std::string::npos);
  5092. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  5093. std::string::npos);
  5094. }
  5095. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  5096. auto res = cli_.Get("/streamed-with-range",
  5097. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  5098. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5099. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5100. EXPECT_EQ(269U, res->body.size());
  5101. // Check that both duplicate range contents are present
  5102. size_t first_abc = res->body.find("abc\r\n");
  5103. EXPECT_TRUE(first_abc != std::string::npos);
  5104. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  5105. EXPECT_TRUE(second_abc != std::string::npos);
  5106. // Check that Content-Range headers are present for both ranges
  5107. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  5108. EXPECT_TRUE(first_range != std::string::npos);
  5109. size_t second_range =
  5110. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  5111. EXPECT_TRUE(second_range != std::string::npos);
  5112. }
  5113. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  5114. auto res =
  5115. cli_.Get("/streamed-with-range?error",
  5116. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  5117. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5118. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5119. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5120. EXPECT_EQ(false, res->has_header("Content-Range"));
  5121. EXPECT_EQ(0U, res->body.size());
  5122. }
  5123. TEST_F(ServerTest, GetStreamedEndless) {
  5124. uint64_t offset = 0;
  5125. auto res = cli_.Get("/streamed-cancel",
  5126. [&](const char * /*data*/, uint64_t data_length) {
  5127. if (offset < 100) {
  5128. offset += data_length;
  5129. return true;
  5130. }
  5131. return false;
  5132. });
  5133. ASSERT_TRUE(!res);
  5134. EXPECT_EQ(Error::Canceled, res.error());
  5135. }
  5136. TEST_F(ServerTest, ClientStop) {
  5137. std::atomic_size_t count{4};
  5138. std::vector<std::thread> threads;
  5139. for (auto i = count.load(); i != 0; --i) {
  5140. threads.emplace_back([&]() {
  5141. auto res = cli_.Get("/streamed-cancel",
  5142. [&](const char *, uint64_t) { return true; });
  5143. --count;
  5144. ASSERT_TRUE(!res);
  5145. EXPECT_TRUE(res.error() == Error::Canceled ||
  5146. res.error() == Error::Read || res.error() == Error::Write);
  5147. });
  5148. }
  5149. std::this_thread::sleep_for(std::chrono::seconds(2));
  5150. while (count != 0) {
  5151. cli_.stop();
  5152. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  5153. }
  5154. for (auto &t : threads) {
  5155. t.join();
  5156. }
  5157. }
  5158. TEST_F(ServerTest, GetWithRange1) {
  5159. auto res = cli_.Get("/with-range", Headers{
  5160. make_range_header({{3, 5}}),
  5161. {"Accept-Encoding", ""},
  5162. });
  5163. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5164. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5165. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5166. EXPECT_EQ(true, res->has_header("Content-Range"));
  5167. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  5168. EXPECT_EQ(std::string("def"), res->body);
  5169. }
  5170. TEST_F(ServerTest, GetWithRange2) {
  5171. auto res = cli_.Get("/with-range", Headers{
  5172. make_range_header({{1, -1}}),
  5173. {"Accept-Encoding", ""},
  5174. });
  5175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5176. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5177. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5178. EXPECT_EQ(true, res->has_header("Content-Range"));
  5179. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  5180. EXPECT_EQ(std::string("bcdefg"), res->body);
  5181. }
  5182. TEST_F(ServerTest, GetWithRange3) {
  5183. auto res = cli_.Get("/with-range", Headers{
  5184. make_range_header({{0, 0}}),
  5185. {"Accept-Encoding", ""},
  5186. });
  5187. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5188. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5189. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  5190. EXPECT_EQ(true, res->has_header("Content-Range"));
  5191. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  5192. EXPECT_EQ(std::string("a"), res->body);
  5193. }
  5194. TEST_F(ServerTest, GetWithRange4) {
  5195. auto res = cli_.Get("/with-range", Headers{
  5196. make_range_header({{-1, 2}}),
  5197. {"Accept-Encoding", ""},
  5198. });
  5199. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5200. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5201. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5202. EXPECT_EQ(true, res->has_header("Content-Range"));
  5203. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  5204. EXPECT_EQ(std::string("fg"), res->body);
  5205. }
  5206. TEST_F(ServerTest, GetWithRange5) {
  5207. auto res = cli_.Get("/with-range", Headers{
  5208. make_range_header({{0, 5}}),
  5209. {"Accept-Encoding", ""},
  5210. });
  5211. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5212. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5213. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5214. EXPECT_EQ(true, res->has_header("Content-Range"));
  5215. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  5216. EXPECT_EQ(std::string("abcdef"), res->body);
  5217. }
  5218. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  5219. auto res =
  5220. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  5221. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5222. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5223. }
  5224. TEST_F(ServerTest, GetWithRangeMultipart) {
  5225. auto res =
  5226. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5227. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5228. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5229. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  5230. EXPECT_EQ(false, res->has_header("Content-Range"));
  5231. EXPECT_EQ(267U, res->body.size());
  5232. }
  5233. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  5234. auto res = cli_.Get("/with-range",
  5235. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  5236. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5237. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5238. }
  5239. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  5240. auto res = cli_.Get("/with-range-customized-response",
  5241. Headers{{make_range_header({{1, 2}})}});
  5242. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5243. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5244. EXPECT_EQ(true, res->has_header("Content-Length"));
  5245. EXPECT_EQ(false, res->has_header("Content-Range"));
  5246. EXPECT_EQ(JSON_DATA, res->body);
  5247. }
  5248. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  5249. auto res = cli_.Get("/with-range-customized-response",
  5250. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5251. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5252. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5253. EXPECT_EQ(true, res->has_header("Content-Length"));
  5254. EXPECT_EQ(false, res->has_header("Content-Range"));
  5255. EXPECT_EQ(JSON_DATA, res->body);
  5256. }
  5257. TEST_F(ServerTest, Issue1772) {
  5258. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  5259. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5260. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  5261. }
  5262. TEST_F(ServerTest, Issue609) {
  5263. auto res = cli_.Delete("/issue609");
  5264. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5265. EXPECT_EQ(StatusCode::OK_200, res->status);
  5266. EXPECT_EQ(std::string("ok"), res->body);
  5267. }
  5268. TEST_F(ServerTest, GetStreamedChunked) {
  5269. auto res = cli_.Get("/streamed-chunked");
  5270. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5271. EXPECT_EQ(StatusCode::OK_200, res->status);
  5272. EXPECT_EQ(std::string("123456789"), res->body);
  5273. }
  5274. TEST_F(ServerTest, GetStreamedChunked2) {
  5275. auto res = cli_.Get("/streamed-chunked2");
  5276. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5277. EXPECT_EQ(StatusCode::OK_200, res->status);
  5278. EXPECT_EQ(std::string("123456789"), res->body);
  5279. }
  5280. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  5281. auto res = cli_.Get("/streamed-chunked-with-trailer");
  5282. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5283. EXPECT_EQ(StatusCode::OK_200, res->status);
  5284. EXPECT_EQ(std::string("123456789"), res->body);
  5285. EXPECT_TRUE(res->has_header("Trailer"));
  5286. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  5287. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  5288. // Trailers are now stored separately from headers (security fix)
  5289. EXPECT_EQ(2U, res->trailers.size());
  5290. EXPECT_TRUE(res->has_trailer("Dummy1"));
  5291. EXPECT_TRUE(res->has_trailer("Dummy2"));
  5292. EXPECT_FALSE(res->has_trailer("Dummy3"));
  5293. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  5294. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  5295. // Verify trailers are NOT in headers (security verification)
  5296. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  5297. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  5298. }
  5299. TEST_F(ServerTest, LargeChunkedPost) {
  5300. Request req;
  5301. req.method = "POST";
  5302. req.path = "/large-chunked";
  5303. std::string host_and_port;
  5304. host_and_port += HOST;
  5305. host_and_port += ":";
  5306. host_and_port += std::to_string(PORT);
  5307. req.headers.emplace("Host", host_and_port.c_str());
  5308. req.headers.emplace("Accept", "*/*");
  5309. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5310. req.headers.emplace("Content-Type", "text/plain");
  5311. req.headers.emplace("Content-Length", "0");
  5312. req.headers.emplace("Transfer-Encoding", "chunked");
  5313. std::string long_string(30 * 1024u, 'a');
  5314. std::string chunk = "7800\r\n" + long_string + "\r\n";
  5315. // Attempt to make a large enough post to exceed OS buffers, to test that
  5316. // the server handles short reads if the full chunk data isn't available.
  5317. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  5318. auto res = std::make_shared<Response>();
  5319. auto error = Error::Success;
  5320. auto ret = cli_.send(req, *res, error);
  5321. ASSERT_TRUE(ret);
  5322. EXPECT_EQ(StatusCode::OK_200, res->status);
  5323. }
  5324. TEST_F(ServerTest, GetMethodRemoteAddr) {
  5325. auto res = cli_.Get("/remote_addr");
  5326. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5327. EXPECT_EQ(StatusCode::OK_200, res->status);
  5328. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5329. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  5330. }
  5331. TEST_F(ServerTest, GetMethodLocalAddr) {
  5332. auto res = cli_.Get("/local_addr");
  5333. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5334. EXPECT_EQ(StatusCode::OK_200, res->status);
  5335. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5336. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  5337. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  5338. }
  5339. TEST_F(ServerTest, HTTPResponseSplitting) {
  5340. auto res = cli_.Get("/http_response_splitting");
  5341. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5342. EXPECT_EQ(StatusCode::OK_200, res->status);
  5343. }
  5344. TEST_F(ServerTest, SlowRequest) {
  5345. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5346. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5347. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5348. }
  5349. #if 0
  5350. TEST_F(ServerTest, SlowPost) {
  5351. char buffer[64 * 1024];
  5352. memset(buffer, 0x42, sizeof(buffer));
  5353. auto res = cli_.Post(
  5354. "/slowpost", 64 * 1024 * 1024,
  5355. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5356. auto ret = sink.write(buffer, sizeof(buffer));
  5357. EXPECT_TRUE(ret);
  5358. return true;
  5359. },
  5360. "text/plain");
  5361. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5362. EXPECT_EQ(StatusCode::OK_200, res->status);
  5363. }
  5364. TEST_F(ServerTest, SlowPostFail) {
  5365. char buffer[64 * 1024];
  5366. memset(buffer, 0x42, sizeof(buffer));
  5367. cli_.set_write_timeout(std::chrono::seconds(0));
  5368. auto res = cli_.Post(
  5369. "/slowpost", 64 * 1024 * 1024,
  5370. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5371. sink.write(buffer, sizeof(buffer));
  5372. return true;
  5373. },
  5374. "text/plain");
  5375. ASSERT_TRUE(!res);
  5376. EXPECT_EQ(Error::Write, res.error());
  5377. }
  5378. #endif
  5379. TEST_F(ServerTest, Put) {
  5380. auto res = cli_.Put("/put", "PUT", "text/plain");
  5381. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5382. EXPECT_EQ(StatusCode::OK_200, res->status);
  5383. EXPECT_EQ("PUT", res->body);
  5384. }
  5385. TEST_F(ServerTest, PutWithContentProvider) {
  5386. auto res = cli_.Put(
  5387. "/put", 3,
  5388. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5389. sink.os << "PUT";
  5390. return true;
  5391. },
  5392. "text/plain");
  5393. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5394. EXPECT_EQ(StatusCode::OK_200, res->status);
  5395. EXPECT_EQ("PUT", res->body);
  5396. }
  5397. TEST_F(ServerTest, PostWithContentProviderAbort) {
  5398. auto res = cli_.Post(
  5399. "/post", 42,
  5400. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  5401. return false;
  5402. },
  5403. "text/plain");
  5404. ASSERT_TRUE(!res);
  5405. EXPECT_EQ(Error::Canceled, res.error());
  5406. }
  5407. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  5408. auto res = cli_.Put(
  5409. "/put",
  5410. [](size_t /*offset*/, DataSink &sink) {
  5411. sink.os << "PUT";
  5412. sink.done();
  5413. return true;
  5414. },
  5415. "text/plain");
  5416. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5417. EXPECT_EQ(StatusCode::OK_200, res->status);
  5418. EXPECT_EQ("PUT", res->body);
  5419. }
  5420. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  5421. auto res = cli_.Post(
  5422. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  5423. "text/plain");
  5424. ASSERT_TRUE(!res);
  5425. EXPECT_EQ(Error::Canceled, res.error());
  5426. }
  5427. TEST_F(ServerTest, PostLoopBack) {
  5428. std::string body;
  5429. auto res = cli_.Post(
  5430. "/post-loopback", 9,
  5431. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5432. EXPECT_EQ(9u, length);
  5433. sink.write("123", 3);
  5434. sink.write("456", 3);
  5435. sink.write("789", 3);
  5436. return true;
  5437. },
  5438. "text/plain",
  5439. [&body](const char *data, size_t data_length) {
  5440. body.append(data, data_length);
  5441. return true;
  5442. });
  5443. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5444. EXPECT_EQ(StatusCode::OK_200, res->status);
  5445. EXPECT_EQ("123456789", body);
  5446. }
  5447. TEST_F(ServerTest, PutLoopBack) {
  5448. std::string body;
  5449. auto res = cli_.Put(
  5450. "/put-loopback", 9,
  5451. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5452. EXPECT_EQ(9u, length);
  5453. sink.write("123", 3);
  5454. sink.write("456", 3);
  5455. sink.write("789", 3);
  5456. return true;
  5457. },
  5458. "text/plain",
  5459. [&body](const char *data, size_t data_length) {
  5460. body.append(data, data_length);
  5461. return true;
  5462. });
  5463. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5464. EXPECT_EQ(StatusCode::OK_200, res->status);
  5465. EXPECT_EQ("123456789", body);
  5466. }
  5467. TEST_F(ServerTest, PatchLoopBack) {
  5468. std::string body;
  5469. auto res = cli_.Patch(
  5470. "/patch-loopback", 9,
  5471. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5472. EXPECT_EQ(9u, length);
  5473. sink.write("123", 3);
  5474. sink.write("456", 3);
  5475. sink.write("789", 3);
  5476. return true;
  5477. },
  5478. "text/plain",
  5479. [&body](const char *data, size_t data_length) {
  5480. body.append(data, data_length);
  5481. return true;
  5482. });
  5483. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5484. EXPECT_EQ(StatusCode::OK_200, res->status);
  5485. EXPECT_EQ("123456789", body);
  5486. }
  5487. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  5488. std::string body;
  5489. auto res = cli_.Post(
  5490. "/post-loopback",
  5491. [](size_t /*offset*/, DataSink &sink) {
  5492. sink.write("123", 3);
  5493. sink.write("456", 3);
  5494. sink.write("789", 3);
  5495. sink.done();
  5496. return true;
  5497. },
  5498. "text/plain",
  5499. [&body](const char *data, size_t data_length) {
  5500. body.append(data, data_length);
  5501. return true;
  5502. });
  5503. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5504. EXPECT_EQ(StatusCode::OK_200, res->status);
  5505. EXPECT_EQ("123456789", body);
  5506. }
  5507. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5508. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  5509. cli_.set_compress(true);
  5510. auto res = cli_.Put(
  5511. "/put", 3,
  5512. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5513. sink.os << "PUT";
  5514. return true;
  5515. },
  5516. "text/plain");
  5517. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5518. EXPECT_EQ(StatusCode::OK_200, res->status);
  5519. EXPECT_EQ("PUT", res->body);
  5520. }
  5521. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  5522. cli_.set_compress(true);
  5523. auto res = cli_.Post(
  5524. "/post", 42,
  5525. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  5526. return false;
  5527. },
  5528. "text/plain");
  5529. ASSERT_TRUE(!res);
  5530. EXPECT_EQ(Error::Canceled, res.error());
  5531. }
  5532. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  5533. cli_.set_compress(true);
  5534. auto res = cli_.Put(
  5535. "/put",
  5536. [](size_t /*offset*/, DataSink &sink) {
  5537. sink.os << "PUT";
  5538. sink.done();
  5539. return true;
  5540. },
  5541. "text/plain");
  5542. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5543. EXPECT_EQ(StatusCode::OK_200, res->status);
  5544. EXPECT_EQ("PUT", res->body);
  5545. }
  5546. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  5547. cli_.set_compress(true);
  5548. auto res = cli_.Post(
  5549. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  5550. "text/plain");
  5551. ASSERT_TRUE(!res);
  5552. EXPECT_EQ(Error::Canceled, res.error());
  5553. }
  5554. TEST_F(ServerTest, PutLargeFileWithGzip) {
  5555. cli_.set_compress(true);
  5556. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  5557. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5558. EXPECT_EQ(StatusCode::OK_200, res->status);
  5559. EXPECT_EQ(LARGE_DATA, res->body);
  5560. }
  5561. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  5562. #ifdef CPPHTTPLIB_SSL_ENABLED
  5563. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  5564. Client cli(s.c_str());
  5565. cli.enable_server_certificate_verification(false);
  5566. #else
  5567. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  5568. Client cli(s.c_str());
  5569. #endif
  5570. cli.set_compress(true);
  5571. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  5572. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5573. EXPECT_EQ(StatusCode::OK_200, res->status);
  5574. EXPECT_EQ(LARGE_DATA, res->body);
  5575. // The compressed size should be less than a 10th of the original. May vary
  5576. // depending on the zlib library.
  5577. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  5578. static_cast<uint64_t>(10 * 1024 * 1024));
  5579. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5580. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  5581. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  5582. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  5583. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5584. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  5585. #endif
  5586. }
  5587. TEST_F(ServerTest, PutContentWithDeflate) {
  5588. cli_.set_compress(false);
  5589. Headers headers;
  5590. headers.emplace("Content-Encoding", "deflate");
  5591. // PUT in deflate format:
  5592. auto res = cli_.Put("/put", headers,
  5593. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  5594. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5595. EXPECT_EQ(StatusCode::OK_200, res->status);
  5596. EXPECT_EQ("PUT", res->body);
  5597. }
  5598. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  5599. Headers headers;
  5600. headers.emplace("Accept-Encoding", "gzip, deflate");
  5601. auto res = cli_.Get("/streamed-chunked", headers);
  5602. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5603. EXPECT_EQ(StatusCode::OK_200, res->status);
  5604. EXPECT_EQ(std::string("123456789"), res->body);
  5605. }
  5606. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  5607. Headers headers;
  5608. headers.emplace("Accept-Encoding", "gzip, deflate");
  5609. auto res = cli_.Get("/streamed-chunked2", headers);
  5610. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5611. EXPECT_EQ(StatusCode::OK_200, res->status);
  5612. EXPECT_EQ(std::string("123456789"), res->body);
  5613. }
  5614. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  5615. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  5616. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5617. EXPECT_EQ(StatusCode::OK_200, res->status);
  5618. }
  5619. TEST(GzipDecompressor, ChunkedDecompression) {
  5620. std::string data;
  5621. for (size_t i = 0; i < 32 * 1024; ++i) {
  5622. data.push_back(static_cast<char>('a' + i % 26));
  5623. }
  5624. std::string compressed_data;
  5625. {
  5626. httplib::detail::gzip_compressor compressor;
  5627. bool result = compressor.compress(
  5628. data.data(), data.size(),
  5629. /*last=*/true,
  5630. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5631. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5632. compressed_data_size);
  5633. return true;
  5634. });
  5635. ASSERT_TRUE(result);
  5636. }
  5637. std::string decompressed_data;
  5638. {
  5639. httplib::detail::gzip_decompressor decompressor;
  5640. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5641. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5642. size_t chunk_size = 130;
  5643. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5644. chunk_begin += chunk_size) {
  5645. size_t current_chunk_size =
  5646. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5647. bool result = decompressor.decompress(
  5648. compressed_data.data() + chunk_begin, current_chunk_size,
  5649. [&](const char *decompressed_data_chunk,
  5650. size_t decompressed_data_chunk_size) {
  5651. decompressed_data.insert(decompressed_data.size(),
  5652. decompressed_data_chunk,
  5653. decompressed_data_chunk_size);
  5654. return true;
  5655. });
  5656. ASSERT_TRUE(result);
  5657. }
  5658. }
  5659. ASSERT_EQ(data, decompressed_data);
  5660. }
  5661. TEST(GzipDecompressor, DeflateDecompression) {
  5662. std::string original_text = "Raw deflate without gzip";
  5663. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  5664. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  5665. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  5666. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  5667. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5668. std::string decompressed_data;
  5669. {
  5670. httplib::detail::gzip_decompressor decompressor;
  5671. bool result = decompressor.decompress(
  5672. compressed_data.data(), compressed_data.size(),
  5673. [&](const char *decompressed_data_chunk,
  5674. size_t decompressed_data_chunk_size) {
  5675. decompressed_data.insert(decompressed_data.size(),
  5676. decompressed_data_chunk,
  5677. decompressed_data_chunk_size);
  5678. return true;
  5679. });
  5680. ASSERT_TRUE(result);
  5681. }
  5682. ASSERT_EQ(original_text, decompressed_data);
  5683. }
  5684. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  5685. std::string original_text = "Raw deflate without gzip";
  5686. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  5687. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  5688. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  5689. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  5690. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  5691. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5692. std::string decompressed_data;
  5693. {
  5694. httplib::detail::gzip_decompressor decompressor;
  5695. bool result = decompressor.decompress(
  5696. compressed_data.data(), compressed_data.size(),
  5697. [&](const char *decompressed_data_chunk,
  5698. size_t decompressed_data_chunk_size) {
  5699. decompressed_data.insert(decompressed_data.size(),
  5700. decompressed_data_chunk,
  5701. decompressed_data_chunk_size);
  5702. return true;
  5703. });
  5704. ASSERT_TRUE(result);
  5705. }
  5706. ASSERT_EQ(original_text, decompressed_data);
  5707. }
  5708. #endif
  5709. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5710. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  5711. Headers headers;
  5712. headers.emplace("Accept-Encoding", "br");
  5713. auto res = cli_.Get("/streamed-chunked", headers);
  5714. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5715. EXPECT_EQ(StatusCode::OK_200, res->status);
  5716. EXPECT_EQ(std::string("123456789"), res->body);
  5717. }
  5718. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  5719. Headers headers;
  5720. headers.emplace("Accept-Encoding", "br");
  5721. auto res = cli_.Get("/streamed-chunked2", headers);
  5722. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5723. EXPECT_EQ(StatusCode::OK_200, res->status);
  5724. EXPECT_EQ(std::string("123456789"), res->body);
  5725. }
  5726. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  5727. cli_.set_compress(true);
  5728. auto res = cli_.Put(
  5729. "/put", 3,
  5730. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5731. sink.os << "PUT";
  5732. return true;
  5733. },
  5734. "text/plain");
  5735. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5736. EXPECT_EQ(StatusCode::OK_200, res->status);
  5737. EXPECT_EQ("PUT", res->body);
  5738. }
  5739. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  5740. cli_.set_compress(true);
  5741. auto res = cli_.Put(
  5742. "/put",
  5743. [](size_t /*offset*/, DataSink &sink) {
  5744. sink.os << "PUT";
  5745. sink.done();
  5746. return true;
  5747. },
  5748. "text/plain");
  5749. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5750. EXPECT_EQ(StatusCode::OK_200, res->status);
  5751. EXPECT_EQ("PUT", res->body);
  5752. }
  5753. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  5754. cli_.set_compress(true);
  5755. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  5756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5757. EXPECT_EQ(StatusCode::OK_200, res->status);
  5758. EXPECT_EQ(LARGE_DATA, res->body);
  5759. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  5760. }
  5761. #endif
  5762. TEST_F(ServerTest, Patch) {
  5763. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  5764. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5765. EXPECT_EQ(StatusCode::OK_200, res->status);
  5766. EXPECT_EQ("PATCH", res->body);
  5767. }
  5768. TEST_F(ServerTest, Delete) {
  5769. auto res = cli_.Delete("/delete");
  5770. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5771. EXPECT_EQ(StatusCode::OK_200, res->status);
  5772. EXPECT_EQ("DELETE", res->body);
  5773. }
  5774. TEST_F(ServerTest, DeleteContentReceiver) {
  5775. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  5776. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5777. EXPECT_EQ(StatusCode::OK_200, res->status);
  5778. EXPECT_EQ("content", res->body);
  5779. }
  5780. TEST_F(ServerTest, Options) {
  5781. auto res = cli_.Options("*");
  5782. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5783. EXPECT_EQ(StatusCode::OK_200, res->status);
  5784. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  5785. EXPECT_TRUE(res->body.empty());
  5786. }
  5787. TEST_F(ServerTest, URL) {
  5788. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  5789. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5790. EXPECT_EQ(StatusCode::OK_200, res->status);
  5791. }
  5792. TEST_F(ServerTest, ArrayParam) {
  5793. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  5794. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5795. EXPECT_EQ(StatusCode::OK_200, res->status);
  5796. }
  5797. TEST_F(ServerTest, ArrayParamValues) {
  5798. auto res =
  5799. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  5800. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5801. EXPECT_EQ(StatusCode::OK_200, res->status);
  5802. }
  5803. TEST_F(ServerTest, NoMultipleHeaders) {
  5804. Headers headers = {{"Content-Length", "5"}};
  5805. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  5806. "text/plain");
  5807. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5808. EXPECT_EQ(StatusCode::OK_200, res->status);
  5809. }
  5810. TEST_F(ServerTest, PostContentReceiver) {
  5811. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5812. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5813. ASSERT_EQ(StatusCode::OK_200, res->status);
  5814. ASSERT_EQ("content", res->body);
  5815. }
  5816. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  5817. UploadFormDataItems items = {
  5818. {"text1", "text default", "", ""},
  5819. {"text2", "aωb", "", ""},
  5820. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5821. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5822. {"file3", "", "", "application/octet-stream"},
  5823. };
  5824. auto res = cli_.Post("/content_receiver", items);
  5825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5826. EXPECT_EQ(StatusCode::OK_200, res->status);
  5827. }
  5828. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  5829. UploadFormDataItems items = {
  5830. {"text1", "text default", "", ""},
  5831. {"text2", "aωb", "", ""},
  5832. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5833. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5834. {"file3", "", "", "application/octet-stream"},
  5835. };
  5836. auto boundary = std::string("+++++");
  5837. std::string body;
  5838. for (const auto &item : items) {
  5839. body += "--" + boundary + "\r\n";
  5840. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  5841. if (!item.filename.empty()) {
  5842. body += "; filename=\"" + item.filename + "\"";
  5843. }
  5844. body += "\r\n";
  5845. if (!item.content_type.empty()) {
  5846. body += "Content-Type: " + item.content_type + "\r\n";
  5847. }
  5848. body += "\r\n";
  5849. body += item.content + "\r\n";
  5850. }
  5851. body += "--" + boundary + "--\r\n";
  5852. std::string content_type = "multipart/form-data; boundary=" + boundary;
  5853. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  5854. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5855. EXPECT_EQ(StatusCode::OK_200, res->status);
  5856. }
  5857. TEST(MultipartFormDataTest, FieldEscaping) {
  5858. Server svr;
  5859. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  5860. const ContentReader &content_reader) {
  5861. ASSERT_TRUE(req.is_multipart_form_data());
  5862. std::vector<FormData> received;
  5863. content_reader(
  5864. [&](const FormData &file) {
  5865. received.push_back(file);
  5866. return true;
  5867. },
  5868. [&](const char *data, size_t data_length) {
  5869. received.back().content.append(data, data_length);
  5870. return true;
  5871. });
  5872. // '"', CR and LF in names and filenames are escaped following the
  5873. // WHATWG HTML standard, so each part still parses as a single part
  5874. // with no injected headers. Content types get CR/LF escaped too,
  5875. // while '"' (legal there, e.g. quoted charset) is preserved.
  5876. ASSERT_EQ(4U, received.size());
  5877. EXPECT_EQ("na%22me", received[0].name);
  5878. EXPECT_EQ("quoted name", received[0].content);
  5879. EXPECT_EQ("file", received[1].name);
  5880. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  5881. received[1].filename);
  5882. EXPECT_EQ("application/octet-stream", received[1].content_type);
  5883. EXPECT_EQ("injected", received[1].content);
  5884. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  5885. EXPECT_EQ("my%22file.txt", received[2].filename);
  5886. EXPECT_EQ("cr lf name", received[2].content);
  5887. EXPECT_EQ("typed", received[3].name);
  5888. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  5889. received[3].content_type);
  5890. EXPECT_EQ("typed content", received[3].content);
  5891. });
  5892. auto port = svr.bind_to_any_port("localhost");
  5893. auto t = std::thread([&]() { svr.listen_after_bind(); });
  5894. auto se = detail::scope_exit([&] {
  5895. svr.stop();
  5896. t.join();
  5897. ASSERT_FALSE(svr.is_running());
  5898. });
  5899. svr.wait_until_ready();
  5900. Client cli("localhost", port);
  5901. UploadFormDataItems items = {
  5902. {"na\"me", "quoted name", "", ""},
  5903. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  5904. "application/octet-stream"},
  5905. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  5906. {"typed", "typed content", "",
  5907. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  5908. };
  5909. auto res = cli.Post("/post", items);
  5910. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5911. EXPECT_EQ(StatusCode::OK_200, res->status);
  5912. }
  5913. TEST(MultipartFormDataTest, PublicWriterAPI) {
  5914. const UploadFormDataItems items = {
  5915. {"name1", "Content 1", "", ""},
  5916. {"name2", "Content 2", "file2.txt", "text/plain"},
  5917. };
  5918. Server svr;
  5919. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  5920. const ContentReader &content_reader) {
  5921. ASSERT_TRUE(req.is_multipart_form_data());
  5922. std::vector<FormData> received;
  5923. content_reader(
  5924. [&](const FormData &file) {
  5925. received.push_back(file);
  5926. return true;
  5927. },
  5928. [&](const char *data, size_t data_length) {
  5929. received.back().content.append(data, data_length);
  5930. return true;
  5931. });
  5932. ASSERT_EQ(2U, received.size());
  5933. EXPECT_EQ("name1", received[0].name);
  5934. EXPECT_EQ("Content 1", received[0].content);
  5935. EXPECT_EQ("name2", received[1].name);
  5936. EXPECT_EQ("Content 2", received[1].content);
  5937. EXPECT_EQ("file2.txt", received[1].filename);
  5938. EXPECT_EQ("text/plain", received[1].content_type);
  5939. });
  5940. auto port = svr.bind_to_any_port("localhost");
  5941. auto t = std::thread([&]() { svr.listen_after_bind(); });
  5942. auto se = detail::scope_exit([&] {
  5943. svr.stop();
  5944. t.join();
  5945. ASSERT_FALSE(svr.is_running());
  5946. });
  5947. svr.wait_until_ready();
  5948. Client cli("localhost", port);
  5949. // Whole-body serialization with a generated boundary
  5950. {
  5951. MultipartFormDataWriter writer;
  5952. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  5953. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  5954. writer.content_type());
  5955. auto body = writer.serialize(items);
  5956. EXPECT_EQ(body.size(), writer.content_length(items));
  5957. auto res = cli.Post("/post", body, writer.content_type());
  5958. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5959. EXPECT_EQ(StatusCode::OK_200, res->status);
  5960. }
  5961. // Per-part framing with a custom boundary via a content provider
  5962. {
  5963. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  5964. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  5965. MultipartFormDataWriter writer("custom-boundary_123");
  5966. EXPECT_EQ("custom-boundary_123", writer.boundary());
  5967. std::string body;
  5968. for (const auto &item : items) {
  5969. body += writer.item_begin(item);
  5970. body += item.content;
  5971. body += MultipartFormDataWriter::item_end();
  5972. }
  5973. body += writer.finish();
  5974. EXPECT_EQ(body.size(), writer.content_length(items));
  5975. auto res = cli.Post(
  5976. "/post", body.size(),
  5977. [&](size_t offset, size_t length, DataSink &sink) {
  5978. sink.write(body.data() + offset, length);
  5979. return true;
  5980. },
  5981. writer.content_type());
  5982. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5983. EXPECT_EQ(StatusCode::OK_200, res->status);
  5984. }
  5985. }
  5986. TEST_F(ServerTest, PostContentReceiverGzip) {
  5987. cli_.set_compress(true);
  5988. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5989. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5990. ASSERT_EQ(StatusCode::OK_200, res->status);
  5991. ASSERT_EQ("content", res->body);
  5992. }
  5993. TEST_F(ServerTest, PutContentReceiver) {
  5994. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  5995. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5996. ASSERT_EQ(StatusCode::OK_200, res->status);
  5997. ASSERT_EQ("content", res->body);
  5998. }
  5999. TEST_F(ServerTest, PatchContentReceiver) {
  6000. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  6001. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6002. ASSERT_EQ(StatusCode::OK_200, res->status);
  6003. ASSERT_EQ("content", res->body);
  6004. }
  6005. template <typename ClientType>
  6006. void TestWithHeadersAndContentReceiver(
  6007. ClientType &cli,
  6008. std::function<Result(ClientType &, const std::string &, const Headers &,
  6009. const std::string &, const std::string &,
  6010. ContentReceiver, DownloadProgress)>
  6011. request_func) {
  6012. Headers headers;
  6013. headers.emplace("X-Custom-Header", "test-value");
  6014. std::string received_body;
  6015. auto res = request_func(
  6016. cli, "/content_receiver", headers, "content", "application/json",
  6017. [&](const char *data, size_t data_length) {
  6018. received_body.append(data, data_length);
  6019. return true;
  6020. },
  6021. nullptr);
  6022. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6023. EXPECT_EQ(StatusCode::OK_200, res->status);
  6024. EXPECT_EQ("content", received_body);
  6025. }
  6026. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  6027. #ifdef CPPHTTPLIB_SSL_ENABLED
  6028. using ClientT = SSLClient;
  6029. #else
  6030. using ClientT = Client;
  6031. #endif
  6032. TestWithHeadersAndContentReceiver<ClientT>(
  6033. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6034. const std::string &body, const std::string &content_type,
  6035. ContentReceiver receiver, DownloadProgress progress) {
  6036. return cli.Post(path, headers, body, content_type, receiver, progress);
  6037. });
  6038. }
  6039. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  6040. #ifdef CPPHTTPLIB_SSL_ENABLED
  6041. using ClientT = SSLClient;
  6042. #else
  6043. using ClientT = Client;
  6044. #endif
  6045. TestWithHeadersAndContentReceiver<ClientT>(
  6046. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6047. const std::string &body, const std::string &content_type,
  6048. ContentReceiver receiver, DownloadProgress progress) {
  6049. return cli.Put(path, headers, body, content_type, receiver, progress);
  6050. });
  6051. }
  6052. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  6053. #ifdef CPPHTTPLIB_SSL_ENABLED
  6054. using ClientT = SSLClient;
  6055. #else
  6056. using ClientT = Client;
  6057. #endif
  6058. TestWithHeadersAndContentReceiver<ClientT>(
  6059. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6060. const std::string &body, const std::string &content_type,
  6061. ContentReceiver receiver, DownloadProgress progress) {
  6062. return cli.Patch(path, headers, body, content_type, receiver, progress);
  6063. });
  6064. }
  6065. template <typename ClientType>
  6066. void TestWithHeadersAndContentReceiverWithProgress(
  6067. ClientType &cli,
  6068. std::function<Result(ClientType &, const std::string &, const Headers &,
  6069. const std::string &, const std::string &,
  6070. ContentReceiver, DownloadProgress)>
  6071. request_func) {
  6072. Headers headers;
  6073. headers.emplace("X-Test-Header", "progress-test");
  6074. std::string received_body;
  6075. auto progress_called = false;
  6076. auto res = request_func(
  6077. cli, "/content_receiver", headers, "content", "text/plain",
  6078. [&](const char *data, size_t data_length) {
  6079. received_body.append(data, data_length);
  6080. return true;
  6081. },
  6082. [&](uint64_t /*current*/, uint64_t /*total*/) {
  6083. progress_called = true;
  6084. return true;
  6085. });
  6086. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6087. EXPECT_EQ(StatusCode::OK_200, res->status);
  6088. EXPECT_EQ("content", received_body);
  6089. EXPECT_TRUE(progress_called);
  6090. }
  6091. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  6092. #ifdef CPPHTTPLIB_SSL_ENABLED
  6093. using ClientT = SSLClient;
  6094. #else
  6095. using ClientT = Client;
  6096. #endif
  6097. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  6098. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6099. const std::string &body, const std::string &content_type,
  6100. ContentReceiver receiver, DownloadProgress progress) {
  6101. return cli.Post(path, headers, body, content_type, receiver, progress);
  6102. });
  6103. }
  6104. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  6105. #ifdef CPPHTTPLIB_SSL_ENABLED
  6106. using ClientT = SSLClient;
  6107. #else
  6108. using ClientT = Client;
  6109. #endif
  6110. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  6111. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6112. const std::string &body, const std::string &content_type,
  6113. ContentReceiver receiver, DownloadProgress progress) {
  6114. return cli.Put(path, headers, body, content_type, receiver, progress);
  6115. });
  6116. }
  6117. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  6118. #ifdef CPPHTTPLIB_SSL_ENABLED
  6119. using ClientT = SSLClient;
  6120. #else
  6121. using ClientT = Client;
  6122. #endif
  6123. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  6124. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6125. const std::string &body, const std::string &content_type,
  6126. ContentReceiver receiver, DownloadProgress progress) {
  6127. return cli.Patch(path, headers, body, content_type, receiver, progress);
  6128. });
  6129. }
  6130. template <typename ClientType>
  6131. void TestWithHeadersAndContentReceiverError(
  6132. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  6133. const Headers &, const std::string &,
  6134. const std::string &, ContentReceiver)>
  6135. request_func) {
  6136. Headers headers;
  6137. headers.emplace("X-Error-Test", "true");
  6138. std::string received_body;
  6139. auto receiver_failed = false;
  6140. auto res =
  6141. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  6142. [&](const char *data, size_t data_length) {
  6143. received_body.append(data, data_length);
  6144. receiver_failed = true;
  6145. return false;
  6146. });
  6147. ASSERT_FALSE(res);
  6148. EXPECT_TRUE(receiver_failed);
  6149. }
  6150. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  6151. #ifdef CPPHTTPLIB_SSL_ENABLED
  6152. using ClientT = SSLClient;
  6153. #else
  6154. using ClientT = Client;
  6155. #endif
  6156. TestWithHeadersAndContentReceiverError<ClientT>(
  6157. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6158. const std::string &body, const std::string &content_type,
  6159. ContentReceiver receiver) {
  6160. return cli.Post(path, headers, body, content_type, receiver);
  6161. });
  6162. }
  6163. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  6164. #ifdef CPPHTTPLIB_SSL_ENABLED
  6165. using ClientT = SSLClient;
  6166. #else
  6167. using ClientT = Client;
  6168. #endif
  6169. TestWithHeadersAndContentReceiverError<ClientT>(
  6170. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6171. const std::string &body, const std::string &content_type,
  6172. ContentReceiver receiver) {
  6173. return cli.Put(path, headers, body, content_type, receiver);
  6174. });
  6175. }
  6176. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  6177. #ifdef CPPHTTPLIB_SSL_ENABLED
  6178. using ClientT = SSLClient;
  6179. #else
  6180. using ClientT = Client;
  6181. #endif
  6182. TestWithHeadersAndContentReceiverError<ClientT>(
  6183. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6184. const std::string &body, const std::string &content_type,
  6185. ContentReceiver receiver) {
  6186. return cli.Patch(path, headers, body, content_type, receiver);
  6187. });
  6188. }
  6189. TEST_F(ServerTest, PostQueryStringAndBody) {
  6190. auto res =
  6191. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  6192. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6193. ASSERT_EQ(StatusCode::OK_200, res->status);
  6194. }
  6195. TEST_F(ServerTest, HTTP2Magic) {
  6196. Request req;
  6197. req.method = "PRI";
  6198. req.path = "*";
  6199. req.body = "SM";
  6200. auto res = std::make_shared<Response>();
  6201. auto error = Error::Success;
  6202. auto ret = cli_.send(req, *res, error);
  6203. ASSERT_TRUE(ret);
  6204. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6205. }
  6206. TEST_F(ServerTest, KeepAlive) {
  6207. auto res = cli_.Get("/hi");
  6208. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6209. EXPECT_EQ(StatusCode::OK_200, res->status);
  6210. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6211. EXPECT_EQ("Hello World!", res->body);
  6212. res = cli_.Get("/hi");
  6213. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6214. EXPECT_EQ(StatusCode::OK_200, res->status);
  6215. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6216. EXPECT_EQ("Hello World!", res->body);
  6217. res = cli_.Get("/hi");
  6218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6219. EXPECT_EQ(StatusCode::OK_200, res->status);
  6220. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6221. EXPECT_EQ("Hello World!", res->body);
  6222. res = cli_.Get("/not-exist");
  6223. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6224. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6225. res = cli_.Post("/empty", "", "text/plain");
  6226. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6227. EXPECT_EQ(StatusCode::OK_200, res->status);
  6228. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6229. EXPECT_EQ("empty", res->body);
  6230. EXPECT_EQ("close", res->get_header_value("Connection"));
  6231. res = cli_.Post(
  6232. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  6233. "text/plain");
  6234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6235. EXPECT_EQ(StatusCode::OK_200, res->status);
  6236. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6237. EXPECT_EQ("empty", res->body);
  6238. cli_.set_keep_alive(false);
  6239. res = cli_.Get("/last-request");
  6240. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6241. EXPECT_EQ(StatusCode::OK_200, res->status);
  6242. EXPECT_EQ("close", res->get_header_value("Connection"));
  6243. }
  6244. TEST_F(ServerTest, TooManyRedirect) {
  6245. cli_.set_follow_location(true);
  6246. auto res = cli_.Get("/redirect/0");
  6247. ASSERT_TRUE(!res);
  6248. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  6249. }
  6250. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  6251. Request req;
  6252. req.method = "FOOBAR";
  6253. req.path = "/hi";
  6254. cli_.set_keep_alive(true);
  6255. auto res = cli_.send(req);
  6256. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6257. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6258. EXPECT_EQ("close", res->get_header_value("Connection"));
  6259. EXPECT_FALSE(cli_.is_socket_open());
  6260. }
  6261. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  6262. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6263. TEST_F(ServerTest, Gzip) {
  6264. Headers headers;
  6265. headers.emplace("Accept-Encoding", "gzip, deflate");
  6266. auto res = cli_.Get("/compress", headers);
  6267. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6268. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6269. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6270. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6271. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6272. "7890123456789012345678901234567890",
  6273. res->body);
  6274. EXPECT_EQ(StatusCode::OK_200, res->status);
  6275. }
  6276. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  6277. Headers headers;
  6278. headers.emplace("Accept-Encoding", "gzip, deflate");
  6279. auto res = cli_.Get("/compress-with-charset", headers);
  6280. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6281. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6282. EXPECT_EQ("application/json; charset=utf-8",
  6283. res->get_header_value("Content-Type"));
  6284. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6285. "7890123456789012345678901234567890",
  6286. res->body);
  6287. EXPECT_EQ(StatusCode::OK_200, res->status);
  6288. }
  6289. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  6290. Headers headers;
  6291. headers.emplace("Accept-Encoding", "");
  6292. auto res = cli_.Get("/compress", headers);
  6293. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6294. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6295. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6296. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6297. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6298. "7890123456789012345678901234567890",
  6299. res->body);
  6300. EXPECT_EQ(StatusCode::OK_200, res->status);
  6301. }
  6302. TEST_F(ServerTest, GzipWithContentReceiver) {
  6303. Headers headers;
  6304. headers.emplace("Accept-Encoding", "gzip, deflate");
  6305. std::string body;
  6306. auto res = cli_.Get("/compress", headers,
  6307. [&](const char *data, uint64_t data_length) {
  6308. EXPECT_EQ(100U, data_length);
  6309. body.append(data, data_length);
  6310. return true;
  6311. });
  6312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6313. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6314. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6315. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6316. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6317. "7890123456789012345678901234567890",
  6318. body);
  6319. EXPECT_EQ(StatusCode::OK_200, res->status);
  6320. }
  6321. TEST_F(ServerTest, GzipWithoutDecompressing) {
  6322. Headers headers;
  6323. headers.emplace("Accept-Encoding", "gzip, deflate");
  6324. cli_.set_decompress(false);
  6325. auto res = cli_.Get("/compress", headers);
  6326. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6327. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6328. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6329. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6330. EXPECT_EQ(33U, res->body.size());
  6331. EXPECT_EQ(StatusCode::OK_200, res->status);
  6332. }
  6333. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  6334. Headers headers;
  6335. headers.emplace("Accept-Encoding", "");
  6336. std::string body;
  6337. auto res = cli_.Get("/compress", headers,
  6338. [&](const char *data, uint64_t data_length) {
  6339. EXPECT_EQ(100U, data_length);
  6340. body.append(data, data_length);
  6341. return true;
  6342. });
  6343. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6344. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6345. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6346. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6347. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6348. "7890123456789012345678901234567890",
  6349. body);
  6350. EXPECT_EQ(StatusCode::OK_200, res->status);
  6351. }
  6352. TEST_F(ServerTest, NoGzip) {
  6353. Headers headers;
  6354. headers.emplace("Accept-Encoding", "gzip, deflate");
  6355. auto res = cli_.Get("/nocompress", headers);
  6356. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6357. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6358. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6359. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6360. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6361. "7890123456789012345678901234567890",
  6362. res->body);
  6363. EXPECT_EQ(StatusCode::OK_200, res->status);
  6364. }
  6365. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  6366. Headers headers;
  6367. headers.emplace("Accept-Encoding", "gzip, deflate");
  6368. std::string body;
  6369. auto res = cli_.Get("/nocompress", headers,
  6370. [&](const char *data, uint64_t data_length) {
  6371. EXPECT_EQ(100U, data_length);
  6372. body.append(data, data_length);
  6373. return true;
  6374. });
  6375. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6376. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6377. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6378. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6379. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6380. "7890123456789012345678901234567890",
  6381. body);
  6382. EXPECT_EQ(StatusCode::OK_200, res->status);
  6383. }
  6384. TEST_F(ServerTest, MultipartFormDataGzip) {
  6385. UploadFormDataItems items = {
  6386. {"key1", "test", "", ""},
  6387. {"key2", "--abcdefg123", "", ""},
  6388. };
  6389. cli_.set_compress(true);
  6390. auto res = cli_.Post("/compress-multipart", items);
  6391. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6392. EXPECT_EQ(StatusCode::OK_200, res->status);
  6393. }
  6394. #endif
  6395. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6396. TEST_F(ServerTest, Brotli) {
  6397. Headers headers;
  6398. headers.emplace("Accept-Encoding", "br");
  6399. auto res = cli_.Get("/compress", headers);
  6400. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6401. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  6402. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6403. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  6404. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6405. "7890123456789012345678901234567890",
  6406. res->body);
  6407. EXPECT_EQ(StatusCode::OK_200, res->status);
  6408. }
  6409. #endif
  6410. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  6411. TEST_F(ServerTest, Zstd) {
  6412. Headers headers;
  6413. headers.emplace("Accept-Encoding", "zstd");
  6414. auto res = cli_.Get("/compress", headers);
  6415. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6416. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6417. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6418. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6419. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6420. "7890123456789012345678901234567890",
  6421. res->body);
  6422. EXPECT_EQ(StatusCode::OK_200, res->status);
  6423. }
  6424. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  6425. Headers headers;
  6426. headers.emplace("Accept-Encoding", "");
  6427. auto res = cli_.Get("/compress", headers);
  6428. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6429. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6430. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6431. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6432. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6433. "7890123456789012345678901234567890",
  6434. res->body);
  6435. EXPECT_EQ(StatusCode::OK_200, res->status);
  6436. }
  6437. TEST_F(ServerTest, ZstdWithContentReceiver) {
  6438. Headers headers;
  6439. headers.emplace("Accept-Encoding", "zstd");
  6440. std::string body;
  6441. auto res = cli_.Get("/compress", headers,
  6442. [&](const char *data, uint64_t data_length) {
  6443. EXPECT_EQ(100U, data_length);
  6444. body.append(data, data_length);
  6445. return true;
  6446. });
  6447. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6448. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6449. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6450. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6451. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6452. "7890123456789012345678901234567890",
  6453. body);
  6454. EXPECT_EQ(StatusCode::OK_200, res->status);
  6455. }
  6456. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  6457. Headers headers;
  6458. headers.emplace("Accept-Encoding", "zstd");
  6459. cli_.set_decompress(false);
  6460. auto res = cli_.Get("/compress", headers);
  6461. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  6462. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  6463. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  6464. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  6465. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6466. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6467. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6468. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6469. EXPECT_EQ(StatusCode::OK_200, res->status);
  6470. ASSERT_EQ(26U, res->body.size());
  6471. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  6472. 0);
  6473. }
  6474. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  6475. Headers headers;
  6476. headers.emplace("Accept-Encoding", "");
  6477. std::string body;
  6478. auto res = cli_.Get("/compress", headers,
  6479. [&](const char *data, uint64_t data_length) {
  6480. EXPECT_EQ(100U, data_length);
  6481. body.append(data, data_length);
  6482. return true;
  6483. });
  6484. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6485. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6486. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6487. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6488. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6489. "7890123456789012345678901234567890",
  6490. body);
  6491. EXPECT_EQ(StatusCode::OK_200, res->status);
  6492. }
  6493. TEST_F(ServerTest, NoZstd) {
  6494. Headers headers;
  6495. headers.emplace("Accept-Encoding", "zstd");
  6496. auto res = cli_.Get("/nocompress", headers);
  6497. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6498. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6499. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6500. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6501. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6502. "7890123456789012345678901234567890",
  6503. res->body);
  6504. EXPECT_EQ(StatusCode::OK_200, res->status);
  6505. }
  6506. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  6507. Headers headers;
  6508. headers.emplace("Accept-Encoding", "zstd");
  6509. std::string body;
  6510. auto res = cli_.Get("/nocompress", headers,
  6511. [&](const char *data, uint64_t data_length) {
  6512. EXPECT_EQ(100U, data_length);
  6513. body.append(data, data_length);
  6514. return true;
  6515. });
  6516. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6517. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6518. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6519. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6520. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6521. "7890123456789012345678901234567890",
  6522. body);
  6523. EXPECT_EQ(StatusCode::OK_200, res->status);
  6524. }
  6525. // TODO: How to enable zstd ??
  6526. TEST_F(ServerTest, MultipartFormDataZstd) {
  6527. UploadFormDataItems items = {
  6528. {"key1", "test", "", ""},
  6529. {"key2", "--abcdefg123", "", ""},
  6530. };
  6531. Headers headers;
  6532. headers.emplace("Accept-Encoding", "zstd");
  6533. cli_.set_compress(true);
  6534. auto res = cli_.Post("/compress-multipart", headers, items);
  6535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6536. EXPECT_EQ(StatusCode::OK_200, res->status);
  6537. }
  6538. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  6539. Headers headers;
  6540. headers.emplace("Accept-Encoding", "zstd");
  6541. cli_.set_compress(true);
  6542. auto res = cli_.Put(
  6543. "/put", headers, 3,
  6544. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6545. sink.os << "PUT";
  6546. return true;
  6547. },
  6548. "text/plain");
  6549. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6550. EXPECT_EQ(StatusCode::OK_200, res->status);
  6551. EXPECT_EQ("PUT", res->body);
  6552. }
  6553. // Pre-compression logging tests
  6554. TEST_F(ServerTest, PreCompressionLogging) {
  6555. // Test data for compression (matches the actual /compress endpoint content)
  6556. const std::string test_content =
  6557. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6558. "3456789012345678901234567890";
  6559. // Variables to capture logging data
  6560. std::string pre_compression_body;
  6561. std::string pre_compression_content_type;
  6562. std::string pre_compression_content_encoding;
  6563. std::string post_compression_body;
  6564. std::string post_compression_content_type;
  6565. std::string post_compression_content_encoding;
  6566. // Set up pre-compression logger
  6567. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  6568. const Response &res) {
  6569. pre_compression_body = res.body;
  6570. pre_compression_content_type = res.get_header_value("Content-Type");
  6571. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  6572. });
  6573. // Set up post-compression logger
  6574. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6575. post_compression_body = res.body;
  6576. post_compression_content_type = res.get_header_value("Content-Type");
  6577. post_compression_content_encoding =
  6578. res.get_header_value("Content-Encoding");
  6579. });
  6580. // Test with gzip compression
  6581. Headers headers;
  6582. headers.emplace("Accept-Encoding", "gzip");
  6583. auto res = cli_.Get("/compress", headers);
  6584. // Verify response was compressed
  6585. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6586. EXPECT_EQ(StatusCode::OK_200, res->status);
  6587. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6588. // Verify pre-compression logger captured uncompressed content
  6589. EXPECT_EQ(test_content, pre_compression_body);
  6590. EXPECT_EQ("text/plain", pre_compression_content_type);
  6591. EXPECT_TRUE(pre_compression_content_encoding
  6592. .empty()); // No encoding header before compression
  6593. // Verify post-compression logger captured compressed content
  6594. EXPECT_NE(test_content,
  6595. post_compression_body); // Should be different after compression
  6596. EXPECT_EQ("text/plain", post_compression_content_type);
  6597. EXPECT_EQ("gzip", post_compression_content_encoding);
  6598. // Verify compressed content is smaller
  6599. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  6600. }
  6601. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  6602. const std::string test_content =
  6603. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6604. "3456789012345678901234567890";
  6605. std::string pre_compression_body;
  6606. std::string post_compression_body;
  6607. svr_.set_pre_compression_logger(
  6608. [&](const Request & /*req*/, const Response &res) {
  6609. pre_compression_body = res.body;
  6610. });
  6611. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6612. post_compression_body = res.body;
  6613. });
  6614. Headers headers;
  6615. headers.emplace("Accept-Encoding", "br");
  6616. auto res = cli_.Get("/compress", headers);
  6617. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6618. EXPECT_EQ(StatusCode::OK_200, res->status);
  6619. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  6620. // Verify pre-compression content is uncompressed
  6621. EXPECT_EQ(test_content, pre_compression_body);
  6622. // Verify post-compression content is compressed
  6623. EXPECT_NE(test_content, post_compression_body);
  6624. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  6625. }
  6626. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  6627. const std::string test_content =
  6628. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6629. "3456789012345678901234567890";
  6630. std::string pre_compression_body;
  6631. std::string post_compression_body;
  6632. svr_.set_pre_compression_logger(
  6633. [&](const Request & /*req*/, const Response &res) {
  6634. pre_compression_body = res.body;
  6635. });
  6636. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6637. post_compression_body = res.body;
  6638. });
  6639. // Request without compression (use /nocompress endpoint)
  6640. Headers headers;
  6641. auto res = cli_.Get("/nocompress", headers);
  6642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6643. EXPECT_EQ(StatusCode::OK_200, res->status);
  6644. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6645. // Pre-compression logger should not be called when no compression is applied
  6646. EXPECT_TRUE(
  6647. pre_compression_body.empty()); // Pre-compression logger not called
  6648. EXPECT_EQ(
  6649. test_content,
  6650. post_compression_body); // Post-compression logger captures final content
  6651. }
  6652. TEST_F(ServerTest, LoggerSeesContentLength) {
  6653. size_t logged_content_length = 0;
  6654. std::string logged_content_length_header;
  6655. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6656. logged_content_length = res.content_length_;
  6657. logged_content_length_header = res.get_header_value("Content-Length");
  6658. });
  6659. auto res = cli_.Get("/nocompress");
  6660. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6661. EXPECT_EQ(StatusCode::OK_200, res->status);
  6662. EXPECT_EQ(res->body.size(), logged_content_length);
  6663. EXPECT_EQ(std::to_string(logged_content_length),
  6664. logged_content_length_header);
  6665. }
  6666. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  6667. const std::string test_content =
  6668. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6669. "3456789012345678901234567890";
  6670. std::string pre_compression_body;
  6671. bool pre_logger_called = false;
  6672. // Set only pre-compression logger
  6673. svr_.set_pre_compression_logger(
  6674. [&](const Request & /*req*/, const Response &res) {
  6675. pre_compression_body = res.body;
  6676. pre_logger_called = true;
  6677. });
  6678. Headers headers;
  6679. headers.emplace("Accept-Encoding", "gzip");
  6680. auto res = cli_.Get("/compress", headers);
  6681. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6682. EXPECT_EQ(StatusCode::OK_200, res->status);
  6683. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6684. // Verify pre-compression logger was called
  6685. EXPECT_TRUE(pre_logger_called);
  6686. EXPECT_EQ(test_content, pre_compression_body);
  6687. }
  6688. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  6689. {
  6690. // Test with Expect: 100-continue header - success case
  6691. // Server returns 100 Continue, client sends body, server returns 200 OK
  6692. Request req;
  6693. req.method = "POST";
  6694. req.path = "/post-large";
  6695. req.set_header("Expect", "100-continue");
  6696. req.body = LARGE_DATA;
  6697. Response res;
  6698. auto error = Error::Success;
  6699. cli_.set_keep_alive(true);
  6700. auto ret = cli_.send(req, res, error);
  6701. EXPECT_TRUE(ret);
  6702. EXPECT_EQ(StatusCode::OK_200, res.status);
  6703. EXPECT_EQ(LARGE_DATA, res.body);
  6704. }
  6705. {
  6706. // Test with Expect: 100-continue header - error case
  6707. // Client should not send the body when server returns an error
  6708. Request req;
  6709. req.method = "POST";
  6710. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  6711. req.set_header("Expect", "100-continue");
  6712. req.body = LARGE_DATA;
  6713. Response res;
  6714. auto error = Error::Success;
  6715. auto start = std::chrono::high_resolution_clock::now();
  6716. cli_.set_keep_alive(true);
  6717. auto ret = cli_.send(req, res, error);
  6718. auto end = std::chrono::high_resolution_clock::now();
  6719. auto elapsed =
  6720. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6721. .count();
  6722. // With Expect: 100-continue, request completes successfully but with error
  6723. EXPECT_TRUE(ret);
  6724. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  6725. EXPECT_EQ("close", res.get_header_value("Connection"));
  6726. EXPECT_FALSE(cli_.is_socket_open());
  6727. EXPECT_LE(elapsed, 2000);
  6728. }
  6729. {
  6730. // Send an extra GET request to ensure error recovery without hanging
  6731. Request req;
  6732. req.method = "GET";
  6733. req.path = "/hi";
  6734. auto start = std::chrono::high_resolution_clock::now();
  6735. auto res = cli_.send(req);
  6736. auto end = std::chrono::high_resolution_clock::now();
  6737. auto elapsed =
  6738. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6739. .count();
  6740. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6741. EXPECT_EQ(StatusCode::OK_200, res->status);
  6742. EXPECT_EQ("Hello World!", res->body);
  6743. EXPECT_LE(elapsed, 500);
  6744. }
  6745. }
  6746. TEST(ZstdDecompressor, ChunkedDecompression) {
  6747. std::string data;
  6748. for (size_t i = 0; i < 32 * 1024; ++i) {
  6749. data.push_back(static_cast<char>('a' + i % 26));
  6750. }
  6751. std::string compressed_data;
  6752. {
  6753. httplib::detail::zstd_compressor compressor;
  6754. bool result = compressor.compress(
  6755. data.data(), data.size(),
  6756. /*last=*/true,
  6757. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  6758. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  6759. compressed_data_size);
  6760. return true;
  6761. });
  6762. ASSERT_TRUE(result);
  6763. }
  6764. std::string decompressed_data;
  6765. {
  6766. httplib::detail::zstd_decompressor decompressor;
  6767. // Chunk size is chosen specifically to have a decompressed chunk size equal
  6768. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  6769. size_t chunk_size = 130;
  6770. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  6771. chunk_begin += chunk_size) {
  6772. size_t current_chunk_size =
  6773. std::min(compressed_data.size() - chunk_begin, chunk_size);
  6774. bool result = decompressor.decompress(
  6775. compressed_data.data() + chunk_begin, current_chunk_size,
  6776. [&](const char *decompressed_data_chunk,
  6777. size_t decompressed_data_chunk_size) {
  6778. decompressed_data.insert(decompressed_data.size(),
  6779. decompressed_data_chunk,
  6780. decompressed_data_chunk_size);
  6781. return true;
  6782. });
  6783. ASSERT_TRUE(result);
  6784. }
  6785. }
  6786. ASSERT_EQ(data, decompressed_data);
  6787. }
  6788. TEST(ZstdDecompressor, Decompress) {
  6789. std::string original_text = "Compressed with ZSTD";
  6790. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  6791. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  6792. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  6793. 0x20, 0x5a, 0x53, 0x54, 0x44};
  6794. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6795. std::string decompressed_data;
  6796. {
  6797. httplib::detail::zstd_decompressor decompressor;
  6798. bool result = decompressor.decompress(
  6799. compressed_data.data(), compressed_data.size(),
  6800. [&](const char *decompressed_data_chunk,
  6801. size_t decompressed_data_chunk_size) {
  6802. decompressed_data.insert(decompressed_data.size(),
  6803. decompressed_data_chunk,
  6804. decompressed_data_chunk_size);
  6805. return true;
  6806. });
  6807. ASSERT_TRUE(result);
  6808. }
  6809. ASSERT_EQ(original_text, decompressed_data);
  6810. }
  6811. #endif
  6812. // Sends a raw request to a server listening at HOST:PORT.
  6813. static bool send_request(time_t read_timeout_sec, const std::string &req,
  6814. std::string *resp = nullptr) {
  6815. auto error = Error::Success;
  6816. auto client_sock = detail::create_client_socket(
  6817. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  6818. /*connection_timeout_sec=*/5, 0,
  6819. /*read_timeout_sec=*/5, 0,
  6820. /*write_timeout_sec=*/5, 0, std::string(), error);
  6821. if (client_sock == INVALID_SOCKET) { return false; }
  6822. auto ret = detail::process_client_socket(
  6823. client_sock, read_timeout_sec, 0, 0, 0, 0,
  6824. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  6825. if (req.size() !=
  6826. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  6827. return false;
  6828. }
  6829. char buf[512];
  6830. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  6831. while (line_reader.getline()) {
  6832. if (resp) { *resp += line_reader.ptr(); }
  6833. }
  6834. return true;
  6835. });
  6836. detail::close_socket(client_sock);
  6837. return ret;
  6838. }
  6839. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  6840. Server svr;
  6841. std::string header_value;
  6842. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  6843. header_value = req.get_header_value("foo");
  6844. res.set_content("ok", "text/plain");
  6845. });
  6846. thread t = thread([&] { svr.listen(HOST, PORT); });
  6847. auto se = detail::scope_exit([&] {
  6848. svr.stop();
  6849. t.join();
  6850. ASSERT_FALSE(svr.is_running());
  6851. });
  6852. svr.wait_until_ready();
  6853. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  6854. // like characters are not treated the same - use vertical tab and escape.
  6855. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  6856. "foo: \t \v bar \x1B\t \r\n"
  6857. "Connection: close\r\n"
  6858. "\r\n";
  6859. std::string res;
  6860. ASSERT_TRUE(send_request(5, req, &res));
  6861. EXPECT_EQ(header_value, "");
  6862. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  6863. }
  6864. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  6865. Server svr;
  6866. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  6867. auto i = new int(0);
  6868. res.set_header("Trailer", "X-Safe, X-Reflected");
  6869. res.set_chunked_content_provider(
  6870. "text/plain",
  6871. [i](size_t /*offset*/, DataSink &sink) {
  6872. if (*i == 0) {
  6873. sink.os << "body";
  6874. } else {
  6875. Headers trailer;
  6876. // A valid trailer that must survive.
  6877. trailer.emplace("X-Safe", "safe");
  6878. // Attacker-controlled value carrying CR/LF (response splitting).
  6879. trailer.emplace("X-Reflected",
  6880. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  6881. // Attacker-controlled name carrying CR/LF.
  6882. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  6883. sink.done_with_trailer(trailer);
  6884. }
  6885. (*i)++;
  6886. return true;
  6887. },
  6888. [i](bool /*success*/) { delete i; });
  6889. });
  6890. thread t = thread([&] { svr.listen(HOST, PORT); });
  6891. auto se = detail::scope_exit([&] {
  6892. svr.stop();
  6893. t.join();
  6894. ASSERT_FALSE(svr.is_running());
  6895. });
  6896. svr.wait_until_ready();
  6897. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  6898. "Host: " + HOST +
  6899. "\r\n"
  6900. "Connection: close\r\n"
  6901. "\r\n";
  6902. std::string res;
  6903. ASSERT_TRUE(send_request(5, req, &res));
  6904. // The injected fields must not appear anywhere in the raw response.
  6905. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  6906. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  6907. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  6908. // Invalid trailers are dropped entirely, matching set_header().
  6909. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  6910. // The valid trailer still passes through.
  6911. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  6912. }
  6913. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  6914. Server svr;
  6915. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  6916. // res.headers is a public field an application can populate directly,
  6917. // bypassing set_header()'s validation (e.g. reflecting a request value).
  6918. // A valid header that must survive.
  6919. res.headers.emplace("X-Safe", "safe");
  6920. // Attacker-controlled value carrying CR/LF (response splitting).
  6921. res.headers.emplace("X-Reflected",
  6922. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  6923. // Attacker-controlled name carrying CR/LF.
  6924. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  6925. res.set_content("body", "text/plain");
  6926. });
  6927. thread t = thread([&] { svr.listen(HOST, PORT); });
  6928. auto se = detail::scope_exit([&] {
  6929. svr.stop();
  6930. t.join();
  6931. ASSERT_FALSE(svr.is_running());
  6932. });
  6933. svr.wait_until_ready();
  6934. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  6935. "Host: " + HOST +
  6936. "\r\n"
  6937. "Connection: close\r\n"
  6938. "\r\n";
  6939. std::string res;
  6940. ASSERT_TRUE(send_request(5, req, &res));
  6941. // The injected fields must not appear anywhere in the raw response.
  6942. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  6943. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  6944. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  6945. // Invalid headers are dropped entirely, matching set_header().
  6946. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  6947. // The valid header still passes through.
  6948. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  6949. }
  6950. // Forward declaration: in split builds split.py strips `inline` and moves the
  6951. // definition into httplib.cc, so detail::write_request_line is not visible from
  6952. // the public httplib.h. Re-declaring it here lets the tests link against the
  6953. // symbol in both header-only and split builds.
  6954. namespace httplib {
  6955. namespace detail {
  6956. ssize_t write_request_line(Stream &strm, const std::string &method,
  6957. const std::string &path);
  6958. } // namespace detail
  6959. } // namespace httplib
  6960. TEST(RequestLineInjectionTest, RejectsCRLFInTarget) {
  6961. // A well-formed target is written verbatim.
  6962. {
  6963. detail::BufferStream strm;
  6964. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  6965. EXPECT_GT(n, 0);
  6966. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  6967. }
  6968. // A target carrying CR/LF must be rejected before anything reaches the wire,
  6969. // otherwise it splits the request line and injects a header or a whole
  6970. // request. This is what a decoded redirect Location ("%0D%0A") turns into
  6971. // when path encoding is disabled.
  6972. const std::string evil_targets[] = {
  6973. "/a\r\nInjected: pwned",
  6974. "/a\rInjected",
  6975. "/a\nInjected",
  6976. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  6977. };
  6978. for (const auto &evil : evil_targets) {
  6979. detail::BufferStream strm;
  6980. auto n = detail::write_request_line(strm, "GET", evil);
  6981. EXPECT_LT(n, 0);
  6982. EXPECT_TRUE(strm.get_buffer().empty());
  6983. }
  6984. }
  6985. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  6986. // End-to-end counterpart to RejectsCRLFInTarget. With path encoding disabled
  6987. // the client transmits the target verbatim, so a CR/LF-bearing target -- what
  6988. // a redirect Location "%0D%0A" decodes to -- reaches write_request. The
  6989. // client must fail cleanly with Error::Write instead of putting a
  6990. // request-line-less, header-injecting request on the wire.
  6991. Server svr;
  6992. svr.Get("/a", [](const Request &, Response &res) {
  6993. res.set_content("ok", "text/plain");
  6994. });
  6995. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6996. auto se = detail::scope_exit([&] {
  6997. svr.stop();
  6998. thread.join();
  6999. ASSERT_FALSE(svr.is_running());
  7000. });
  7001. svr.wait_until_ready();
  7002. {
  7003. Client cli(HOST, PORT);
  7004. cli.set_path_encode(false);
  7005. // The request is rejected before anything is written, so the connection
  7006. // stays silent and the subsequent response read would otherwise block for
  7007. // the full default read timeout. Shorten it -- the assertion is on the
  7008. // error, not the timeout.
  7009. cli.set_read_timeout(1, 0);
  7010. auto res = cli.Get("/a\r\nInjected: pwned");
  7011. EXPECT_FALSE(res);
  7012. EXPECT_EQ(Error::Write, res.error());
  7013. }
  7014. }
  7015. // Sends a raw request and verifies that there isn't a crash or exception.
  7016. static void test_raw_request(const std::string &req,
  7017. std::string *out = nullptr) {
  7018. Server svr;
  7019. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7020. res.set_content("ok", "text/plain");
  7021. });
  7022. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  7023. res.set_content("ok", "text/plain");
  7024. });
  7025. svr.Get("/header_field_value_check",
  7026. [&](const Request & /*req*/, Response &res) {
  7027. res.set_content("ok", "text/plain");
  7028. });
  7029. // Server read timeout must be longer than the client read timeout for the
  7030. // bug to reproduce, probably to force the server to process a request
  7031. // without a trailing blank line.
  7032. const time_t client_read_timeout_sec = 1;
  7033. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  7034. bool listen_thread_ok = false;
  7035. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  7036. auto se = detail::scope_exit([&] {
  7037. svr.stop();
  7038. t.join();
  7039. ASSERT_FALSE(svr.is_running());
  7040. EXPECT_TRUE(listen_thread_ok);
  7041. });
  7042. svr.wait_until_ready();
  7043. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  7044. }
  7045. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  7046. // A certain header line causes an exception if the header property is parsed
  7047. // naively with a single regex. This occurs with libc++ but not libstdc++.
  7048. test_raw_request(
  7049. "GET /hi HTTP/1.1\r\n"
  7050. " : "
  7051. " "
  7052. " ");
  7053. }
  7054. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  7055. // A certain header line causes an exception if the header property *name* is
  7056. // parsed with a regular expression starting with "(.+?):" - this is a non-
  7057. // greedy matcher and requires backtracking when there are a lot of ":"
  7058. // characters.
  7059. // This occurs with libc++ but not libstdc++.
  7060. test_raw_request(
  7061. "GET /hi HTTP/1.1\r\n"
  7062. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  7063. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  7064. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  7065. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  7066. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  7067. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  7068. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  7069. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  7070. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  7071. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  7072. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  7073. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  7074. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  7075. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  7076. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  7077. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  7078. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  7079. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  7080. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  7081. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  7082. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  7083. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  7084. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  7085. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  7086. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  7087. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  7088. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  7089. "&&&%%%");
  7090. }
  7091. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  7092. // Make sure this doesn't crash the server.
  7093. // In a previous version of the header line regex, the "\r" rendered the line
  7094. // unparsable and the regex engine repeatedly backtracked, trying to look for
  7095. // a new position where the leading white space ended and the field value
  7096. // began.
  7097. // The crash occurs with libc++ but not libstdc++.
  7098. test_raw_request("GET /hi HTTP/1.1\r\n"
  7099. "a:" +
  7100. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  7101. "\r\n"
  7102. "\r\n");
  7103. }
  7104. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  7105. std::string out;
  7106. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  7107. "Content-Type: text/plain\r\n"
  7108. "Transfer-Encoding: chunked\r\n"
  7109. "\r\n"
  7110. "nothex\r\n",
  7111. &out);
  7112. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7113. }
  7114. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  7115. std::string out;
  7116. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  7117. "Content-Type: text/plain\r\n"
  7118. "Transfer-Encoding: chunked\r\n"
  7119. "\r\n"
  7120. "3\r\n"
  7121. "xyz\r\n"
  7122. "NaN\r\n",
  7123. &out);
  7124. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7125. }
  7126. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  7127. std::string out;
  7128. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  7129. "Content-Type: text/plain\r\n"
  7130. "Transfer-Encoding: chunked\r\n"
  7131. "\r\n"
  7132. // Length is too large for 64 bits.
  7133. "1ffffffffffffffff\r\n"
  7134. "xyz\r\n",
  7135. &out);
  7136. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7137. }
  7138. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  7139. test_raw_request("GET /hi HTTP/1.1\r\n"
  7140. "Content-Type: text/plain\r\n\r");
  7141. }
  7142. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  7143. std::string out;
  7144. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  7145. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7146. }
  7147. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  7148. Server svr;
  7149. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  7150. EXPECT_TRUE(!req.remote_addr.empty());
  7151. });
  7152. thread t = thread([&] { svr.listen(HOST, PORT); });
  7153. auto se = detail::scope_exit([&] {
  7154. svr.stop();
  7155. t.join();
  7156. ASSERT_FALSE(svr.is_running());
  7157. });
  7158. svr.wait_until_ready();
  7159. // Send an invalid request line to trigger Bad Request
  7160. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  7161. std::string out;
  7162. ASSERT_TRUE(send_request(5, bad_req, &out));
  7163. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7164. }
  7165. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  7166. std::string out;
  7167. std::string request(
  7168. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  7169. test_raw_request(request, &out);
  7170. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7171. }
  7172. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  7173. std::string out;
  7174. std::string request(
  7175. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  7176. test_raw_request(request, &out);
  7177. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7178. }
  7179. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  7180. std::string out;
  7181. std::string request(
  7182. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  7183. test_raw_request(request, &out);
  7184. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7185. }
  7186. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  7187. std::string out;
  7188. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  7189. "Test: \r\n\r\n",
  7190. &out);
  7191. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  7192. }
  7193. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  7194. Server svr;
  7195. std::string x_custom;
  7196. std::string cookie;
  7197. std::string xff;
  7198. std::string x_unicode;
  7199. std::string x_iis;
  7200. svr.Get("/check", [&](const Request &req, Response &res) {
  7201. x_custom = req.get_header_value("X-Custom");
  7202. cookie = req.get_header_value("Cookie");
  7203. xff = req.get_header_value("X-Forwarded-For");
  7204. x_unicode = req.get_header_value("X-Unicode");
  7205. x_iis = req.get_header_value("X-IIS");
  7206. res.set_content("ok", "text/plain");
  7207. });
  7208. thread t = thread([&] { svr.listen(HOST, PORT); });
  7209. auto se = detail::scope_exit([&] {
  7210. svr.stop();
  7211. t.join();
  7212. ASSERT_FALSE(svr.is_running());
  7213. });
  7214. svr.wait_until_ready();
  7215. const std::string req = "GET /check HTTP/1.1\r\n"
  7216. "Host: localhost\r\n"
  7217. "X-Custom: a%0D%0AInjected: b\r\n"
  7218. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  7219. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  7220. "X-Unicode: %E3%81%82\r\n"
  7221. "X-IIS: %u00E9\r\n"
  7222. "Connection: close\r\n"
  7223. "\r\n";
  7224. std::string res;
  7225. ASSERT_TRUE(send_request(5, req, &res));
  7226. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7227. // Every value must be returned verbatim (wire form), with no decoding.
  7228. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  7229. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  7230. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  7231. EXPECT_EQ("%E3%81%82", x_unicode);
  7232. EXPECT_EQ("%u00E9", x_iis);
  7233. }
  7234. // Applications that previously relied on automatic percent-decoding can
  7235. // reproduce the old behavior by explicitly calling decode_path_component()
  7236. // or, for RFC 3986 conformance, decode_uri_component().
  7237. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  7238. Server svr;
  7239. std::string decoded;
  7240. svr.Get("/check", [&](const Request &req, Response &res) {
  7241. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  7242. res.set_content("ok", "text/plain");
  7243. });
  7244. thread t = thread([&] { svr.listen(HOST, PORT); });
  7245. auto se = detail::scope_exit([&] {
  7246. svr.stop();
  7247. t.join();
  7248. ASSERT_FALSE(svr.is_running());
  7249. });
  7250. svr.wait_until_ready();
  7251. const std::string req = "GET /check HTTP/1.1\r\n"
  7252. "Host: localhost\r\n"
  7253. "X-Custom: hello%20world\r\n"
  7254. "Connection: close\r\n"
  7255. "\r\n";
  7256. std::string res;
  7257. ASSERT_TRUE(send_request(5, req, &res));
  7258. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7259. EXPECT_EQ("hello world", decoded);
  7260. }
  7261. // Regression test for #2033. Browsers send Referer values that include
  7262. // percent-encoded characters such as %0A inside the URL. Decoding the
  7263. // header value would either trip the post-decode CR/LF/NUL guard (the
  7264. // original bug, returning 400) or, after that guard was relaxed, silently
  7265. // store a literal LF — both unacceptable. The wire form must round-trip.
  7266. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  7267. Server svr;
  7268. std::string referer;
  7269. svr.Get("/check", [&](const Request &req, Response &res) {
  7270. referer = req.get_header_value("Referer");
  7271. res.set_content("ok", "text/plain");
  7272. });
  7273. thread t = thread([&] { svr.listen(HOST, PORT); });
  7274. auto se = detail::scope_exit([&] {
  7275. svr.stop();
  7276. t.join();
  7277. ASSERT_FALSE(svr.is_running());
  7278. });
  7279. svr.wait_until_ready();
  7280. const std::string req = "GET /check HTTP/1.1\r\n"
  7281. "Host: localhost\r\n"
  7282. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  7283. "Connection: close\r\n"
  7284. "\r\n";
  7285. std::string res;
  7286. ASSERT_TRUE(send_request(5, req, &res));
  7287. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7288. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  7289. }
  7290. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  7291. Server svr;
  7292. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  7293. res.set_header("Cache-Control", "no-cache");
  7294. res.set_chunked_content_provider(
  7295. "text/event-stream", [](size_t offset, DataSink &sink) {
  7296. std::string s = "data:";
  7297. s += std::to_string(offset);
  7298. s += "\n\n";
  7299. auto ret = sink.write(s.data(), s.size());
  7300. EXPECT_TRUE(ret);
  7301. std::this_thread::sleep_for(std::chrono::seconds(1));
  7302. return true;
  7303. });
  7304. });
  7305. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7306. svr.wait_until_ready();
  7307. Client client(HOST, PORT);
  7308. const Headers headers = {{"Accept", "text/event-stream"}};
  7309. auto get_thread = std::thread([&client, &headers]() {
  7310. auto res = client.Get(
  7311. "/events", headers,
  7312. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  7313. });
  7314. auto se = detail::scope_exit([&] {
  7315. svr.stop();
  7316. get_thread.join();
  7317. listen_thread.join();
  7318. ASSERT_FALSE(svr.is_running());
  7319. });
  7320. // Give GET time to get a few messages.
  7321. std::this_thread::sleep_for(std::chrono::seconds(2));
  7322. }
  7323. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  7324. httplib::Server svr;
  7325. svr.Post("/hi",
  7326. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  7327. res.status = StatusCode::OK_200;
  7328. });
  7329. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7330. svr.wait_until_ready();
  7331. Client cli(HOST, PORT);
  7332. auto res = cli.Post("/hi", "data", "text/plain");
  7333. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7334. EXPECT_EQ(StatusCode::OK_200, res->status);
  7335. svr.stop();
  7336. thread.join();
  7337. ASSERT_FALSE(svr.is_running());
  7338. res = cli.Post("/hi", "data", "text/plain");
  7339. ASSERT_FALSE(res);
  7340. }
  7341. TEST(ServerStopTest, ListenFailure) {
  7342. Server svr;
  7343. auto t = thread([&]() {
  7344. auto ret = svr.listen("????", PORT);
  7345. EXPECT_FALSE(ret);
  7346. });
  7347. svr.wait_until_ready();
  7348. svr.stop();
  7349. t.join();
  7350. }
  7351. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  7352. TEST(ServerStopTest, Decommision) {
  7353. Server svr;
  7354. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  7355. for (int i = 0; i < 4; i++) {
  7356. auto is_even = !(i % 2);
  7357. std::thread t{[&] {
  7358. try {
  7359. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  7360. if (is_even) {
  7361. throw std::runtime_error("Some thing that happens to go wrong.");
  7362. }
  7363. svr.listen(HOST, PORT);
  7364. } catch (...) { svr.decommission(); }
  7365. }};
  7366. svr.wait_until_ready();
  7367. // Server is up
  7368. {
  7369. Client cli(HOST, PORT);
  7370. auto res = cli.Get("/hi");
  7371. if (is_even) {
  7372. EXPECT_FALSE(res);
  7373. } else {
  7374. EXPECT_TRUE(res);
  7375. EXPECT_EQ("hi...", res->body);
  7376. }
  7377. }
  7378. svr.stop();
  7379. t.join();
  7380. // Server is down...
  7381. {
  7382. Client cli(HOST, PORT);
  7383. auto res = cli.Get("/hi");
  7384. EXPECT_FALSE(res);
  7385. }
  7386. }
  7387. }
  7388. #endif
  7389. // Helper function for string body upload progress tests
  7390. template <typename SetupHandler, typename ClientCall>
  7391. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  7392. ClientCall &&client_call,
  7393. const string &body) {
  7394. Server svr;
  7395. setup_handler(svr);
  7396. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7397. auto se = detail::scope_exit([&] {
  7398. svr.stop();
  7399. t.join();
  7400. });
  7401. svr.wait_until_ready();
  7402. Client cli(HOST, PORT);
  7403. vector<uint64_t> progress_values;
  7404. bool progress_called = false;
  7405. auto res =
  7406. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  7407. progress_values.push_back(current);
  7408. progress_called = true;
  7409. return true;
  7410. });
  7411. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7412. EXPECT_EQ(200, res->status);
  7413. EXPECT_TRUE(progress_called);
  7414. }
  7415. TEST(UploadProgressTest, PostStringBodyBasic) {
  7416. TestStringBodyUploadProgress(
  7417. [](Server &svr) {
  7418. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  7419. res.set_content("received", "text/plain");
  7420. });
  7421. },
  7422. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7423. return cli.Post("/test", body, "text/plain", progress_callback);
  7424. },
  7425. "test data for upload progress");
  7426. }
  7427. TEST(UploadProgressTest, PutStringBodyBasic) {
  7428. TestStringBodyUploadProgress(
  7429. [](Server &svr) {
  7430. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  7431. res.set_content("put received", "text/plain");
  7432. });
  7433. },
  7434. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7435. return cli.Put("/test", body, "text/plain", progress_callback);
  7436. },
  7437. "put test data for upload progress");
  7438. }
  7439. TEST(UploadProgressTest, PatchStringBodyBasic) {
  7440. TestStringBodyUploadProgress(
  7441. [](Server &svr) {
  7442. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  7443. res.set_content("patch received", "text/plain");
  7444. });
  7445. },
  7446. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7447. return cli.Patch("/test", body, "text/plain", progress_callback);
  7448. },
  7449. "patch test data for upload progress");
  7450. }
  7451. // Helper function for content provider upload progress tests
  7452. template <typename SetupHandler, typename ClientCall>
  7453. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  7454. ClientCall &&client_call) {
  7455. Server svr;
  7456. setup_handler(svr);
  7457. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7458. auto se = detail::scope_exit([&] {
  7459. svr.stop();
  7460. t.join();
  7461. });
  7462. svr.wait_until_ready();
  7463. Client cli(HOST, PORT);
  7464. vector<uint64_t> progress_values;
  7465. auto res =
  7466. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  7467. progress_values.push_back(current);
  7468. return true;
  7469. });
  7470. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7471. EXPECT_EQ(200, res->status);
  7472. EXPECT_FALSE(progress_values.empty());
  7473. }
  7474. TEST(UploadProgressTest, PostContentProviderProgress) {
  7475. TestContentProviderUploadProgress(
  7476. [](Server &svr) {
  7477. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  7478. res.set_content("provider received", "text/plain");
  7479. });
  7480. },
  7481. [](Client &cli, UploadProgress progress_callback) {
  7482. return cli.Post(
  7483. "/test", 10,
  7484. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  7485. sink.os << "test data";
  7486. return true;
  7487. },
  7488. "text/plain", progress_callback);
  7489. });
  7490. }
  7491. // Helper function for multipart upload progress tests
  7492. template <typename SetupHandler, typename ClientCall>
  7493. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  7494. ClientCall &&client_call,
  7495. const string &endpoint) {
  7496. Server svr;
  7497. setup_handler(svr);
  7498. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7499. auto se = detail::scope_exit([&] {
  7500. svr.stop();
  7501. t.join();
  7502. });
  7503. svr.wait_until_ready();
  7504. Client cli(HOST, PORT);
  7505. vector<uint64_t> progress_values;
  7506. UploadFormDataItems items = {
  7507. {"field1", "value1", "", ""},
  7508. {"field2", "longer value for progress tracking test", "", ""},
  7509. {"file1", "file content data for upload progress", "test.txt",
  7510. "text/plain"}};
  7511. auto res = client_call(cli, endpoint, items,
  7512. [&](uint64_t current, uint64_t /*total*/) -> bool {
  7513. progress_values.push_back(current);
  7514. return true;
  7515. });
  7516. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7517. EXPECT_EQ(200, res->status);
  7518. EXPECT_FALSE(progress_values.empty());
  7519. }
  7520. TEST(UploadProgressTest, PostMultipartProgress) {
  7521. TestMultipartUploadProgress(
  7522. [](Server &svr) {
  7523. svr.Post("/multipart", [](const Request &req, Response &res) {
  7524. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  7525. res.set_content("multipart received", "text/plain");
  7526. });
  7527. },
  7528. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  7529. UploadProgress progress_callback) {
  7530. return cli.Post(endpoint, items, progress_callback);
  7531. },
  7532. "/multipart");
  7533. }
  7534. // Helper function for basic download progress tests
  7535. template <typename SetupHandler, typename ClientCall>
  7536. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  7537. ClientCall &&client_call, const string &endpoint,
  7538. size_t expected_content_size) {
  7539. Server svr;
  7540. setup_handler(svr);
  7541. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7542. auto se = detail::scope_exit([&] {
  7543. svr.stop();
  7544. t.join();
  7545. });
  7546. svr.wait_until_ready();
  7547. Client cli(HOST, PORT);
  7548. vector<uint64_t> progress_values;
  7549. auto res = client_call(cli, endpoint,
  7550. [&](uint64_t current, uint64_t /*total*/) -> bool {
  7551. progress_values.push_back(current);
  7552. return true;
  7553. });
  7554. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7555. EXPECT_EQ(200, res->status);
  7556. EXPECT_FALSE(progress_values.empty());
  7557. EXPECT_EQ(expected_content_size, res->body.size());
  7558. }
  7559. TEST(DownloadProgressTest, GetBasic) {
  7560. TestBasicDownloadProgress(
  7561. [](Server &svr) {
  7562. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  7563. string content(1000, 'D');
  7564. res.set_content(content, "text/plain");
  7565. });
  7566. },
  7567. [](Client &cli, const string &endpoint,
  7568. DownloadProgress progress_callback) {
  7569. return cli.Get(endpoint, progress_callback);
  7570. },
  7571. "/download", 1000u);
  7572. }
  7573. // Helper function for content receiver download progress tests
  7574. template <typename SetupHandler, typename ClientCall>
  7575. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  7576. ClientCall &&client_call,
  7577. const string &endpoint,
  7578. size_t expected_content_size) {
  7579. Server svr;
  7580. setup_handler(svr);
  7581. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7582. auto se = detail::scope_exit([&] {
  7583. svr.stop();
  7584. t.join();
  7585. });
  7586. svr.wait_until_ready();
  7587. Client cli(HOST, PORT);
  7588. vector<uint64_t> progress_values;
  7589. string received_body;
  7590. auto res = client_call(
  7591. cli, endpoint,
  7592. [&](const char *data, size_t data_length) -> bool {
  7593. received_body.append(data, data_length);
  7594. return true;
  7595. },
  7596. [&](uint64_t current, uint64_t /*total*/) -> bool {
  7597. progress_values.push_back(current);
  7598. return true;
  7599. });
  7600. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7601. EXPECT_EQ(200, res->status);
  7602. EXPECT_FALSE(progress_values.empty());
  7603. EXPECT_EQ(expected_content_size, received_body.size());
  7604. EXPECT_TRUE(res->body.empty());
  7605. }
  7606. TEST(DownloadProgressTest, GetWithContentReceiver) {
  7607. TestContentReceiverDownloadProgress(
  7608. [](Server &svr) {
  7609. svr.Get("/download-receiver",
  7610. [](const Request & /*req*/, Response &res) {
  7611. string content(2000, 'R');
  7612. res.set_content(content, "text/plain");
  7613. });
  7614. },
  7615. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  7616. DownloadProgress progress_callback) {
  7617. return cli.Get(endpoint, content_receiver, progress_callback);
  7618. },
  7619. "/download-receiver", 2000u);
  7620. }
  7621. TEST(StreamingTest, NoContentLengthStreaming) {
  7622. Server svr;
  7623. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  7624. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  7625. if (offset < 6) {
  7626. sink.os << (offset < 3 ? "a" : "b");
  7627. } else {
  7628. sink.done();
  7629. }
  7630. return true;
  7631. });
  7632. });
  7633. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7634. auto listen_se = detail::scope_exit([&] {
  7635. svr.stop();
  7636. listen_thread.join();
  7637. ASSERT_FALSE(svr.is_running());
  7638. });
  7639. svr.wait_until_ready();
  7640. Client client(HOST, PORT);
  7641. auto get_thread = std::thread([&client]() {
  7642. std::string s;
  7643. auto res =
  7644. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  7645. s += std::string(data, len);
  7646. return true;
  7647. });
  7648. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7649. EXPECT_EQ(StatusCode::OK_200, res->status);
  7650. EXPECT_EQ("aaabbb", s);
  7651. });
  7652. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  7653. // Give GET time to get a few messages.
  7654. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  7655. }
  7656. TEST(MountTest, Unmount) {
  7657. Server svr;
  7658. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7659. auto se = detail::scope_exit([&] {
  7660. svr.stop();
  7661. listen_thread.join();
  7662. ASSERT_FALSE(svr.is_running());
  7663. });
  7664. svr.wait_until_ready();
  7665. Client cli("localhost", PORT);
  7666. svr.set_mount_point("/mount2", "./www2");
  7667. auto res = cli.Get("/");
  7668. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7669. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7670. res = cli.Get("/mount2/dir/test.html");
  7671. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7672. EXPECT_EQ(StatusCode::OK_200, res->status);
  7673. svr.set_mount_point("/", "./www");
  7674. res = cli.Get("/dir/");
  7675. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7676. EXPECT_EQ(StatusCode::OK_200, res->status);
  7677. svr.remove_mount_point("/");
  7678. res = cli.Get("/dir/");
  7679. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7680. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7681. svr.remove_mount_point("/mount2");
  7682. res = cli.Get("/mount2/dir/test.html");
  7683. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7684. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7685. }
  7686. TEST(MountTest, Redicect) {
  7687. Server svr;
  7688. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7689. auto se = detail::scope_exit([&] {
  7690. svr.stop();
  7691. listen_thread.join();
  7692. ASSERT_FALSE(svr.is_running());
  7693. });
  7694. svr.set_mount_point("/", "./www");
  7695. svr.wait_until_ready();
  7696. Client cli("localhost", PORT);
  7697. auto res = cli.Get("/dir/");
  7698. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7699. EXPECT_EQ(StatusCode::OK_200, res->status);
  7700. res = cli.Get("/dir");
  7701. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7702. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7703. res = cli.Get("/file");
  7704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7705. EXPECT_EQ(StatusCode::OK_200, res->status);
  7706. res = cli.Get("/file/");
  7707. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7708. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7709. cli.set_follow_location(true);
  7710. res = cli.Get("/dir");
  7711. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7712. EXPECT_EQ(StatusCode::OK_200, res->status);
  7713. }
  7714. TEST(MountTest, MultibytesPathName) {
  7715. Server svr;
  7716. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7717. auto se = detail::scope_exit([&] {
  7718. svr.stop();
  7719. listen_thread.join();
  7720. ASSERT_FALSE(svr.is_running());
  7721. });
  7722. svr.set_mount_point("/", "./www");
  7723. svr.wait_until_ready();
  7724. Client cli("localhost", PORT);
  7725. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  7726. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7727. EXPECT_EQ(StatusCode::OK_200, res->status);
  7728. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  7729. }
  7730. #ifdef _WIN32
  7731. // Issue #2435: mmap::open() must succeed even when another handle holds
  7732. // the file open for writing (e.g. an active log file).
  7733. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  7734. const char *path = "mmap_concurrent_writer_test.txt";
  7735. const char *content = "hello";
  7736. {
  7737. std::ofstream f(path, std::ios::binary);
  7738. f.write(content, static_cast<std::streamsize>(strlen(content)));
  7739. }
  7740. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  7741. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  7742. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  7743. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  7744. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  7745. detail::mmap m(path);
  7746. ASSERT_TRUE(m.is_open());
  7747. EXPECT_EQ(strlen(content), m.size());
  7748. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  7749. }
  7750. #endif
  7751. TEST(KeepAliveTest, ReadTimeout) {
  7752. Server svr;
  7753. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  7754. std::this_thread::sleep_for(std::chrono::seconds(2));
  7755. res.set_content("a", "text/plain");
  7756. });
  7757. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  7758. res.set_content("b", "text/plain");
  7759. });
  7760. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7761. auto se = detail::scope_exit([&] {
  7762. svr.stop();
  7763. listen_thread.join();
  7764. ASSERT_FALSE(svr.is_running());
  7765. });
  7766. svr.wait_until_ready();
  7767. Client cli("localhost", PORT);
  7768. cli.set_keep_alive(true);
  7769. cli.set_read_timeout(std::chrono::seconds(1));
  7770. auto resa = cli.Get("/a");
  7771. ASSERT_FALSE(resa);
  7772. EXPECT_EQ(Error::Read, resa.error());
  7773. auto resb = cli.Get("/b");
  7774. ASSERT_TRUE(resb);
  7775. EXPECT_EQ(StatusCode::OK_200, resb->status);
  7776. EXPECT_EQ("b", resb->body);
  7777. }
  7778. TEST(KeepAliveTest, MaxCount) {
  7779. size_t keep_alive_max_count = 3;
  7780. Server svr;
  7781. svr.set_keep_alive_max_count(keep_alive_max_count);
  7782. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  7783. res.set_content("Hello World!", "text/plain");
  7784. });
  7785. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7786. auto se = detail::scope_exit([&] {
  7787. svr.stop();
  7788. listen_thread.join();
  7789. ASSERT_FALSE(svr.is_running());
  7790. });
  7791. svr.wait_until_ready();
  7792. Client cli(HOST, PORT);
  7793. cli.set_keep_alive(true);
  7794. for (size_t i = 0; i < 5; i++) {
  7795. auto result = cli.Get("/hi");
  7796. ASSERT_TRUE(result);
  7797. EXPECT_EQ(StatusCode::OK_200, result->status);
  7798. if (i == keep_alive_max_count - 1) {
  7799. EXPECT_EQ("close", result->get_header_value("Connection"));
  7800. } else {
  7801. EXPECT_FALSE(result->has_header("Connection"));
  7802. }
  7803. }
  7804. }
  7805. TEST(KeepAliveTest, Issue1041) {
  7806. Server svr;
  7807. svr.set_keep_alive_timeout(3);
  7808. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  7809. res.set_content("Hello World!", "text/plain");
  7810. });
  7811. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7812. auto se = detail::scope_exit([&] {
  7813. svr.stop();
  7814. listen_thread.join();
  7815. ASSERT_FALSE(svr.is_running());
  7816. });
  7817. svr.wait_until_ready();
  7818. Client cli(HOST, PORT);
  7819. cli.set_keep_alive(true);
  7820. auto result = cli.Get("/hi");
  7821. ASSERT_TRUE(result);
  7822. EXPECT_EQ(StatusCode::OK_200, result->status);
  7823. std::this_thread::sleep_for(std::chrono::seconds(5));
  7824. result = cli.Get("/hi");
  7825. ASSERT_TRUE(result);
  7826. EXPECT_EQ(StatusCode::OK_200, result->status);
  7827. }
  7828. TEST(KeepAliveTest, Issue1959) {
  7829. Server svr;
  7830. svr.set_keep_alive_timeout(5);
  7831. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  7832. res.set_content("a", "text/plain");
  7833. });
  7834. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7835. auto se = detail::scope_exit([&] {
  7836. if (!svr.is_running()) return;
  7837. svr.stop();
  7838. listen_thread.join();
  7839. ASSERT_FALSE(svr.is_running());
  7840. });
  7841. svr.wait_until_ready();
  7842. Client cli("localhost", PORT);
  7843. cli.set_keep_alive(true);
  7844. using namespace std::chrono;
  7845. auto start = steady_clock::now();
  7846. cli.Get("/a");
  7847. svr.stop();
  7848. listen_thread.join();
  7849. auto end = steady_clock::now();
  7850. auto elapsed = duration_cast<milliseconds>(end - start).count();
  7851. EXPECT_LT(elapsed, 5000);
  7852. }
  7853. #ifdef CPPHTTPLIB_SSL_ENABLED
  7854. TEST(KeepAliveTest, SSLClientReconnection) {
  7855. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7856. ASSERT_TRUE(svr.is_valid());
  7857. svr.set_keep_alive_timeout(1);
  7858. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  7859. res.set_content("Hello World!", "text/plain");
  7860. });
  7861. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7862. auto se = detail::scope_exit([&] {
  7863. svr.stop();
  7864. listen_thread.join();
  7865. ASSERT_FALSE(svr.is_running());
  7866. });
  7867. svr.wait_until_ready();
  7868. SSLClient cli(HOST, PORT);
  7869. cli.enable_server_certificate_verification(false);
  7870. cli.set_keep_alive(true);
  7871. auto result = cli.Get("/hi");
  7872. ASSERT_TRUE(result);
  7873. EXPECT_EQ(StatusCode::OK_200, result->status);
  7874. result = cli.Get("/hi");
  7875. ASSERT_TRUE(result);
  7876. EXPECT_EQ(StatusCode::OK_200, result->status);
  7877. std::this_thread::sleep_for(std::chrono::seconds(2));
  7878. // Recoonect
  7879. result = cli.Get("/hi");
  7880. ASSERT_TRUE(result);
  7881. EXPECT_EQ(StatusCode::OK_200, result->status);
  7882. result = cli.Get("/hi");
  7883. ASSERT_TRUE(result);
  7884. EXPECT_EQ(StatusCode::OK_200, result->status);
  7885. }
  7886. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  7887. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7888. ASSERT_TRUE(svr.is_valid());
  7889. svr.set_keep_alive_timeout(1);
  7890. std::string content = "reconnect";
  7891. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  7892. res.set_content("Hello World!", "text/plain");
  7893. });
  7894. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7895. auto se = detail::scope_exit([&] {
  7896. svr.stop();
  7897. listen_thread.join();
  7898. ASSERT_FALSE(svr.is_running());
  7899. });
  7900. svr.wait_until_ready();
  7901. SSLClient cli(HOST, PORT);
  7902. cli.enable_server_certificate_verification(false);
  7903. cli.set_keep_alive(true);
  7904. auto result = cli.Post(
  7905. "/hi", content.size(),
  7906. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7907. sink.write(content.c_str(), content.size());
  7908. return true;
  7909. },
  7910. "text/plain");
  7911. ASSERT_TRUE(result);
  7912. EXPECT_EQ(200, result->status);
  7913. std::this_thread::sleep_for(std::chrono::seconds(2));
  7914. // Recoonect
  7915. result = cli.Post(
  7916. "/hi", content.size(),
  7917. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7918. sink.write(content.c_str(), content.size());
  7919. return true;
  7920. },
  7921. "text/plain");
  7922. ASSERT_TRUE(result);
  7923. EXPECT_EQ(200, result->status);
  7924. result = cli.Post(
  7925. "/hi", content.size(),
  7926. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7927. sink.write(content.c_str(), content.size());
  7928. return true;
  7929. },
  7930. "text/plain");
  7931. ASSERT_TRUE(result);
  7932. EXPECT_EQ(200, result->status);
  7933. }
  7934. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  7935. using namespace httplib::tls;
  7936. {
  7937. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7938. ASSERT_TRUE(svr.is_valid());
  7939. svr.Get("/sni", [&](const Request &req, Response &res) {
  7940. std::string expected = req.sni();
  7941. EXPECT_EQ(expected, req.get_param_value("expected"));
  7942. res.set_content("ok", "text/plain");
  7943. });
  7944. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7945. auto se = detail::scope_exit([&] {
  7946. svr.stop();
  7947. listen_thread.join();
  7948. ASSERT_FALSE(svr.is_running());
  7949. });
  7950. svr.wait_until_ready();
  7951. {
  7952. SSLClient cli("localhost", PORT);
  7953. cli.enable_server_certificate_verification(false);
  7954. auto res = cli.Get("/sni?expected=localhost");
  7955. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7956. }
  7957. {
  7958. SSLClient cli("::1", PORT);
  7959. cli.enable_server_certificate_verification(false);
  7960. auto res = cli.Get("/sni?expected=");
  7961. // NOTE: This may fail if the server is listening on IPv4 only
  7962. // (e.g., when localhost resolves to 127.0.0.1 only)
  7963. if (res) {
  7964. EXPECT_EQ(StatusCode::OK_200, res->status);
  7965. } else {
  7966. EXPECT_EQ(Error::Connection, res.error());
  7967. }
  7968. }
  7969. }
  7970. }
  7971. #endif
  7972. TEST(ClientProblemDetectionTest, ContentProvider) {
  7973. Server svr;
  7974. size_t content_length = 1024 * 1024;
  7975. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7976. res.set_content_provider(
  7977. content_length, "text/plain",
  7978. [&](size_t offset, size_t length, DataSink &sink) {
  7979. auto out_len = std::min(length, static_cast<size_t>(1024));
  7980. std::string out(out_len, '@');
  7981. sink.write(out.data(), out_len);
  7982. return offset < 4096;
  7983. },
  7984. [](bool success) { ASSERT_FALSE(success); });
  7985. });
  7986. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  7987. res.set_content_provider(
  7988. 0, "text/plain",
  7989. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  7990. EXPECT_TRUE(false);
  7991. return true;
  7992. },
  7993. [](bool success) { ASSERT_FALSE(success); });
  7994. });
  7995. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7996. auto se = detail::scope_exit([&] {
  7997. svr.stop();
  7998. listen_thread.join();
  7999. ASSERT_FALSE(svr.is_running());
  8000. });
  8001. svr.wait_until_ready();
  8002. Client cli("localhost", PORT);
  8003. {
  8004. auto res = cli.Get("/hi", [&](const char * /*data*/,
  8005. size_t /*data_length*/) { return false; });
  8006. ASSERT_FALSE(res);
  8007. }
  8008. {
  8009. auto res = cli.Get("/empty", [&](const char * /*data*/,
  8010. size_t /*data_length*/) { return false; });
  8011. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8012. }
  8013. }
  8014. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  8015. Server svr;
  8016. svr.set_error_handler([](Request const &, Response &res) -> void {
  8017. res.set_chunked_content_provider(
  8018. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  8019. sink.os << "hello";
  8020. sink.os << "world";
  8021. sink.done();
  8022. return true;
  8023. });
  8024. });
  8025. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8026. auto se = detail::scope_exit([&] {
  8027. svr.stop();
  8028. listen_thread.join();
  8029. ASSERT_FALSE(svr.is_running());
  8030. });
  8031. svr.wait_until_ready();
  8032. Client cli("localhost", PORT);
  8033. auto res = cli.Get("/");
  8034. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8035. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8036. EXPECT_EQ("helloworld", res->body);
  8037. }
  8038. TEST(LongPollingTest, ClientCloseDetection) {
  8039. Server svr;
  8040. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  8041. res.set_chunked_content_provider(
  8042. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  8043. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  8044. sink.os << "hello";
  8045. auto count = 10;
  8046. while (count > 0 && sink.is_writable()) {
  8047. this_thread::sleep_for(chrono::milliseconds(10));
  8048. count--;
  8049. }
  8050. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  8051. return true;
  8052. });
  8053. });
  8054. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8055. auto se = detail::scope_exit([&] {
  8056. svr.stop();
  8057. listen_thread.join();
  8058. ASSERT_FALSE(svr.is_running());
  8059. });
  8060. svr.wait_until_ready();
  8061. Client cli("localhost", PORT);
  8062. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  8063. EXPECT_EQ("hello", string(data, data_length));
  8064. return false; // close the socket immediately.
  8065. });
  8066. ASSERT_FALSE(res);
  8067. }
  8068. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  8069. Server svr;
  8070. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  8071. res.set_chunked_content_provider(
  8072. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  8073. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  8074. sink.os << "hello";
  8075. EXPECT_TRUE(sink.os.good());
  8076. // Wait for the client to close the connection
  8077. auto count = 10;
  8078. while (count > 0 && sink.is_writable()) {
  8079. this_thread::sleep_for(chrono::milliseconds(10));
  8080. count--;
  8081. }
  8082. // After client disconnect, write repeatedly until the socket
  8083. // write actually fails (small writes may be absorbed by the
  8084. // kernel buffer)
  8085. std::string chunk(1024, 'x');
  8086. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  8087. sink.os << chunk;
  8088. }
  8089. EXPECT_TRUE(sink.os.fail());
  8090. return true;
  8091. });
  8092. });
  8093. auto port = svr.bind_to_any_port("localhost");
  8094. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  8095. auto se = detail::scope_exit([&] {
  8096. svr.stop();
  8097. listen_thread.join();
  8098. ASSERT_FALSE(svr.is_running());
  8099. });
  8100. svr.wait_until_ready();
  8101. Client cli("localhost", port);
  8102. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  8103. EXPECT_EQ("hello", string(data, data_length));
  8104. return false; // close the socket immediately.
  8105. });
  8106. ASSERT_FALSE(res);
  8107. }
  8108. TEST(GetWithParametersTest, GetWithParameters) {
  8109. Server svr;
  8110. svr.Get("/", [&](const Request &req, Response &) {
  8111. EXPECT_EQ("world", req.get_param_value("hello"));
  8112. EXPECT_EQ("world2", req.get_param_value("hello2"));
  8113. EXPECT_EQ("world3", req.get_param_value("hello3"));
  8114. });
  8115. svr.Get("/params", [&](const Request &req, Response &) {
  8116. EXPECT_EQ("world", req.get_param_value("hello"));
  8117. EXPECT_EQ("world2", req.get_param_value("hello2"));
  8118. EXPECT_EQ("world3", req.get_param_value("hello3"));
  8119. });
  8120. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  8121. EXPECT_EQ("resource-id", req.matches[1]);
  8122. EXPECT_EQ("foo", req.get_param_value("param1"));
  8123. EXPECT_EQ("bar", req.get_param_value("param2"));
  8124. });
  8125. svr.Get("/users/:id", [&](const Request &req, Response &) {
  8126. EXPECT_EQ("user-id", req.path_params.at("id"));
  8127. EXPECT_EQ("foo", req.get_param_value("param1"));
  8128. EXPECT_EQ("bar", req.get_param_value("param2"));
  8129. });
  8130. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  8131. auto se = detail::scope_exit([&] {
  8132. svr.stop();
  8133. listen_thread.join();
  8134. ASSERT_FALSE(svr.is_running());
  8135. });
  8136. svr.wait_until_ready();
  8137. {
  8138. Client cli(HOST, PORT);
  8139. Params params;
  8140. params.emplace("hello", "world");
  8141. params.emplace("hello2", "world2");
  8142. params.emplace("hello3", "world3");
  8143. auto res = cli.Get("/", params, Headers{});
  8144. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8145. EXPECT_EQ(StatusCode::OK_200, res->status);
  8146. }
  8147. {
  8148. Client cli(HOST, PORT);
  8149. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  8150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8151. EXPECT_EQ(StatusCode::OK_200, res->status);
  8152. }
  8153. {
  8154. Client cli(HOST, PORT);
  8155. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  8156. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8157. EXPECT_EQ(StatusCode::OK_200, res->status);
  8158. }
  8159. {
  8160. Client cli(HOST, PORT);
  8161. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  8162. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8163. EXPECT_EQ(StatusCode::OK_200, res->status);
  8164. }
  8165. }
  8166. TEST(GetWithParametersTest, GetWithParameters2) {
  8167. Server svr;
  8168. svr.Get("/", [&](const Request &req, Response &res) {
  8169. auto text = req.get_param_value("hello");
  8170. res.set_content(text, "text/plain");
  8171. });
  8172. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8173. auto se = detail::scope_exit([&] {
  8174. svr.stop();
  8175. listen_thread.join();
  8176. ASSERT_FALSE(svr.is_running());
  8177. });
  8178. svr.wait_until_ready();
  8179. Client cli("localhost", PORT);
  8180. Params params;
  8181. params.emplace("hello", "world");
  8182. std::string body;
  8183. auto res = cli.Get("/", params, Headers{},
  8184. [&](const char *data, size_t data_length) {
  8185. body.append(data, data_length);
  8186. return true;
  8187. });
  8188. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8189. EXPECT_EQ(StatusCode::OK_200, res->status);
  8190. EXPECT_EQ("world", body);
  8191. }
  8192. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  8193. Server svr;
  8194. svr.Get("/search", [&](const Request &req, Response &res) {
  8195. auto q = req.get_param_value("q");
  8196. res.set_content(q, "text/plain");
  8197. });
  8198. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8199. auto se = detail::scope_exit([&] {
  8200. svr.stop();
  8201. listen_thread.join();
  8202. ASSERT_FALSE(svr.is_running());
  8203. });
  8204. svr.wait_until_ready();
  8205. Client cli("localhost", PORT);
  8206. // Verify that Get(path, params) works without requiring Headers argument
  8207. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  8208. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8209. EXPECT_EQ(StatusCode::OK_200, res->status);
  8210. EXPECT_EQ("cpp-httplib", res->body);
  8211. }
  8212. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  8213. auto host = "httpbingo.org";
  8214. auto path = std::string{"/range/32"};
  8215. #ifdef CPPHTTPLIB_SSL_ENABLED
  8216. SSLClient cli(host);
  8217. #else
  8218. Client cli(host);
  8219. #endif
  8220. cli.set_default_headers({make_range_header({{1, 10}})});
  8221. cli.set_connection_timeout(5);
  8222. {
  8223. auto res = cli.Get(path);
  8224. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8225. EXPECT_EQ("bcdefghijk", res->body);
  8226. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8227. }
  8228. {
  8229. auto res = cli.Get(path);
  8230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8231. EXPECT_EQ("bcdefghijk", res->body);
  8232. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8233. }
  8234. }
  8235. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  8236. Server svr;
  8237. svr.set_default_headers({{"Hello", "World"}});
  8238. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  8239. res.set_content("ok", "text/plain");
  8240. });
  8241. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8242. auto se = detail::scope_exit([&] {
  8243. svr.stop();
  8244. listen_thread.join();
  8245. ASSERT_FALSE(svr.is_running());
  8246. });
  8247. svr.wait_until_ready();
  8248. Client cli("localhost", PORT);
  8249. auto res = cli.Get("/");
  8250. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8251. EXPECT_EQ(StatusCode::OK_200, res->status);
  8252. EXPECT_EQ("ok", res->body);
  8253. EXPECT_EQ("World", res->get_header_value("Hello"));
  8254. }
  8255. #ifdef CPPHTTPLIB_SSL_ENABLED
  8256. TEST(KeepAliveTest, ReadTimeoutSSL) {
  8257. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8258. ASSERT_TRUE(svr.is_valid());
  8259. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  8260. std::this_thread::sleep_for(std::chrono::seconds(2));
  8261. res.set_content("a", "text/plain");
  8262. });
  8263. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  8264. res.set_content("b", "text/plain");
  8265. });
  8266. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8267. auto se = detail::scope_exit([&] {
  8268. svr.stop();
  8269. listen_thread.join();
  8270. ASSERT_FALSE(svr.is_running());
  8271. });
  8272. svr.wait_until_ready();
  8273. SSLClient cli("localhost", PORT);
  8274. cli.enable_server_certificate_verification(false);
  8275. cli.set_keep_alive(true);
  8276. cli.set_read_timeout(std::chrono::seconds(1));
  8277. auto resa = cli.Get("/a");
  8278. ASSERT_TRUE(!resa);
  8279. EXPECT_EQ(Error::Read, resa.error());
  8280. auto resb = cli.Get("/b");
  8281. ASSERT_TRUE(resb);
  8282. EXPECT_EQ(StatusCode::OK_200, resb->status);
  8283. EXPECT_EQ("b", resb->body);
  8284. }
  8285. #endif
  8286. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  8287. protected:
  8288. ServerTestWithAI_PASSIVE()
  8289. : cli_(HOST, PORT)
  8290. #ifdef CPPHTTPLIB_SSL_ENABLED
  8291. ,
  8292. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  8293. #endif
  8294. {
  8295. #ifdef CPPHTTPLIB_SSL_ENABLED
  8296. cli_.enable_server_certificate_verification(false);
  8297. #endif
  8298. }
  8299. virtual void SetUp() {
  8300. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  8301. res.set_content("Hello World!", "text/plain");
  8302. });
  8303. t_ = thread(
  8304. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  8305. svr_.wait_until_ready();
  8306. }
  8307. virtual void TearDown() {
  8308. svr_.stop();
  8309. t_.join();
  8310. }
  8311. #ifdef CPPHTTPLIB_SSL_ENABLED
  8312. SSLClient cli_;
  8313. SSLServer svr_;
  8314. #else
  8315. Client cli_;
  8316. Server svr_;
  8317. #endif
  8318. thread t_;
  8319. };
  8320. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  8321. auto res = cli_.Get("/hi");
  8322. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8323. EXPECT_EQ(StatusCode::OK_200, res->status);
  8324. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8325. EXPECT_EQ("Hello World!", res->body);
  8326. }
  8327. class ServerUpDownTest : public ::testing::Test {
  8328. protected:
  8329. ServerUpDownTest() : cli_(HOST, PORT) {}
  8330. virtual void SetUp() {
  8331. t_ = thread([&]() {
  8332. svr_.bind_to_any_port(HOST);
  8333. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  8334. ASSERT_TRUE(svr_.listen_after_bind());
  8335. });
  8336. svr_.wait_until_ready();
  8337. }
  8338. virtual void TearDown() {
  8339. svr_.stop();
  8340. t_.join();
  8341. }
  8342. Client cli_;
  8343. Server svr_;
  8344. thread t_;
  8345. };
  8346. TEST_F(ServerUpDownTest, QuickStartStop) {
  8347. // Should not crash, especially when run with
  8348. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  8349. }
  8350. class PayloadMaxLengthTest : public ::testing::Test {
  8351. protected:
  8352. PayloadMaxLengthTest()
  8353. : cli_(HOST, PORT)
  8354. #ifdef CPPHTTPLIB_SSL_ENABLED
  8355. ,
  8356. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  8357. #endif
  8358. {
  8359. #ifdef CPPHTTPLIB_SSL_ENABLED
  8360. cli_.enable_server_certificate_verification(false);
  8361. #endif
  8362. }
  8363. virtual void SetUp() {
  8364. svr_.set_payload_max_length(8);
  8365. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  8366. res.set_content("test", "text/plain");
  8367. });
  8368. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  8369. svr_.wait_until_ready();
  8370. }
  8371. virtual void TearDown() {
  8372. svr_.stop();
  8373. t_.join();
  8374. }
  8375. #ifdef CPPHTTPLIB_SSL_ENABLED
  8376. SSLClient cli_;
  8377. SSLServer svr_;
  8378. #else
  8379. Client cli_;
  8380. Server svr_;
  8381. #endif
  8382. thread t_;
  8383. };
  8384. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  8385. auto res = cli_.Post("/test", "123456789", "text/plain");
  8386. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8387. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8388. res = cli_.Post("/test", "12345678", "text/plain");
  8389. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8390. EXPECT_EQ(StatusCode::OK_200, res->status);
  8391. }
  8392. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  8393. // Test chunked encoding with payload exceeding the 8-byte limit
  8394. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  8395. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  8396. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8397. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8398. }
  8399. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  8400. // Test chunked encoding with payload within the 8-byte limit
  8401. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  8402. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  8403. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8404. EXPECT_EQ(StatusCode::OK_200, res->status);
  8405. }
  8406. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  8407. // Test using send_request to send chunked data exceeding payload limit
  8408. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  8409. "Host: " +
  8410. std::string(HOST) + ":" + std::to_string(PORT) +
  8411. "\r\n"
  8412. "Transfer-Encoding: chunked\r\n"
  8413. "Connection: close\r\n"
  8414. "\r\n"
  8415. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  8416. "0123456789\r\n"
  8417. "0\r\n" // End chunk
  8418. "\r\n";
  8419. std::string response;
  8420. bool result = send_request(1, chunked_request, &response);
  8421. if (!result) {
  8422. // If send_request fails, it might be because the server closed the
  8423. // connection due to payload limit enforcement, which is acceptable
  8424. SUCCEED()
  8425. << "Server rejected oversized chunked request (connection closed)";
  8426. } else {
  8427. // If we got a response, check if it's an error response or connection was
  8428. // closed early Short response length indicates connection was closed due to
  8429. // payload limit
  8430. if (response.length() <= 10) {
  8431. SUCCEED() << "Server closed connection for oversized chunked request";
  8432. } else {
  8433. // Check for error status codes
  8434. EXPECT_TRUE(response.find("413") != std::string::npos ||
  8435. response.find("Payload Too Large") != std::string::npos ||
  8436. response.find("400") != std::string::npos);
  8437. }
  8438. }
  8439. }
  8440. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  8441. // Test request without Content-Length header exceeding payload limit
  8442. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8443. "Host: " +
  8444. std::string(HOST) + ":" +
  8445. std::to_string(PORT) +
  8446. "\r\n"
  8447. "Connection: close\r\n"
  8448. "\r\n";
  8449. // Add payload exceeding the 8-byte limit
  8450. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  8451. request_without_content_length += large_payload;
  8452. std::string response;
  8453. bool result = send_request(1, request_without_content_length, &response);
  8454. if (!result) {
  8455. // If send_request fails, server likely closed connection due to payload
  8456. // limit
  8457. SUCCEED() << "Server rejected oversized request without Content-Length "
  8458. "(connection closed)";
  8459. } else {
  8460. // Check if server responded with error or closed connection early
  8461. if (response.length() <= 10) {
  8462. SUCCEED() << "Server closed connection for oversized request without "
  8463. "Content-Length";
  8464. } else {
  8465. // Check for error status codes
  8466. EXPECT_TRUE(response.find("413") != std::string::npos ||
  8467. response.find("Payload Too Large") != std::string::npos ||
  8468. response.find("400") != std::string::npos);
  8469. }
  8470. }
  8471. }
  8472. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  8473. // Test request without Content-Length header within payload limit
  8474. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8475. "Host: " +
  8476. std::string(HOST) + ":" +
  8477. std::to_string(PORT) +
  8478. "\r\n"
  8479. "Connection: close\r\n"
  8480. "\r\n";
  8481. // Add payload within the 8-byte limit
  8482. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  8483. request_without_content_length += small_payload;
  8484. std::string response;
  8485. bool result = send_request(1, request_without_content_length, &response);
  8486. // For requests without Content-Length, the server may have different behavior
  8487. // The key is that it should not reject due to payload limit for small
  8488. // payloads
  8489. if (result) {
  8490. // Check for any HTTP response (success or error, but not connection closed)
  8491. if (response.length() > 10) {
  8492. SUCCEED()
  8493. << "Server processed request without Content-Length within limit";
  8494. } else {
  8495. // Short response might indicate connection closed, which is acceptable
  8496. SUCCEED() << "Server closed connection for request without "
  8497. "Content-Length (acceptable behavior)";
  8498. }
  8499. } else {
  8500. // Connection failure might be due to protocol requirements
  8501. SUCCEED() << "Connection issue with request without Content-Length "
  8502. "(environment-specific)";
  8503. }
  8504. }
  8505. class LargePayloadMaxLengthTest : public ::testing::Test {
  8506. protected:
  8507. LargePayloadMaxLengthTest()
  8508. : cli_(HOST, PORT)
  8509. #ifdef CPPHTTPLIB_SSL_ENABLED
  8510. ,
  8511. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  8512. #endif
  8513. {
  8514. #ifdef CPPHTTPLIB_SSL_ENABLED
  8515. cli_.enable_server_certificate_verification(false);
  8516. #endif
  8517. }
  8518. virtual void SetUp() {
  8519. // Set 10MB payload limit
  8520. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  8521. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  8522. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  8523. res.set_content("Large payload test", "text/plain");
  8524. });
  8525. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  8526. svr_.wait_until_ready();
  8527. }
  8528. virtual void TearDown() {
  8529. svr_.stop();
  8530. t_.join();
  8531. }
  8532. #ifdef CPPHTTPLIB_SSL_ENABLED
  8533. SSLClient cli_;
  8534. SSLServer svr_;
  8535. #else
  8536. Client cli_;
  8537. Server svr_;
  8538. #endif
  8539. thread t_;
  8540. };
  8541. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  8542. // Test chunked encoding with payload within 10MB limit
  8543. std::string medium_payload(5 * 1024 * 1024,
  8544. 'A'); // 5MB payload, within 10MB limit
  8545. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  8546. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8547. EXPECT_EQ(StatusCode::OK_200, res->status);
  8548. }
  8549. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  8550. // Test chunked encoding with payload exceeding 10MB limit
  8551. std::string large_payload(12 * 1024 * 1024,
  8552. 'B'); // 12MB payload, exceeds 10MB limit
  8553. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  8554. // Server may either return 413 or close the connection
  8555. if (res) {
  8556. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8557. } else {
  8558. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  8559. }
  8560. }
  8561. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  8562. // Test request without Content-Length header within 10MB limit
  8563. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8564. "Host: " +
  8565. std::string(HOST) + ":" +
  8566. std::to_string(PORT) +
  8567. "\r\n"
  8568. "Connection: close\r\n"
  8569. "\r\n";
  8570. // Add 1MB payload (within 10MB limit)
  8571. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  8572. request_without_content_length += medium_payload;
  8573. std::string response;
  8574. bool result = send_request(5, request_without_content_length, &response);
  8575. if (result) {
  8576. // Should get a proper HTTP response for payloads within limit
  8577. if (response.length() > 10) {
  8578. SUCCEED() << "Server processed 1MB request without Content-Length within "
  8579. "10MB limit";
  8580. } else {
  8581. SUCCEED() << "Server closed connection (acceptable behavior for no "
  8582. "Content-Length)";
  8583. }
  8584. } else {
  8585. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  8586. }
  8587. }
  8588. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  8589. // Test request without Content-Length header exceeding 10MB limit
  8590. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8591. "Host: " +
  8592. std::string(HOST) + ":" +
  8593. std::to_string(PORT) +
  8594. "\r\n"
  8595. "Connection: close\r\n"
  8596. "\r\n";
  8597. // Add 12MB payload (exceeds 10MB limit)
  8598. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  8599. request_without_content_length += large_payload;
  8600. std::string response;
  8601. bool result = send_request(10, request_without_content_length, &response);
  8602. if (!result) {
  8603. // Server should close connection due to payload limit
  8604. SUCCEED() << "Server rejected 12MB request without Content-Length "
  8605. "(connection closed)";
  8606. } else {
  8607. // Check for error response
  8608. if (response.length() <= 10) {
  8609. SUCCEED()
  8610. << "Server closed connection for 12MB request exceeding 10MB limit";
  8611. } else {
  8612. EXPECT_TRUE(response.find("413") != std::string::npos ||
  8613. response.find("Payload Too Large") != std::string::npos ||
  8614. response.find("400") != std::string::npos);
  8615. }
  8616. }
  8617. }
  8618. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8619. // `payload_max_length` is not enforced on decompressed body in ContentReader
  8620. // path.
  8621. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  8622. Server svr;
  8623. const size_t LIMIT = 64 * 1024; // 64KB
  8624. svr.set_payload_max_length(LIMIT);
  8625. size_t total = 0;
  8626. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  8627. const ContentReader &content_reader) {
  8628. content_reader([&](const char * /*data*/, size_t len) {
  8629. total += len;
  8630. return true;
  8631. });
  8632. res.status = 200;
  8633. res.set_content("stream_ok", "text/plain");
  8634. });
  8635. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8636. auto se = detail::scope_exit([&] {
  8637. svr.stop();
  8638. thread.join();
  8639. ASSERT_FALSE(svr.is_running());
  8640. });
  8641. svr.wait_until_ready();
  8642. // Prepare 256KB raw data and gzip-compress it
  8643. std::string raw(256 * 1024, 'A');
  8644. std::string gz;
  8645. {
  8646. z_stream zs{};
  8647. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  8648. Z_DEFAULT_STRATEGY);
  8649. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  8650. zs.avail_in = static_cast<uInt>(raw.size());
  8651. char outbuf[4096];
  8652. int ret;
  8653. do {
  8654. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  8655. zs.avail_out = sizeof(outbuf);
  8656. ret = deflate(&zs, Z_FINISH);
  8657. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  8658. } while (ret != Z_STREAM_END);
  8659. deflateEnd(&zs);
  8660. }
  8661. Client cli(HOST, PORT);
  8662. cli.set_connection_timeout(std::chrono::seconds(5));
  8663. Headers headers = {{"Content-Encoding", "gzip"}};
  8664. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  8665. "application/octet-stream");
  8666. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8667. // Server must reject oversized decompressed payloads with 413.
  8668. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8669. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  8670. EXPECT_LE(total, LIMIT);
  8671. }
  8672. #endif
  8673. // Regression test for DoS vulnerability: a malicious server sending a response
  8674. // without Content-Length header must not cause unbounded memory consumption on
  8675. // the client side. The client should stop reading after a reasonable limit,
  8676. // similar to the server-side set_payload_max_length protection.
  8677. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  8678. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  8679. #ifndef _WIN32
  8680. signal(SIGPIPE, SIG_IGN);
  8681. #endif
  8682. auto server_thread = std::thread([] {
  8683. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  8684. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8685. default_socket_options(srv);
  8686. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8687. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8688. sockaddr_in addr{};
  8689. addr.sin_family = AF_INET;
  8690. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8691. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8692. int opt = 1;
  8693. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8694. #ifdef _WIN32
  8695. reinterpret_cast<const char *>(&opt),
  8696. #else
  8697. &opt,
  8698. #endif
  8699. sizeof(opt));
  8700. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8701. ::listen(srv, 1);
  8702. sockaddr_in cli_addr{};
  8703. socklen_t cli_len = sizeof(cli_addr);
  8704. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8705. if (cli != INVALID_SOCKET) {
  8706. char buf[4096];
  8707. ::recv(cli, buf, sizeof(buf), 0);
  8708. // Malicious response: no Content-Length, no chunked encoding
  8709. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8710. "Connection: close\r\n"
  8711. "\r\n";
  8712. ::send(cli,
  8713. #ifdef _WIN32
  8714. static_cast<const char *>(response_header.c_str()),
  8715. static_cast<int>(response_header.size()),
  8716. #else
  8717. response_header.c_str(), response_header.size(),
  8718. #endif
  8719. 0);
  8720. // Send 10MB of data
  8721. std::string chunk(64 * 1024, 'A');
  8722. size_t total_sent = 0;
  8723. while (total_sent < MALICIOUS_DATA_SIZE) {
  8724. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  8725. auto sent = ::send(cli,
  8726. #ifdef _WIN32
  8727. static_cast<const char *>(chunk.c_str()),
  8728. static_cast<int>(to_send),
  8729. #else
  8730. chunk.c_str(), to_send,
  8731. #endif
  8732. 0);
  8733. if (sent <= 0) break;
  8734. total_sent += static_cast<size_t>(sent);
  8735. }
  8736. detail::close_socket(cli);
  8737. }
  8738. detail::close_socket(srv);
  8739. });
  8740. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8741. size_t total_read = 0;
  8742. {
  8743. Client cli("127.0.0.1", PORT + 2);
  8744. cli.set_read_timeout(5, 0);
  8745. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  8746. auto stream = cli.open_stream("GET", "/malicious");
  8747. ASSERT_TRUE(stream.is_valid());
  8748. char buffer[64 * 1024];
  8749. ssize_t n;
  8750. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  8751. total_read += static_cast<size_t>(n);
  8752. }
  8753. } // StreamHandle and Client destroyed here, closing the socket
  8754. server_thread.join();
  8755. // With set_payload_max_length, the client must stop reading before consuming
  8756. // all 10MB. The read loop should be cut off at or near the configured limit.
  8757. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  8758. << "Client read " << total_read << " bytes, exceeding the configured "
  8759. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  8760. }
  8761. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  8762. // the entire response body without truncation.
  8763. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  8764. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  8765. #ifndef _WIN32
  8766. signal(SIGPIPE, SIG_IGN);
  8767. #endif
  8768. auto server_thread = std::thread([] {
  8769. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8770. default_socket_options(srv);
  8771. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8772. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8773. sockaddr_in addr{};
  8774. addr.sin_family = AF_INET;
  8775. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8776. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8777. int opt = 1;
  8778. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8779. #ifdef _WIN32
  8780. reinterpret_cast<const char *>(&opt),
  8781. #else
  8782. &opt,
  8783. #endif
  8784. sizeof(opt));
  8785. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8786. ::listen(srv, 1);
  8787. sockaddr_in cli_addr{};
  8788. socklen_t cli_len = sizeof(cli_addr);
  8789. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8790. if (cli != INVALID_SOCKET) {
  8791. char buf[4096];
  8792. ::recv(cli, buf, sizeof(buf), 0);
  8793. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8794. "Connection: close\r\n"
  8795. "\r\n";
  8796. ::send(cli,
  8797. #ifdef _WIN32
  8798. static_cast<const char *>(response_header.c_str()),
  8799. static_cast<int>(response_header.size()),
  8800. #else
  8801. response_header.c_str(), response_header.size(),
  8802. #endif
  8803. 0);
  8804. std::string chunk(64 * 1024, 'A');
  8805. size_t total_sent = 0;
  8806. while (total_sent < DATA_SIZE) {
  8807. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8808. auto sent = ::send(cli,
  8809. #ifdef _WIN32
  8810. static_cast<const char *>(chunk.c_str()),
  8811. static_cast<int>(to_send),
  8812. #else
  8813. chunk.c_str(), to_send,
  8814. #endif
  8815. 0);
  8816. if (sent <= 0) break;
  8817. total_sent += static_cast<size_t>(sent);
  8818. }
  8819. #ifdef _WIN32
  8820. ::shutdown(cli, SD_SEND);
  8821. #else
  8822. ::shutdown(cli, SHUT_WR);
  8823. #endif
  8824. // Drain until the client closes its end, ensuring all data is delivered
  8825. char drain[1024];
  8826. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  8827. detail::close_socket(cli);
  8828. }
  8829. detail::close_socket(srv);
  8830. });
  8831. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8832. size_t total_read = 0;
  8833. {
  8834. Client cli("127.0.0.1", PORT + 2);
  8835. cli.set_read_timeout(5, 0);
  8836. cli.set_payload_max_length(0); // 0 means no limit
  8837. auto stream = cli.open_stream("GET", "/data");
  8838. ASSERT_TRUE(stream.is_valid());
  8839. char buffer[64 * 1024];
  8840. ssize_t n;
  8841. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  8842. total_read += static_cast<size_t>(n);
  8843. }
  8844. }
  8845. server_thread.join();
  8846. EXPECT_EQ(total_read, DATA_SIZE)
  8847. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  8848. << " bytes without truncation, but only read " << total_read << " bytes.";
  8849. }
  8850. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  8851. // enormous Content-Length must not cause the client to pre-allocate a huge
  8852. // response body buffer. The reservation is capped at payload_max_length_, and
  8853. // the read itself fails when the body exceeds the limit.
  8854. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  8855. #ifndef _WIN32
  8856. signal(SIGPIPE, SIG_IGN);
  8857. #endif
  8858. auto server_thread = std::thread([] {
  8859. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8860. default_socket_options(srv);
  8861. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8862. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8863. sockaddr_in addr{};
  8864. addr.sin_family = AF_INET;
  8865. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8866. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8867. int opt = 1;
  8868. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8869. #ifdef _WIN32
  8870. reinterpret_cast<const char *>(&opt),
  8871. #else
  8872. &opt,
  8873. #endif
  8874. sizeof(opt));
  8875. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8876. ::listen(srv, 1);
  8877. sockaddr_in cli_addr{};
  8878. socklen_t cli_len = sizeof(cli_addr);
  8879. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8880. if (cli != INVALID_SOCKET) {
  8881. char buf[4096];
  8882. ::recv(cli, buf, sizeof(buf), 0);
  8883. // Malicious response: claim a 20GB body but send only a tiny payload.
  8884. std::string response = "HTTP/1.1 200 OK\r\n"
  8885. "Content-Length: 20000000000\r\n"
  8886. "\r\n"
  8887. "abc";
  8888. ::send(cli,
  8889. #ifdef _WIN32
  8890. static_cast<const char *>(response.c_str()),
  8891. static_cast<int>(response.size()),
  8892. #else
  8893. response.c_str(), response.size(),
  8894. #endif
  8895. 0);
  8896. detail::close_socket(cli);
  8897. }
  8898. detail::close_socket(srv);
  8899. });
  8900. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8901. {
  8902. Client cli("127.0.0.1", PORT + 2);
  8903. cli.set_read_timeout(5, 0);
  8904. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  8905. // result in a 20GB pre-allocation. The Get() call is expected to fail
  8906. // (server claims more bytes than payload_max_length permits), but it must
  8907. // not exhaust memory before getting there.
  8908. auto res = cli.Get("/malicious");
  8909. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  8910. }
  8911. server_thread.join();
  8912. }
  8913. // Verify that content_receiver bypasses the default payload_max_length,
  8914. // allowing streaming downloads larger than 100MB without requiring an explicit
  8915. // set_payload_max_length call.
  8916. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  8917. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  8918. #ifndef _WIN32
  8919. signal(SIGPIPE, SIG_IGN);
  8920. #endif
  8921. auto server_thread = std::thread([] {
  8922. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8923. default_socket_options(srv);
  8924. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8925. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8926. sockaddr_in addr{};
  8927. addr.sin_family = AF_INET;
  8928. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8929. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8930. int opt = 1;
  8931. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8932. #ifdef _WIN32
  8933. reinterpret_cast<const char *>(&opt),
  8934. #else
  8935. &opt,
  8936. #endif
  8937. sizeof(opt));
  8938. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8939. ::listen(srv, 1);
  8940. sockaddr_in cli_addr{};
  8941. socklen_t cli_len = sizeof(cli_addr);
  8942. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8943. if (cli != INVALID_SOCKET) {
  8944. char buf[4096];
  8945. ::recv(cli, buf, sizeof(buf), 0);
  8946. // Response with Content-Length larger than default 100MB limit
  8947. auto content_length = std::to_string(DATA_SIZE);
  8948. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8949. "Content-Length: " +
  8950. content_length +
  8951. "\r\n"
  8952. "Connection: close\r\n"
  8953. "\r\n";
  8954. ::send(cli,
  8955. #ifdef _WIN32
  8956. static_cast<const char *>(response_header.c_str()),
  8957. static_cast<int>(response_header.size()),
  8958. #else
  8959. response_header.c_str(), response_header.size(),
  8960. #endif
  8961. 0);
  8962. std::string chunk(64 * 1024, 'A');
  8963. size_t total_sent = 0;
  8964. while (total_sent < DATA_SIZE) {
  8965. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8966. auto sent = ::send(cli,
  8967. #ifdef _WIN32
  8968. static_cast<const char *>(chunk.c_str()),
  8969. static_cast<int>(to_send),
  8970. #else
  8971. chunk.c_str(), to_send,
  8972. #endif
  8973. 0);
  8974. if (sent <= 0) break;
  8975. total_sent += static_cast<size_t>(sent);
  8976. }
  8977. detail::close_socket(cli);
  8978. }
  8979. detail::close_socket(srv);
  8980. });
  8981. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8982. size_t total_received = 0;
  8983. {
  8984. Client cli("127.0.0.1", PORT + 2);
  8985. cli.set_read_timeout(10, 0);
  8986. // Do NOT call set_payload_max_length — use the default 100MB limit
  8987. auto res =
  8988. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  8989. total_received += data_length;
  8990. return true;
  8991. });
  8992. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8993. EXPECT_EQ(StatusCode::OK_200, res->status);
  8994. }
  8995. server_thread.join();
  8996. EXPECT_EQ(total_received, DATA_SIZE)
  8997. << "With content_receiver, the client should read all " << DATA_SIZE
  8998. << " bytes despite the default 100MB payload_max_length, but only read "
  8999. << total_received << " bytes.";
  9000. }
  9001. // Verify that an explicit set_payload_max_length smaller than the response is
  9002. // enforced even when a content_receiver is used.
  9003. TEST(ClientVulnerabilityTest,
  9004. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  9005. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  9006. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  9007. #ifndef _WIN32
  9008. signal(SIGPIPE, SIG_IGN);
  9009. #endif
  9010. auto server_thread = std::thread([] {
  9011. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9012. default_socket_options(srv);
  9013. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9014. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9015. sockaddr_in addr{};
  9016. addr.sin_family = AF_INET;
  9017. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9018. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9019. int opt = 1;
  9020. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9021. #ifdef _WIN32
  9022. reinterpret_cast<const char *>(&opt),
  9023. #else
  9024. &opt,
  9025. #endif
  9026. sizeof(opt));
  9027. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9028. ::listen(srv, 1);
  9029. sockaddr_in cli_addr{};
  9030. socklen_t cli_len = sizeof(cli_addr);
  9031. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9032. if (cli != INVALID_SOCKET) {
  9033. char buf[4096];
  9034. ::recv(cli, buf, sizeof(buf), 0);
  9035. auto content_length = std::to_string(DATA_SIZE);
  9036. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9037. "Content-Length: " +
  9038. content_length +
  9039. "\r\n"
  9040. "Connection: close\r\n"
  9041. "\r\n";
  9042. ::send(cli,
  9043. #ifdef _WIN32
  9044. static_cast<const char *>(response_header.c_str()),
  9045. static_cast<int>(response_header.size()),
  9046. #else
  9047. response_header.c_str(), response_header.size(),
  9048. #endif
  9049. 0);
  9050. std::string chunk(64 * 1024, 'A');
  9051. size_t total_sent = 0;
  9052. while (total_sent < DATA_SIZE) {
  9053. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  9054. auto sent = ::send(cli,
  9055. #ifdef _WIN32
  9056. static_cast<const char *>(chunk.c_str()),
  9057. static_cast<int>(to_send),
  9058. #else
  9059. chunk.c_str(), to_send,
  9060. #endif
  9061. 0);
  9062. if (sent <= 0) break;
  9063. total_sent += static_cast<size_t>(sent);
  9064. }
  9065. detail::close_socket(cli);
  9066. }
  9067. detail::close_socket(srv);
  9068. });
  9069. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9070. size_t total_received = 0;
  9071. {
  9072. Client cli("127.0.0.1", PORT + 2);
  9073. cli.set_read_timeout(10, 0);
  9074. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  9075. auto res =
  9076. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  9077. total_received += data_length;
  9078. return true;
  9079. });
  9080. // Should fail because 200MB exceeds the explicit 150MB limit
  9081. EXPECT_FALSE(res);
  9082. }
  9083. server_thread.join();
  9084. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  9085. << "Client with content_receiver should respect the explicit "
  9086. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  9087. << total_received << " bytes.";
  9088. }
  9089. // Verify that an explicit set_payload_max_length larger than the response
  9090. // allows the content_receiver to read all data successfully.
  9091. TEST(ClientVulnerabilityTest,
  9092. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  9093. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  9094. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  9095. #ifndef _WIN32
  9096. signal(SIGPIPE, SIG_IGN);
  9097. #endif
  9098. auto server_thread = std::thread([] {
  9099. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9100. default_socket_options(srv);
  9101. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9102. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9103. sockaddr_in addr{};
  9104. addr.sin_family = AF_INET;
  9105. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9106. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9107. int opt = 1;
  9108. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9109. #ifdef _WIN32
  9110. reinterpret_cast<const char *>(&opt),
  9111. #else
  9112. &opt,
  9113. #endif
  9114. sizeof(opt));
  9115. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9116. ::listen(srv, 1);
  9117. sockaddr_in cli_addr{};
  9118. socklen_t cli_len = sizeof(cli_addr);
  9119. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9120. if (cli != INVALID_SOCKET) {
  9121. char buf[4096];
  9122. ::recv(cli, buf, sizeof(buf), 0);
  9123. auto content_length = std::to_string(DATA_SIZE);
  9124. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9125. "Content-Length: " +
  9126. content_length +
  9127. "\r\n"
  9128. "Connection: close\r\n"
  9129. "\r\n";
  9130. ::send(cli,
  9131. #ifdef _WIN32
  9132. static_cast<const char *>(response_header.c_str()),
  9133. static_cast<int>(response_header.size()),
  9134. #else
  9135. response_header.c_str(), response_header.size(),
  9136. #endif
  9137. 0);
  9138. std::string chunk(64 * 1024, 'A');
  9139. size_t total_sent = 0;
  9140. while (total_sent < DATA_SIZE) {
  9141. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  9142. auto sent = ::send(cli,
  9143. #ifdef _WIN32
  9144. static_cast<const char *>(chunk.c_str()),
  9145. static_cast<int>(to_send),
  9146. #else
  9147. chunk.c_str(), to_send,
  9148. #endif
  9149. 0);
  9150. if (sent <= 0) break;
  9151. total_sent += static_cast<size_t>(sent);
  9152. }
  9153. #ifdef _WIN32
  9154. ::shutdown(cli, SD_SEND);
  9155. #else
  9156. ::shutdown(cli, SHUT_WR);
  9157. #endif
  9158. char drain[1024];
  9159. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  9160. detail::close_socket(cli);
  9161. }
  9162. detail::close_socket(srv);
  9163. });
  9164. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9165. size_t total_received = 0;
  9166. {
  9167. Client cli("127.0.0.1", PORT + 2);
  9168. cli.set_read_timeout(10, 0);
  9169. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  9170. auto res =
  9171. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  9172. total_received += data_length;
  9173. return true;
  9174. });
  9175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9176. EXPECT_EQ(StatusCode::OK_200, res->status);
  9177. }
  9178. server_thread.join();
  9179. EXPECT_EQ(total_received, DATA_SIZE)
  9180. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  9181. << " bytes (larger than " << DATA_SIZE
  9182. << " bytes response), content_receiver should read all data, but only "
  9183. "read "
  9184. << total_received << " bytes.";
  9185. }
  9186. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  9187. // Regression test for "zip bomb" attack on the client side: a malicious server
  9188. // sends a small gzip-compressed response that decompresses to a huge payload.
  9189. // The client must enforce payload_max_length on the decompressed size.
  9190. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  9191. constexpr size_t DECOMPRESSED_SIZE =
  9192. 10 * 1024 * 1024; // 10MB after decompression
  9193. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  9194. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  9195. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  9196. std::string compressed;
  9197. {
  9198. httplib::detail::gzip_compressor compressor;
  9199. bool ok =
  9200. compressor.compress(uncompressed.data(), uncompressed.size(),
  9201. /*last=*/true, [&](const char *buf, size_t len) {
  9202. compressed.append(buf, len);
  9203. return true;
  9204. });
  9205. ASSERT_TRUE(ok);
  9206. }
  9207. // Sanity: compressed data should be much smaller than the decompressed size
  9208. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  9209. #ifndef _WIN32
  9210. signal(SIGPIPE, SIG_IGN);
  9211. #endif
  9212. // Set up the listening socket in the main thread so the server is guaranteed
  9213. // to be ready before the client connects (eliminates race condition).
  9214. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9215. default_socket_options(srv);
  9216. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9217. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9218. sockaddr_in addr{};
  9219. addr.sin_family = AF_INET;
  9220. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  9221. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9222. int opt = 1;
  9223. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9224. #ifdef _WIN32
  9225. reinterpret_cast<const char *>(&opt),
  9226. #else
  9227. &opt,
  9228. #endif
  9229. sizeof(opt));
  9230. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  9231. ASSERT_EQ(0, ::listen(srv, 1));
  9232. auto server_thread = std::thread([&compressed, srv] {
  9233. sockaddr_in cli_addr{};
  9234. socklen_t cli_len = sizeof(cli_addr);
  9235. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9236. if (cli != INVALID_SOCKET) {
  9237. // Read the full HTTP request (until \r\n\r\n)
  9238. char buf[4096];
  9239. size_t total = 0;
  9240. while (total < sizeof(buf)) {
  9241. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  9242. if (n <= 0) break;
  9243. total += static_cast<size_t>(n);
  9244. // Check for end of headers
  9245. if (total >= 4) {
  9246. std::string req(buf, total);
  9247. if (req.find("\r\n\r\n") != std::string::npos) break;
  9248. }
  9249. }
  9250. // Malicious response: gzip-compressed body, no Content-Length
  9251. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9252. "Content-Encoding: gzip\r\n"
  9253. "Connection: close\r\n"
  9254. "\r\n";
  9255. ::send(cli,
  9256. #ifdef _WIN32
  9257. static_cast<const char *>(response_header.c_str()),
  9258. static_cast<int>(response_header.size()),
  9259. #else
  9260. response_header.c_str(), response_header.size(),
  9261. #endif
  9262. 0);
  9263. // Send the compressed payload (small on the wire, huge when decompressed)
  9264. size_t total_sent = 0;
  9265. while (total_sent < compressed.size()) {
  9266. auto to_send = std::min(compressed.size() - total_sent,
  9267. static_cast<size_t>(64 * 1024));
  9268. auto sent =
  9269. ::send(cli,
  9270. #ifdef _WIN32
  9271. static_cast<const char *>(compressed.c_str() + total_sent),
  9272. static_cast<int>(to_send),
  9273. #else
  9274. compressed.c_str() + total_sent, to_send,
  9275. #endif
  9276. 0);
  9277. if (sent <= 0) break;
  9278. total_sent += static_cast<size_t>(sent);
  9279. }
  9280. detail::close_socket(cli);
  9281. }
  9282. });
  9283. auto se = detail::scope_exit([&] {
  9284. detail::close_socket(srv);
  9285. server_thread.join();
  9286. });
  9287. size_t total_decompressed = 0;
  9288. {
  9289. Client cli("127.0.0.1", PORT + 3);
  9290. cli.set_read_timeout(5, 0);
  9291. cli.set_decompress(true);
  9292. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  9293. auto stream = cli.open_stream("GET", "/zipbomb");
  9294. ASSERT_TRUE(stream.is_valid());
  9295. char buffer[64 * 1024];
  9296. ssize_t n;
  9297. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  9298. total_decompressed += static_cast<size_t>(n);
  9299. }
  9300. }
  9301. // The decompressed size must be capped by payload_max_length. Without
  9302. // protection, the client would decompress the full 10MB from a tiny
  9303. // compressed payload, enabling a zip bomb DoS attack.
  9304. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  9305. << "Client decompressed " << total_decompressed
  9306. << " bytes from a gzip response. The decompressed size should be "
  9307. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  9308. }
  9309. #endif
  9310. TEST(HostAndPortPropertiesTest, NoSSL) {
  9311. httplib::Client cli("www.google.com", 1234);
  9312. ASSERT_EQ("www.google.com", cli.host());
  9313. ASSERT_EQ(1234, cli.port());
  9314. }
  9315. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  9316. httplib::Client cli("www.google.com:1234");
  9317. ASSERT_EQ("www.google.com", cli.host());
  9318. ASSERT_EQ(1234, cli.port());
  9319. }
  9320. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  9321. // Port number that overflows int — should not crash, client becomes invalid
  9322. httplib::Client cli("http://www.google.com:99999999999999999999");
  9323. ASSERT_FALSE(cli.is_valid());
  9324. }
  9325. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  9326. // Port 99999 exceeds valid range (1-65535) — should not crash
  9327. httplib::Client cli("http://www.google.com:99999");
  9328. ASSERT_FALSE(cli.is_valid());
  9329. }
  9330. #ifdef CPPHTTPLIB_SSL_ENABLED
  9331. TEST(HostAndPortPropertiesTest, SSL) {
  9332. httplib::SSLClient cli("www.google.com");
  9333. ASSERT_EQ("www.google.com", cli.host());
  9334. ASSERT_EQ(443, cli.port());
  9335. }
  9336. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  9337. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  9338. std::string cert;
  9339. read_file(CA_CERT_FILE, cert);
  9340. httplib::SSLClient httplib_client("www.google.com");
  9341. // Load CA store first time
  9342. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  9343. // Load CA store second time (update)
  9344. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  9345. // Verify client is still valid and can make connections
  9346. httplib_client.enable_server_certificate_verification(true);
  9347. auto res = httplib_client.Get("/");
  9348. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9349. // Google may return 200 or 301 depending on various factors
  9350. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  9351. res->status == StatusCode::MovedPermanently_301);
  9352. }
  9353. TEST(SSLClientTest, ServerNameIndication_Online) {
  9354. auto host = "httpbingo.org";
  9355. auto path = std::string{"/get"};
  9356. SSLClient cli(host, 443);
  9357. auto res = cli.Get(path);
  9358. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9359. ASSERT_EQ(StatusCode::OK_200, res->status);
  9360. }
  9361. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  9362. // Use a site that will cause SSL verification failure due to self-signed cert
  9363. SSLClient cli("self-signed.badssl.com", 443);
  9364. cli.enable_server_certificate_verification(true);
  9365. auto res = cli.Get("/");
  9366. ASSERT_TRUE(!res);
  9367. EXPECT_EQ(Error::SSLServerVerification, res.error());
  9368. // Verify backend error is captured for SSLServerVerification
  9369. // This occurs when certificate verification fails
  9370. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  9371. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  9372. EXPECT_NE(0UL, res.ssl_backend_error());
  9373. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9374. // For OpenSSL, ssl_error is 0 for verification errors
  9375. EXPECT_EQ(0, res.ssl_error());
  9376. #if !defined(_WIN32) || \
  9377. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  9378. // On non-Windows or when Windows Schannel is disabled, the error comes
  9379. // from OpenSSL's verification
  9380. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  9381. res.ssl_backend_error());
  9382. #endif
  9383. #endif
  9384. }
  9385. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  9386. // Use a site where hostname doesn't match the certificate
  9387. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  9388. SSLClient cli("wrong.host.badssl.com", 443);
  9389. cli.enable_server_certificate_verification(true);
  9390. cli.enable_server_hostname_verification(true);
  9391. auto res = cli.Get("/");
  9392. ASSERT_TRUE(!res);
  9393. // The error type depends on when hostname verification occurs:
  9394. // - OpenSSL: SSLServerHostnameVerification (post-handshake verification)
  9395. // - Mbed TLS: SSLServerVerification (during handshake)
  9396. EXPECT_TRUE(res.error() == Error::SSLServerHostnameVerification ||
  9397. res.error() == Error::SSLServerVerification);
  9398. // Verify backend error is captured for hostname verification failure
  9399. EXPECT_NE(0UL, res.ssl_backend_error());
  9400. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9401. // For OpenSSL, ssl_error is 0 for verification errors
  9402. EXPECT_EQ(0, res.ssl_error());
  9403. #if !defined(_WIN32) || \
  9404. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  9405. // On non-Windows or when Windows Schannel is disabled, the error comes
  9406. // from OpenSSL's hostname verification
  9407. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  9408. res.ssl_backend_error());
  9409. #endif
  9410. #endif
  9411. }
  9412. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  9413. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  9414. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  9415. SSLClient cli("www.google.com", 443);
  9416. cli.enable_server_certificate_verification(true);
  9417. auto res = cli.Get("/");
  9418. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  9419. }
  9420. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  9421. SSLClient cli("www.google.com", 443);
  9422. cli.enable_server_certificate_verification(true);
  9423. cli.enable_windows_certificate_verification(false);
  9424. auto res = cli.Get("/");
  9425. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  9426. }
  9427. #endif
  9428. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  9429. Client cli("https://google.com");
  9430. auto res = cli.Get("/");
  9431. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9432. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9433. }
  9434. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  9435. SSLClient cli("google.com");
  9436. cli.set_ca_cert_path(CA_CERT_FILE);
  9437. auto res = cli.Get("/");
  9438. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9439. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9440. }
  9441. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  9442. SSLClient cli("google.com");
  9443. cli.enable_server_certificate_verification(true);
  9444. cli.set_ca_cert_path("hello");
  9445. auto res = cli.Get("/");
  9446. ASSERT_TRUE(!res);
  9447. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  9448. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  9449. // should be set
  9450. EXPECT_EQ(0, res.ssl_error());
  9451. // Verify backend error is captured for SSLLoadingCerts
  9452. // This error occurs when loading CA certificates fails
  9453. EXPECT_NE(0UL, res.ssl_backend_error());
  9454. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9455. // OpenSSL specific error codes:
  9456. // > openssl errstr 0x80000002
  9457. // error:80000002:system library::No such file or directory
  9458. // > openssl errstr 0xA000126
  9459. // error:0A000126:SSL routines::unexpected eof while reading
  9460. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  9461. res.ssl_backend_error() == 0xA000126);
  9462. #endif
  9463. }
  9464. TEST(SSLClientTest, ServerCertificateVerification4) {
  9465. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9466. ASSERT_TRUE(svr.is_valid());
  9467. svr.Get("/test", [&](const Request &, Response &res) {
  9468. res.set_content("test", "text/plain");
  9469. svr.stop();
  9470. ASSERT_TRUE(true);
  9471. });
  9472. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  9473. auto se = detail::scope_exit([&] {
  9474. t.join();
  9475. ASSERT_FALSE(svr.is_running());
  9476. });
  9477. svr.wait_until_ready();
  9478. SSLClient cli("127.0.0.1", PORT);
  9479. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  9480. cli.enable_server_certificate_verification(true);
  9481. cli.set_connection_timeout(30);
  9482. auto res = cli.Get("/test");
  9483. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9484. ASSERT_EQ(StatusCode::OK_200, res->status);
  9485. }
  9486. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  9487. std::string cert;
  9488. read_file(CA_CERT_FILE, cert);
  9489. SSLClient cli("google.com");
  9490. cli.load_ca_cert_store(cert.data(), cert.size());
  9491. const auto res = cli.Get("/");
  9492. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9493. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9494. }
  9495. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  9496. // clang-format off
  9497. static constexpr char cert[] =
  9498. "GlobalSign Root CA\n"
  9499. "==================\n"
  9500. "-----BEGIN CERTIFICATE-----\n"
  9501. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  9502. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  9503. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  9504. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  9505. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  9506. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  9507. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  9508. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  9509. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  9510. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  9511. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  9512. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  9513. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  9514. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  9515. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  9516. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  9517. "-----END CERTIFICATE-----\n";
  9518. // clang-format on
  9519. SSLClient cli("google.com");
  9520. cli.load_ca_cert_store(cert, sizeof(cert));
  9521. const auto res = cli.Get("/");
  9522. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9523. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9524. }
  9525. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  9526. SSLClient cli("www.youtube.com");
  9527. cli.set_ca_cert_path(CA_CERT_FILE);
  9528. cli.enable_server_certificate_verification(true);
  9529. cli.set_follow_location(true);
  9530. auto res = cli.Get("/");
  9531. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9532. ASSERT_EQ(StatusCode::OK_200, res->status);
  9533. }
  9534. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  9535. SSLClient cli("wWw.YouTube.Com");
  9536. cli.set_ca_cert_path(CA_CERT_FILE);
  9537. cli.enable_server_certificate_verification(true);
  9538. cli.enable_server_hostname_verification(true);
  9539. cli.set_follow_location(true);
  9540. auto res = cli.Get("/");
  9541. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9542. ASSERT_EQ(StatusCode::OK_200, res->status);
  9543. }
  9544. TEST(SSLClientTest, HostNameMatchCase_Online) {
  9545. SSLClient cli("gOoGlE.COm");
  9546. cli.enable_server_certificate_verification(true);
  9547. cli.enable_server_hostname_verification(true);
  9548. cli.set_follow_location(true);
  9549. auto res = cli.Get("/");
  9550. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9551. ASSERT_EQ(StatusCode::OK_200, res->status);
  9552. }
  9553. TEST(SSLClientTest, Issue2004_Online) {
  9554. Client client("https://google.com");
  9555. client.set_follow_location(true);
  9556. auto res = client.Get("/");
  9557. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9558. ASSERT_EQ(StatusCode::OK_200, res->status);
  9559. auto body = res->body;
  9560. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  9561. }
  9562. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  9563. // Create SSLClient with invalid cert/key to make is_valid() return false
  9564. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  9565. "nonexistent_key.pem");
  9566. // is_valid() should be false due to cert loading failure
  9567. ASSERT_FALSE(cli.is_valid());
  9568. auto res = cli.Get("/");
  9569. ASSERT_FALSE(res);
  9570. EXPECT_EQ(Error::SSLConnection, res.error());
  9571. }
  9572. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  9573. // Test for Issue #2251: SSL error not properly reported when client cert
  9574. // and key paths are swapped or mismatched
  9575. // This simulates the scenario where user accidentally swaps the cert and key
  9576. // files
  9577. // Using client cert file as private key and vice versa (completely wrong)
  9578. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  9579. // Should fail validation due to cert/key mismatch
  9580. ASSERT_FALSE(cli.is_valid());
  9581. // Attempt to make a request should fail with proper error
  9582. auto res = cli.Get("/");
  9583. ASSERT_FALSE(res);
  9584. EXPECT_EQ(Error::SSLConnection, res.error());
  9585. // SSL error should be recorded in the Result object (this is the key fix for
  9586. // Issue #2251)
  9587. auto backend_error = res.ssl_backend_error();
  9588. EXPECT_NE(0u, backend_error);
  9589. }
  9590. // Tests cert/key mismatch detection at the TLS context level
  9591. TEST(TlsApiTest, ClientCertKeyMismatch) {
  9592. // Test that using mismatched cert/key causes connection failure.
  9593. // We verify this at the SSLClient level rather than through internal
  9594. // TLS API functions.
  9595. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  9596. cli.enable_server_certificate_verification(false);
  9597. cli.set_connection_timeout(2);
  9598. // The mismatch should cause a connection or handshake error
  9599. auto res = cli.Get("/test");
  9600. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  9601. // Either way, the request should fail
  9602. EXPECT_FALSE(res);
  9603. }
  9604. #endif
  9605. #if 0
  9606. TEST(SSLClientTest, SetInterfaceWithINET6) {
  9607. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  9608. ASSERT_TRUE(cli != nullptr);
  9609. cli->set_address_family(AF_INET6);
  9610. cli->set_interface("en0");
  9611. auto res = cli->Get("/get");
  9612. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9613. ASSERT_EQ(StatusCode::OK_200, res->status);
  9614. }
  9615. #endif
  9616. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  9617. #ifdef CPPHTTPLIB_SSL_ENABLED
  9618. void ClientCertPresent(
  9619. const std::string &client_cert_file,
  9620. const std::string &client_private_key_file,
  9621. const std::string &client_encrypted_private_key_pass = std::string()) {
  9622. using namespace httplib::tls;
  9623. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  9624. CLIENT_CA_CERT_DIR);
  9625. ASSERT_TRUE(svr.is_valid());
  9626. svr.Get("/test", [&](const Request &req, Response &res) {
  9627. res.set_content("test", "text/plain");
  9628. auto cert = req.peer_cert();
  9629. ASSERT_TRUE(static_cast<bool>(cert));
  9630. std::string common_name = cert.subject_cn();
  9631. EXPECT_EQ("Common Name", common_name);
  9632. });
  9633. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9634. auto se = detail::scope_exit([&] {
  9635. svr.stop();
  9636. t.join();
  9637. ASSERT_FALSE(svr.is_running());
  9638. });
  9639. svr.wait_until_ready();
  9640. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  9641. client_encrypted_private_key_pass);
  9642. cli.enable_server_certificate_verification(false);
  9643. cli.set_connection_timeout(30);
  9644. auto res = cli.Get("/test");
  9645. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9646. ASSERT_EQ(StatusCode::OK_200, res->status);
  9647. }
  9648. TEST(SSLClientServerTest, ClientCertPresent) {
  9649. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9650. }
  9651. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  9652. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  9653. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  9654. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  9655. }
  9656. // PEM memory-based constructor tests (works with all TLS backends)
  9657. void PemMemoryClientCertPresent(
  9658. const std::string &client_cert_file,
  9659. const std::string &client_private_key_file,
  9660. const std::string &client_encrypted_private_key_pass = std::string()) {
  9661. // Read PEM files into memory
  9662. std::string server_cert_pem, server_key_pem;
  9663. std::string client_ca_pem;
  9664. std::string client_cert_pem, client_key_pem;
  9665. read_file(SERVER_CERT_FILE, server_cert_pem);
  9666. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  9667. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  9668. read_file(client_cert_file, client_cert_pem);
  9669. read_file(client_private_key_file, client_key_pem);
  9670. // Create server with PEM memory
  9671. SSLServer::PemMemory server_pem = {
  9672. server_cert_pem.c_str(),
  9673. server_cert_pem.size(),
  9674. server_key_pem.c_str(),
  9675. server_key_pem.size(),
  9676. client_ca_pem.c_str(),
  9677. client_ca_pem.size(),
  9678. nullptr // no password for server key
  9679. };
  9680. SSLServer svr(server_pem);
  9681. ASSERT_TRUE(svr.is_valid());
  9682. svr.Get("/test", [&](const Request &, Response &res) {
  9683. res.set_content("test", "text/plain");
  9684. });
  9685. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9686. auto se = detail::scope_exit([&] {
  9687. svr.stop();
  9688. t.join();
  9689. ASSERT_FALSE(svr.is_running());
  9690. });
  9691. svr.wait_until_ready();
  9692. // Create client with PEM memory
  9693. const char *password = client_encrypted_private_key_pass.empty()
  9694. ? nullptr
  9695. : client_encrypted_private_key_pass.c_str();
  9696. SSLClient::PemMemory client_pem = {
  9697. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  9698. client_key_pem.size(), password};
  9699. SSLClient cli(HOST, PORT, client_pem);
  9700. cli.enable_server_certificate_verification(false);
  9701. cli.set_connection_timeout(30);
  9702. auto res = cli.Get("/test");
  9703. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9704. ASSERT_EQ(StatusCode::OK_200, res->status);
  9705. }
  9706. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  9707. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9708. }
  9709. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  9710. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  9711. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  9712. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  9713. }
  9714. TEST(SSLClientServerTest, ClientCertMissing) {
  9715. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  9716. CLIENT_CA_CERT_DIR);
  9717. ASSERT_TRUE(svr.is_valid());
  9718. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  9719. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9720. auto se = detail::scope_exit([&] {
  9721. svr.stop();
  9722. t.join();
  9723. ASSERT_FALSE(svr.is_running());
  9724. });
  9725. svr.wait_until_ready();
  9726. SSLClient cli(HOST, PORT);
  9727. cli.set_connection_timeout(30);
  9728. auto res = cli.Get("/test");
  9729. ASSERT_TRUE(!res);
  9730. // When client cert is missing and server requires it, connection fails
  9731. // Error type depends on backend implementation
  9732. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  9733. res.error() == Error::SSLConnection);
  9734. // Verify backend error is captured
  9735. // Note: This test may have different error codes depending on the exact
  9736. // verification failure
  9737. EXPECT_NE(0UL, res.ssl_backend_error());
  9738. }
  9739. TEST(SSLClientServerTest, TrustDirOptional) {
  9740. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  9741. ASSERT_TRUE(svr.is_valid());
  9742. svr.Get("/test", [&](const Request &, Response &res) {
  9743. res.set_content("test", "text/plain");
  9744. });
  9745. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9746. auto se = detail::scope_exit([&] {
  9747. svr.stop();
  9748. t.join();
  9749. ASSERT_FALSE(svr.is_running());
  9750. });
  9751. svr.wait_until_ready();
  9752. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9753. cli.enable_server_certificate_verification(false);
  9754. cli.set_connection_timeout(30);
  9755. auto res = cli.Get("/test");
  9756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9757. ASSERT_EQ(StatusCode::OK_200, res->status);
  9758. }
  9759. TEST(SSLClientServerTest, SSLConnectTimeout) {
  9760. class NoListenSSLServer : public SSLServer {
  9761. public:
  9762. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  9763. const char *client_ca_cert_file_path,
  9764. const char *client_ca_cert_dir_path = nullptr)
  9765. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  9766. client_ca_cert_dir_path),
  9767. stop_(false) {}
  9768. std::atomic_bool stop_;
  9769. private:
  9770. bool process_and_close_socket(socket_t /*sock*/) override {
  9771. // Don't create SSL context
  9772. while (!stop_.load()) {
  9773. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9774. }
  9775. return true;
  9776. }
  9777. };
  9778. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  9779. CLIENT_CA_CERT_FILE);
  9780. ASSERT_TRUE(svr.is_valid());
  9781. svr.Get("/test", [&](const Request &, Response &res) {
  9782. res.set_content("test", "text/plain");
  9783. });
  9784. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9785. auto se = detail::scope_exit([&] {
  9786. svr.stop_ = true;
  9787. svr.stop();
  9788. t.join();
  9789. ASSERT_FALSE(svr.is_running());
  9790. });
  9791. svr.wait_until_ready();
  9792. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9793. cli.enable_server_certificate_verification(false);
  9794. cli.set_connection_timeout(1);
  9795. auto res = cli.Get("/test");
  9796. ASSERT_TRUE(!res);
  9797. EXPECT_EQ(Error::SSLConnection, res.error());
  9798. // Timeout results in WantRead error code (maps to backend-specific value)
  9799. EXPECT_NE(0, res.ssl_error());
  9800. }
  9801. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  9802. // Test SSLServer with client certificate verification using the standard
  9803. // constructor (ContextSetupCallback is tested by backend-specific tests)
  9804. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  9805. CLIENT_CA_CERT_DIR);
  9806. ASSERT_TRUE(svr.is_valid());
  9807. svr.Get("/test", [&](const Request &req, Response &res) {
  9808. res.set_content("test", "text/plain");
  9809. auto cert = req.peer_cert();
  9810. ASSERT_TRUE(static_cast<bool>(cert));
  9811. auto common_name = cert.subject_cn();
  9812. EXPECT_EQ("Common Name", common_name);
  9813. });
  9814. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9815. auto se = detail::scope_exit([&] {
  9816. svr.stop();
  9817. t.join();
  9818. ASSERT_FALSE(svr.is_running());
  9819. });
  9820. svr.wait_until_ready();
  9821. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9822. cli.enable_server_certificate_verification(false);
  9823. cli.set_connection_timeout(30);
  9824. auto res = cli.Get("/test");
  9825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9826. ASSERT_EQ(StatusCode::OK_200, res->status);
  9827. }
  9828. // Test verify_hostname for both OpenSSL and MbedTLS backends
  9829. // Verifies that wildcard matching and exact matching work consistently
  9830. TEST(SSLClientServerTest, TlsVerifyHostname) {
  9831. using namespace httplib::tls;
  9832. // We need a running server to test against
  9833. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9834. ASSERT_TRUE(svr.is_valid());
  9835. svr.Get("/test", [](const Request &, Response &res) {
  9836. res.set_content("ok", "text/plain");
  9837. });
  9838. thread t([&]() { svr.listen(HOST, PORT); });
  9839. auto se = detail::scope_exit([&] {
  9840. svr.stop();
  9841. t.join();
  9842. });
  9843. svr.wait_until_ready();
  9844. bool verify_callback_called = false;
  9845. bool verify_result_wrong = false;
  9846. SSLClient cli(HOST, PORT);
  9847. cli.enable_server_certificate_verification(true);
  9848. cli.set_ca_cert_path(CA_CERT_FILE);
  9849. cli.set_connection_timeout(5);
  9850. // Note: Test certificate has CN="Common Name", not "localhost"
  9851. bool verify_result_cn = false;
  9852. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9853. verify_callback_called = true;
  9854. if (!ctx.cert) return false;
  9855. // Test 1: "Common Name" should match (our test server cert CN)
  9856. verify_result_cn = ctx.check_hostname("Common Name");
  9857. // Test 2: wrong hostname should not match
  9858. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  9859. return true; // Accept for the purpose of this test
  9860. });
  9861. auto res = cli.Get("/test");
  9862. // The request may succeed or fail depending on cert configuration
  9863. // but the callback should have been called
  9864. ASSERT_TRUE(verify_callback_called)
  9865. << "Verify callback should have been called";
  9866. // CN="Common Name" should match our test certificate
  9867. //
  9868. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  9869. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  9870. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  9871. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  9872. // <openssl/base.h>, which is included transitively when
  9873. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  9874. #if defined(OPENSSL_IS_BORINGSSL)
  9875. EXPECT_FALSE(verify_result_cn)
  9876. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  9877. #else
  9878. EXPECT_TRUE(verify_result_cn)
  9879. << "verify_hostname should match 'Common Name' (certificate CN)";
  9880. #endif
  9881. // Wrong hostname should not match
  9882. EXPECT_FALSE(verify_result_wrong)
  9883. << "verify_hostname should not match 'wronghost.example.com'";
  9884. }
  9885. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  9886. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  9887. // X509_check_ip behavior and must hold for every backend.
  9888. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  9889. using namespace httplib::tls;
  9890. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  9891. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  9892. ASSERT_TRUE(svr.is_valid());
  9893. svr.Get("/test", [](const Request &, Response &res) {
  9894. res.set_content("ok", "text/plain");
  9895. });
  9896. thread t([&]() { svr.listen(HOST, PORT); });
  9897. auto se = detail::scope_exit([&] {
  9898. svr.stop();
  9899. t.join();
  9900. });
  9901. svr.wait_until_ready();
  9902. bool verify_callback_called = false;
  9903. bool ip_matched_via_cn = true;
  9904. SSLClient cli(HOST, PORT);
  9905. cli.enable_server_certificate_verification(true);
  9906. cli.set_ca_cert_path(CA_CERT_FILE);
  9907. cli.set_connection_timeout(5);
  9908. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9909. verify_callback_called = true;
  9910. if (!ctx.cert) return false;
  9911. // The IP appears only in the CN, so it must NOT be accepted.
  9912. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  9913. return true; // Accept for the purpose of this test
  9914. });
  9915. cli.Get("/test");
  9916. ASSERT_TRUE(verify_callback_called)
  9917. << "Verify callback should have been called";
  9918. EXPECT_FALSE(ip_matched_via_cn)
  9919. << "An IP host must not be authenticated via the certificate CN";
  9920. }
  9921. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  9922. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  9923. using namespace httplib::tls;
  9924. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  9925. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  9926. ASSERT_TRUE(svr.is_valid());
  9927. svr.Get("/test", [](const Request &, Response &res) {
  9928. res.set_content("ok", "text/plain");
  9929. });
  9930. thread t([&]() { svr.listen(HOST, PORT); });
  9931. auto se = detail::scope_exit([&] {
  9932. svr.stop();
  9933. t.join();
  9934. });
  9935. svr.wait_until_ready();
  9936. bool verify_callback_called = false;
  9937. bool san_matched = false;
  9938. bool wrong_ipv6_matched = true;
  9939. bool cn_ipv6_matched = true;
  9940. SSLClient cli(HOST, PORT);
  9941. cli.enable_server_certificate_verification(true);
  9942. cli.set_ca_cert_path(CA_CERT_FILE);
  9943. cli.set_connection_timeout(5);
  9944. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9945. verify_callback_called = true;
  9946. if (!ctx.cert) return false;
  9947. // Matches the IPv6 iPAddress SAN.
  9948. san_matched = ctx.check_hostname("2001:db8::1");
  9949. // A different IPv6 address must not match.
  9950. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  9951. // "::1" lives only in the CN, so it must not be accepted.
  9952. cn_ipv6_matched = ctx.check_hostname("::1");
  9953. return true; // Accept for the purpose of this test
  9954. });
  9955. cli.Get("/test");
  9956. ASSERT_TRUE(verify_callback_called)
  9957. << "Verify callback should have been called";
  9958. EXPECT_TRUE(san_matched)
  9959. << "verify_hostname should match an IPv6 iPAddress SAN";
  9960. EXPECT_FALSE(wrong_ipv6_matched)
  9961. << "verify_hostname should not match a non-matching IPv6 address";
  9962. EXPECT_FALSE(cn_ipv6_matched)
  9963. << "An IPv6 host must not be authenticated via the certificate CN";
  9964. }
  9965. #endif
  9966. // mbedTLS-specific callback constructor test
  9967. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  9968. #ifdef CPPHTTPLIB_SSL_ENABLED
  9969. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  9970. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  9971. ASSERT_TRUE(svr.is_valid());
  9972. // Set up a handler to verify client certificate is present
  9973. bool client_cert_verified = false;
  9974. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  9975. // Verify that client certificate was provided
  9976. client_cert_verified = true;
  9977. res.set_content("success", "text/plain");
  9978. });
  9979. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9980. auto se = detail::scope_exit([&] {
  9981. svr.stop();
  9982. t.join();
  9983. ASSERT_FALSE(svr.is_running());
  9984. });
  9985. svr.wait_until_ready();
  9986. // Client with certificate
  9987. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9988. cli.enable_server_certificate_verification(false);
  9989. cli.set_connection_timeout(30);
  9990. auto res = cli.Get("/test");
  9991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9992. ASSERT_EQ(StatusCode::OK_200, res->status);
  9993. ASSERT_TRUE(client_cert_verified);
  9994. EXPECT_EQ("success", res->body);
  9995. }
  9996. #endif
  9997. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  9998. // backends
  9999. #ifdef CPPHTTPLIB_SSL_ENABLED
  10000. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  10001. using namespace httplib::tls;
  10002. // Test that when client CA cert file is provided,
  10003. // the server properly requests and validates client certificates
  10004. // Create a server with client authentication
  10005. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  10006. ASSERT_TRUE(svr.is_valid());
  10007. bool handler_called = false;
  10008. svr.Get("/test", [&](const Request &req, Response &res) {
  10009. handler_called = true;
  10010. // Verify that a client certificate was provided
  10011. auto cert = req.peer_cert();
  10012. ASSERT_TRUE(static_cast<bool>(cert));
  10013. // Get the issuer name
  10014. std::string issuer_str = cert.issuer_name();
  10015. ASSERT_FALSE(issuer_str.empty());
  10016. // The client certificate should be issued by our test CA
  10017. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  10018. res.set_content("authenticated", "text/plain");
  10019. });
  10020. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10021. auto se = detail::scope_exit([&] {
  10022. svr.stop();
  10023. t.join();
  10024. ASSERT_FALSE(svr.is_running());
  10025. });
  10026. svr.wait_until_ready();
  10027. // Connect with a client certificate issued by the CA
  10028. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10029. cli.enable_server_certificate_verification(false);
  10030. cli.set_connection_timeout(30);
  10031. auto res = cli.Get("/test");
  10032. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10033. ASSERT_EQ(StatusCode::OK_200, res->status);
  10034. ASSERT_TRUE(handler_called);
  10035. EXPECT_EQ("authenticated", res->body);
  10036. }
  10037. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  10038. using namespace httplib::tls;
  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 cert_checked = false;
  10054. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10055. if (ctx.cert) {
  10056. auto sans = ctx.sans();
  10057. // Test certificate may or may not have SANs - just verify the API
  10058. // works If SANs exist, verify the types are valid
  10059. for (const auto &san : sans) {
  10060. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  10061. san.type == SanType::EMAIL || san.type == SanType::URI ||
  10062. san.type == SanType::OTHER);
  10063. EXPECT_FALSE(san.value.empty());
  10064. }
  10065. cert_checked = true;
  10066. }
  10067. return true;
  10068. });
  10069. auto res = cli.Get("/test");
  10070. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10071. EXPECT_TRUE(cert_checked);
  10072. }
  10073. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  10074. using namespace httplib::tls;
  10075. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10076. ASSERT_TRUE(svr.is_valid());
  10077. svr.Get("/test", [](const Request &, Response &res) {
  10078. res.set_content("ok", "text/plain");
  10079. });
  10080. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10081. auto se = detail::scope_exit([&] {
  10082. svr.stop();
  10083. t.join();
  10084. });
  10085. svr.wait_until_ready();
  10086. SSLClient cli(HOST, PORT);
  10087. cli.enable_server_certificate_verification(false);
  10088. cli.set_connection_timeout(30);
  10089. bool validity_checked = false;
  10090. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10091. if (ctx.cert) {
  10092. time_t not_before = 0, not_after = 0;
  10093. bool result = ctx.validity(not_before, not_after);
  10094. EXPECT_TRUE(result);
  10095. // Verify that not_before < now < not_after for a valid cert
  10096. time_t now = time(nullptr);
  10097. EXPECT_LT(not_before, now);
  10098. EXPECT_GT(not_after, now);
  10099. validity_checked = true;
  10100. }
  10101. return true;
  10102. });
  10103. auto res = cli.Get("/test");
  10104. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10105. EXPECT_TRUE(validity_checked);
  10106. }
  10107. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  10108. using namespace httplib::tls;
  10109. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10110. ASSERT_TRUE(svr.is_valid());
  10111. svr.Get("/test", [](const Request &, Response &res) {
  10112. res.set_content("ok", "text/plain");
  10113. });
  10114. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10115. auto se = detail::scope_exit([&] {
  10116. svr.stop();
  10117. t.join();
  10118. });
  10119. svr.wait_until_ready();
  10120. SSLClient cli(HOST, PORT);
  10121. cli.enable_server_certificate_verification(false);
  10122. cli.set_connection_timeout(30);
  10123. bool serial_checked = false;
  10124. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10125. if (ctx.cert) {
  10126. std::string serial = ctx.serial();
  10127. EXPECT_FALSE(serial.empty());
  10128. // Serial should be a hex string
  10129. for (char c : serial) {
  10130. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  10131. (c >= 'a' && c <= 'f'));
  10132. }
  10133. serial_checked = true;
  10134. }
  10135. return true;
  10136. });
  10137. auto res = cli.Get("/test");
  10138. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10139. EXPECT_TRUE(serial_checked);
  10140. }
  10141. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  10142. // Test 1: Valid CA file - no error should be recorded
  10143. {
  10144. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  10145. CLIENT_CA_CERT_FILE);
  10146. ASSERT_TRUE(svr.is_valid());
  10147. // With valid setup, last_ssl_error should be 0
  10148. EXPECT_EQ(0, svr.ssl_last_error());
  10149. }
  10150. // Test 2: Invalid CA file content
  10151. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  10152. {
  10153. // Create a temporary file with completely invalid content
  10154. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  10155. {
  10156. std::ofstream ofs(temp_invalid_ca);
  10157. ofs << "This is not a certificate file at all\n";
  10158. ofs << "Just plain text content\n";
  10159. }
  10160. // Create server with invalid CA file
  10161. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  10162. // Clean up temporary file
  10163. std::remove(temp_invalid_ca);
  10164. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  10165. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  10166. // Note: SSL_CTX_load_verify_locations typically fails first,
  10167. // but our error handling code path is still exercised
  10168. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  10169. }
  10170. }
  10171. TEST(VerifyCallbackTest, VerifyContextFields) {
  10172. using namespace httplib::tls;
  10173. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10174. ASSERT_TRUE(svr.is_valid());
  10175. svr.Get("/test", [](const Request &, Response &res) {
  10176. res.set_content("ok", "text/plain");
  10177. });
  10178. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10179. auto se = detail::scope_exit([&] {
  10180. svr.stop();
  10181. t.join();
  10182. });
  10183. svr.wait_until_ready();
  10184. SSLClient cli(HOST, PORT);
  10185. cli.enable_server_certificate_verification(false);
  10186. cli.set_connection_timeout(30);
  10187. int callback_count = 0;
  10188. bool saw_leaf_cert = false;
  10189. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10190. if (ctx.cert) {
  10191. callback_count++;
  10192. // We should see at least one certificate (the leaf)
  10193. std::string cn = ctx.subject_cn();
  10194. if (!cn.empty()) { saw_leaf_cert = true; }
  10195. // Verify context fields are populated
  10196. EXPECT_NE(ctx.session, nullptr);
  10197. EXPECT_GE(ctx.depth, 0);
  10198. }
  10199. return true;
  10200. });
  10201. auto res = cli.Get("/test");
  10202. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10203. EXPECT_GT(callback_count, 0);
  10204. EXPECT_TRUE(saw_leaf_cert);
  10205. }
  10206. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  10207. using httplib::tls::TlsError;
  10208. // Test that verify_error_to_string returns empty for success
  10209. std::string success_str = TlsError::verify_error_to_string(0);
  10210. EXPECT_TRUE(success_str.empty());
  10211. // Test that verify_error_to_string returns non-empty for error codes
  10212. // Using a common error code (certificate expired)
  10213. std::string error_str =
  10214. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  10215. EXPECT_FALSE(error_str.empty());
  10216. }
  10217. TEST(SessionVerifierTest, CertificateAccepted) {
  10218. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10219. ASSERT_TRUE(svr.is_valid());
  10220. svr.Get("/test", [](const Request &, Response &res) {
  10221. res.set_content("ok", "text/plain");
  10222. });
  10223. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10224. auto se = detail::scope_exit([&] {
  10225. svr.stop();
  10226. t.join();
  10227. });
  10228. svr.wait_until_ready();
  10229. SSLClient cli(HOST, PORT);
  10230. cli.enable_server_certificate_verification(false);
  10231. cli.set_connection_timeout(30);
  10232. bool callback_called = false;
  10233. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  10234. EXPECT_NE(session, nullptr);
  10235. callback_called = true;
  10236. return SSLVerifierResponse::CertificateAccepted;
  10237. });
  10238. auto res = cli.Get("/test");
  10239. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10240. EXPECT_EQ(200, res->status);
  10241. EXPECT_TRUE(callback_called);
  10242. }
  10243. TEST(SessionVerifierTest, CertificateRejected) {
  10244. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10245. ASSERT_TRUE(svr.is_valid());
  10246. svr.Get("/test", [](const Request &, Response &res) {
  10247. res.set_content("ok", "text/plain");
  10248. });
  10249. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10250. auto se = detail::scope_exit([&] {
  10251. svr.stop();
  10252. t.join();
  10253. });
  10254. svr.wait_until_ready();
  10255. SSLClient cli(HOST, PORT);
  10256. cli.enable_server_certificate_verification(false);
  10257. cli.set_connection_timeout(30);
  10258. bool callback_called = false;
  10259. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  10260. EXPECT_NE(session, nullptr);
  10261. callback_called = true;
  10262. return SSLVerifierResponse::CertificateRejected;
  10263. });
  10264. auto res = cli.Get("/test");
  10265. EXPECT_FALSE(res);
  10266. EXPECT_TRUE(callback_called);
  10267. }
  10268. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  10269. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10270. ASSERT_TRUE(svr.is_valid());
  10271. svr.Get("/test", [](const Request &, Response &res) {
  10272. res.set_content("ok", "text/plain");
  10273. });
  10274. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10275. auto se = detail::scope_exit([&] {
  10276. svr.stop();
  10277. t.join();
  10278. });
  10279. svr.wait_until_ready();
  10280. // NoDecisionMade with verification disabled should succeed (no default check)
  10281. SSLClient cli(HOST, PORT);
  10282. cli.enable_server_certificate_verification(false);
  10283. cli.set_connection_timeout(30);
  10284. bool callback_called = false;
  10285. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  10286. EXPECT_NE(session, nullptr);
  10287. callback_called = true;
  10288. return SSLVerifierResponse::NoDecisionMade;
  10289. });
  10290. auto res = cli.Get("/test");
  10291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10292. EXPECT_EQ(200, res->status);
  10293. EXPECT_TRUE(callback_called);
  10294. }
  10295. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  10296. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10297. ASSERT_TRUE(svr.is_valid());
  10298. svr.Get("/test", [](const Request &, Response &res) {
  10299. res.set_content("ok", "text/plain");
  10300. });
  10301. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10302. auto se = detail::scope_exit([&] {
  10303. svr.stop();
  10304. t.join();
  10305. });
  10306. svr.wait_until_ready();
  10307. // NoDecisionMade with verification enabled should fail (self-signed cert).
  10308. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  10309. // so we only check that the request fails, not whether the callback was
  10310. // called.
  10311. SSLClient cli(HOST, PORT);
  10312. cli.enable_server_certificate_verification(true);
  10313. cli.set_connection_timeout(30);
  10314. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  10315. EXPECT_NE(session, nullptr);
  10316. return SSLVerifierResponse::NoDecisionMade;
  10317. });
  10318. auto res = cli.Get("/test");
  10319. EXPECT_FALSE(res);
  10320. }
  10321. TEST(SSLClientServerTest, ClientCAListFromPem) {
  10322. // Test SSL server using PemMemory constructor with client CA certificates
  10323. // Read PEM files
  10324. std::string server_cert_pem, server_key_pem, client_ca_pem;
  10325. read_file(SERVER_CERT_FILE, server_cert_pem);
  10326. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  10327. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  10328. // Create SSLServer with PemMemory constructor including client CA
  10329. SSLServer::PemMemory server_pem = {
  10330. server_cert_pem.c_str(),
  10331. server_cert_pem.size(),
  10332. server_key_pem.c_str(),
  10333. server_key_pem.size(),
  10334. client_ca_pem.c_str(),
  10335. client_ca_pem.size(),
  10336. nullptr // no password for server key
  10337. };
  10338. SSLServer svr(server_pem);
  10339. ASSERT_TRUE(svr.is_valid());
  10340. // No SSL error should be recorded for valid setup
  10341. EXPECT_EQ(0, svr.ssl_last_error());
  10342. // Set up server endpoints
  10343. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  10344. res.set_content("ok", "text/plain");
  10345. });
  10346. // Start server in a thread
  10347. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  10348. svr.wait_until_ready();
  10349. // Connect with client certificate (using constructor with paths)
  10350. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10351. cli.enable_server_certificate_verification(false);
  10352. auto res = cli.Get("/test-pem-ca");
  10353. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10354. EXPECT_EQ(200, res->status);
  10355. EXPECT_EQ("ok", res->body);
  10356. svr.stop();
  10357. server_thread.join();
  10358. }
  10359. #endif
  10360. #ifdef _WIN32
  10361. TEST(CleanupTest, WSACleanup) {
  10362. int ret = WSACleanup();
  10363. ASSERT_EQ(0, ret);
  10364. }
  10365. #endif
  10366. #ifndef CPPHTTPLIB_SSL_ENABLED
  10367. TEST(NoSSLSupport, SimpleInterface) {
  10368. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  10369. }
  10370. #endif
  10371. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10372. TEST(InvalidScheme, SimpleInterface) {
  10373. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  10374. }
  10375. #endif
  10376. TEST(NoScheme, SimpleInterface) {
  10377. Client cli("yahoo.com:80");
  10378. ASSERT_TRUE(cli.is_valid());
  10379. }
  10380. TEST(SendAPI, SimpleInterface_Online) {
  10381. Client cli("http://yahoo.com");
  10382. Request req;
  10383. req.method = "GET";
  10384. req.path = "/";
  10385. auto res = cli.send(req);
  10386. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10387. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10388. }
  10389. TEST(SendAPI, WithParamsInRequest) {
  10390. Server svr;
  10391. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  10392. EXPECT_TRUE(req.has_param("test"));
  10393. EXPECT_EQ("test_value", req.get_param_value("test"));
  10394. });
  10395. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  10396. auto se = detail::scope_exit([&] {
  10397. svr.stop();
  10398. t.join();
  10399. ASSERT_FALSE(svr.is_running());
  10400. });
  10401. svr.wait_until_ready();
  10402. Client cli(HOST, PORT);
  10403. {
  10404. Request req;
  10405. req.method = "GET";
  10406. req.path = "/";
  10407. req.params.emplace("test", "test_value");
  10408. auto res = cli.send(req);
  10409. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10410. }
  10411. {
  10412. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  10413. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10414. }
  10415. }
  10416. TEST(ClientImplMethods, GetSocketTest) {
  10417. httplib::Server svr;
  10418. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  10419. res.status = StatusCode::OK_200;
  10420. });
  10421. auto port = svr.bind_to_any_port("127.0.0.1");
  10422. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  10423. auto se = detail::scope_exit([&] {
  10424. svr.stop();
  10425. thread.join();
  10426. ASSERT_FALSE(svr.is_running());
  10427. });
  10428. svr.wait_until_ready();
  10429. {
  10430. httplib::Client cli("127.0.0.1", port);
  10431. cli.set_keep_alive(true);
  10432. // Use the behavior of cpp-httplib of opening the connection
  10433. // only when the first request happens. If that changes,
  10434. // this test would be obsolete.
  10435. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  10436. // This also implicitly tests the server. But other tests would fail much
  10437. // earlier than this one to be considered.
  10438. auto res = cli.Get("/");
  10439. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10440. EXPECT_EQ(StatusCode::OK_200, res->status);
  10441. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  10442. }
  10443. }
  10444. #ifdef CPPHTTPLIB_SSL_ENABLED
  10445. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  10446. Client cli("http://yahoo.com");
  10447. auto res = cli.Get("/");
  10448. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10449. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10450. cli.set_follow_location(true);
  10451. res = cli.Get("/");
  10452. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10453. EXPECT_EQ(StatusCode::OK_200, res->status);
  10454. EXPECT_EQ("https://www.yahoo.com/", res->location);
  10455. }
  10456. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  10457. Client cli("https://yahoo.com");
  10458. auto res = cli.Get("/");
  10459. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10460. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10461. cli.set_follow_location(true);
  10462. res = cli.Get("/");
  10463. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10464. EXPECT_EQ(StatusCode::OK_200, res->status);
  10465. EXPECT_EQ("https://www.yahoo.com/", res->location);
  10466. }
  10467. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  10468. Client cli("https://yahoo.com");
  10469. auto res = cli.Get("/");
  10470. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10471. ASSERT_FALSE(!res);
  10472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10473. ASSERT_FALSE(res == nullptr);
  10474. ASSERT_TRUE(res != nullptr);
  10475. EXPECT_EQ(Error::Success, res.error());
  10476. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  10477. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  10478. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10479. cli.set_follow_location(true);
  10480. res = cli.Get("/");
  10481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10482. EXPECT_EQ(Error::Success, res.error());
  10483. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  10484. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  10485. EXPECT_EQ(StatusCode::OK_200, res->status);
  10486. EXPECT_EQ("https://www.yahoo.com/", res->location);
  10487. }
  10488. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  10489. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  10490. Client cli("https://cdnjs.cloudflare.com");
  10491. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  10492. Headers{{"Accept-Encoding", "br"}});
  10493. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10494. EXPECT_EQ(StatusCode::OK_200, res->status);
  10495. EXPECT_EQ(287630U, res->body.size());
  10496. EXPECT_EQ("application/javascript; charset=utf-8",
  10497. res->get_header_value("Content-Type"));
  10498. }
  10499. #endif
  10500. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  10501. #undef REDIR_HOST // Silence compiler warning
  10502. #define REDIR_HOST "https://httpbingo.org"
  10503. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  10504. Client cli(REDIR_HOST);
  10505. cli.set_follow_location(true);
  10506. auto res =
  10507. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  10508. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10509. EXPECT_EQ(StatusCode::OK_200, res->status);
  10510. }
  10511. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  10512. Client cli(REDIR_HOST);
  10513. cli.set_follow_location(true);
  10514. Params params;
  10515. params.emplace("url", "http://example.com");
  10516. params.emplace("status_code", "302");
  10517. auto res = cli.Get(REDIR_PATH, params, Headers{});
  10518. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10519. EXPECT_EQ(StatusCode::OK_200, res->status);
  10520. }
  10521. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  10522. Client cli(REDIR_HOST);
  10523. cli.set_follow_location(true);
  10524. Params params;
  10525. params.emplace("url", "http://example.com");
  10526. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  10527. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10528. EXPECT_EQ(StatusCode::OK_200, res->status);
  10529. }
  10530. TEST(HttpToHttpsRedirectTest, CertFile) {
  10531. auto ssl_port = PORT + 1;
  10532. Server svr;
  10533. ASSERT_TRUE(svr.is_valid());
  10534. svr.Get("/index", [&](const Request &, Response &res) {
  10535. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  10536. "/index");
  10537. svr.stop();
  10538. });
  10539. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10540. ASSERT_TRUE(ssl_svr.is_valid());
  10541. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  10542. res.set_content("test", "text/plain");
  10543. ssl_svr.stop();
  10544. });
  10545. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10546. thread t2 =
  10547. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  10548. auto se = detail::scope_exit([&] {
  10549. t2.join();
  10550. t.join();
  10551. ASSERT_FALSE(svr.is_running());
  10552. });
  10553. svr.wait_until_ready();
  10554. ssl_svr.wait_until_ready();
  10555. Client cli("127.0.0.1", PORT);
  10556. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  10557. cli.enable_server_certificate_verification(true);
  10558. cli.set_follow_location(true);
  10559. cli.set_connection_timeout(30);
  10560. auto res = cli.Get("/index");
  10561. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10562. ASSERT_EQ(StatusCode::OK_200, res->status);
  10563. }
  10564. TEST(SSLClientRedirectTest, CertFile) {
  10565. auto ssl_port = PORT + 1;
  10566. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10567. ASSERT_TRUE(ssl_svr1.is_valid());
  10568. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  10569. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  10570. "/index");
  10571. ssl_svr1.stop();
  10572. });
  10573. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10574. ASSERT_TRUE(ssl_svr2.is_valid());
  10575. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  10576. res.set_content("test", "text/plain");
  10577. ssl_svr2.stop();
  10578. });
  10579. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  10580. thread t2 =
  10581. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  10582. auto se = detail::scope_exit([&] {
  10583. t2.join();
  10584. t.join();
  10585. ASSERT_FALSE(ssl_svr1.is_running());
  10586. });
  10587. ssl_svr1.wait_until_ready();
  10588. ssl_svr2.wait_until_ready();
  10589. SSLClient cli("127.0.0.1", PORT);
  10590. std::string cert;
  10591. read_file(SERVER_CERT2_FILE, cert);
  10592. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10593. cli.enable_server_certificate_verification(true);
  10594. cli.set_follow_location(true);
  10595. cli.set_connection_timeout(30);
  10596. auto res = cli.Get("/index");
  10597. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10598. ASSERT_EQ(StatusCode::OK_200, res->status);
  10599. }
  10600. #endif
  10601. #ifdef CPPHTTPLIB_SSL_ENABLED
  10602. // Test that set_ca_cert_store() skips system certs (consistent with
  10603. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  10604. // should be trusted - system certs should NOT be loaded.
  10605. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  10606. // Load a specific cert that is NOT a system CA cert
  10607. std::string cert;
  10608. read_file(SERVER_CERT2_FILE, cert);
  10609. SSLClient cli("google.com");
  10610. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10611. cli.enable_server_certificate_verification(true);
  10612. // This should FAIL because:
  10613. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  10614. // 2. System certs should NOT be loaded when custom store is set
  10615. // If system certs WERE loaded, this would succeed
  10616. auto res = cli.Get("/");
  10617. ASSERT_FALSE(res);
  10618. EXPECT_EQ(Error::SSLServerVerification, res.error());
  10619. }
  10620. // Same as above, but through the native store handle path. Regression test:
  10621. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  10622. // merged system certs into the user-provided store.
  10623. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  10624. std::string cert;
  10625. read_file(SERVER_CERT2_FILE, cert);
  10626. SSLClient cli("google.com");
  10627. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  10628. cli.enable_server_certificate_verification(true);
  10629. auto res = cli.Get("/");
  10630. ASSERT_FALSE(res);
  10631. EXPECT_EQ(Error::SSLServerVerification, res.error());
  10632. }
  10633. // A custom store set via the native handle must still verify a server whose
  10634. // cert it does contain.
  10635. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  10636. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10637. ASSERT_TRUE(svr.is_valid());
  10638. svr.Get("/test", [&](const Request &, Response &res) {
  10639. res.set_content("test", "text/plain");
  10640. });
  10641. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10642. auto se = detail::scope_exit([&] {
  10643. svr.stop();
  10644. t.join();
  10645. ASSERT_FALSE(svr.is_running());
  10646. });
  10647. svr.wait_until_ready();
  10648. SSLClient cli("127.0.0.1", PORT);
  10649. std::string cert;
  10650. read_file(SERVER_CERT2_FILE, cert);
  10651. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  10652. cli.enable_server_certificate_verification(true);
  10653. cli.set_connection_timeout(30);
  10654. auto res = cli.Get("/test");
  10655. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10656. ASSERT_EQ(StatusCode::OK_200, res->status);
  10657. }
  10658. // CA certs loaded through the universal Client must be transferred to the
  10659. // client created internally for following an HTTPS redirect. Regression test:
  10660. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  10661. // the CA data for redirect transfer.
  10662. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  10663. auto ssl_port = PORT + 1;
  10664. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10665. ASSERT_TRUE(ssl_svr1.is_valid());
  10666. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  10667. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  10668. "/index");
  10669. });
  10670. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10671. ASSERT_TRUE(ssl_svr2.is_valid());
  10672. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  10673. res.set_content("test", "text/plain");
  10674. });
  10675. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  10676. thread t2 =
  10677. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  10678. auto se = detail::scope_exit([&] {
  10679. ssl_svr2.stop();
  10680. ssl_svr1.stop();
  10681. t2.join();
  10682. t.join();
  10683. ASSERT_FALSE(ssl_svr1.is_running());
  10684. });
  10685. ssl_svr1.wait_until_ready();
  10686. ssl_svr2.wait_until_ready();
  10687. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  10688. std::string cert;
  10689. read_file(SERVER_CERT2_FILE, cert);
  10690. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10691. cli.enable_server_certificate_verification(true);
  10692. cli.set_follow_location(true);
  10693. cli.set_connection_timeout(30);
  10694. auto res = cli.Get("/index");
  10695. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10696. ASSERT_EQ(StatusCode::OK_200, res->status);
  10697. }
  10698. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  10699. // so a host signed by a system CA verifies even though a custom CA is set
  10700. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  10701. std::string cert;
  10702. read_file(SERVER_CERT2_FILE, cert);
  10703. SSLClient cli("google.com");
  10704. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10705. cli.enable_system_ca(true);
  10706. cli.enable_server_certificate_verification(true);
  10707. auto res = cli.Get("/");
  10708. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10709. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10710. }
  10711. // The custom CA remains effective when combined with the system CA
  10712. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  10713. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10714. ASSERT_TRUE(svr.is_valid());
  10715. svr.Get("/test", [&](const Request &, Response &res) {
  10716. res.set_content("test", "text/plain");
  10717. });
  10718. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10719. auto se = detail::scope_exit([&] {
  10720. svr.stop();
  10721. t.join();
  10722. ASSERT_FALSE(svr.is_running());
  10723. });
  10724. svr.wait_until_ready();
  10725. SSLClient cli("127.0.0.1", PORT);
  10726. std::string cert;
  10727. read_file(SERVER_CERT2_FILE, cert);
  10728. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10729. cli.enable_system_ca(true);
  10730. cli.enable_server_certificate_verification(true);
  10731. cli.set_connection_timeout(30);
  10732. auto res = cli.Get("/test");
  10733. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10734. ASSERT_EQ(StatusCode::OK_200, res->status);
  10735. }
  10736. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  10737. // skip chain verification entirely (only the certificate identity was
  10738. // checked), so a server presenting an untrusted certificate with a matching
  10739. // IP SAN was accepted. The chain must be validated for IP hosts too.
  10740. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  10741. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10742. ASSERT_TRUE(svr.is_valid());
  10743. svr.Get("/test", [&](const Request &, Response &res) {
  10744. res.set_content("test", "text/plain");
  10745. });
  10746. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10747. auto se = detail::scope_exit([&] {
  10748. svr.stop();
  10749. t.join();
  10750. ASSERT_FALSE(svr.is_running());
  10751. });
  10752. svr.wait_until_ready();
  10753. SSLClient cli("127.0.0.1", PORT);
  10754. std::string cert;
  10755. // A trusted CA that did not sign the server certificate. The server cert
  10756. // (cert2) carries the matching IP SAN, so only chain validation can reject
  10757. // this connection.
  10758. read_file(CLIENT_CA_CERT_FILE, cert);
  10759. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10760. cli.enable_server_certificate_verification(true);
  10761. cli.set_connection_timeout(30);
  10762. auto res = cli.Get("/test");
  10763. ASSERT_FALSE(res);
  10764. }
  10765. // enable_system_ca(false) prevents system CA loading entirely
  10766. TEST(SSLClientTest, DisableSystemCa_Online) {
  10767. SSLClient cli("google.com");
  10768. cli.enable_system_ca(false);
  10769. cli.enable_server_certificate_verification(true);
  10770. auto res = cli.Get("/");
  10771. ASSERT_FALSE(res);
  10772. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  10773. // itself when the CA chain is empty
  10774. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  10775. res.error() == Error::SSLConnection);
  10776. }
  10777. // The universal Client forwards enable_system_ca()
  10778. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  10779. std::string cert;
  10780. read_file(SERVER_CERT2_FILE, cert);
  10781. Client cli("https://google.com");
  10782. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10783. cli.enable_system_ca(true);
  10784. cli.enable_server_certificate_verification(true);
  10785. auto res = cli.Get("/");
  10786. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10787. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10788. }
  10789. // The system CA policy must carry over to the client created internally for
  10790. // following a cross-host HTTPS redirect
  10791. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  10792. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10793. ASSERT_TRUE(svr.is_valid());
  10794. svr.Get("/index", [&](const Request &, Response &res) {
  10795. res.set_redirect("https://www.google.com/");
  10796. });
  10797. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10798. auto se = detail::scope_exit([&] {
  10799. svr.stop();
  10800. t.join();
  10801. ASSERT_FALSE(svr.is_running());
  10802. });
  10803. svr.wait_until_ready();
  10804. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  10805. std::string cert;
  10806. read_file(SERVER_CERT2_FILE, cert);
  10807. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10808. cli.enable_system_ca(true);
  10809. cli.enable_server_certificate_verification(true);
  10810. cli.set_follow_location(true);
  10811. cli.set_connection_timeout(30);
  10812. // Receiving any response proves the redirect client completed the TLS
  10813. // handshake with a system-CA-signed host
  10814. auto res = cli.Get("/index");
  10815. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10816. }
  10817. TEST(MultipartFormDataTest, LargeData) {
  10818. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10819. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  10820. const ContentReader &content_reader) {
  10821. if (req.is_multipart_form_data()) {
  10822. std::vector<FormData> items;
  10823. content_reader(
  10824. [&](const FormData &file) {
  10825. items.push_back(file);
  10826. return true;
  10827. },
  10828. [&](const char *data, size_t data_length) {
  10829. items.back().content.append(data, data_length);
  10830. return true;
  10831. });
  10832. EXPECT_TRUE(std::string(items[0].name) == "document");
  10833. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  10834. EXPECT_TRUE(items[0].filename == "2MB_data");
  10835. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  10836. EXPECT_TRUE(items[1].name == "hello");
  10837. EXPECT_TRUE(items[1].content == "world");
  10838. EXPECT_TRUE(items[1].filename == "");
  10839. EXPECT_TRUE(items[1].content_type == "");
  10840. } else {
  10841. std::string body;
  10842. content_reader([&](const char *data, size_t data_length) {
  10843. body.append(data, data_length);
  10844. return true;
  10845. });
  10846. }
  10847. });
  10848. auto port = svr.bind_to_any_port(HOST);
  10849. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10850. auto se = detail::scope_exit([&] {
  10851. svr.stop();
  10852. t.join();
  10853. ASSERT_FALSE(svr.is_running());
  10854. });
  10855. svr.wait_until_ready();
  10856. {
  10857. std::string data(1024 * 1024 * 2, '.');
  10858. std::stringstream buffer;
  10859. buffer << data;
  10860. SSLClient cli(HOST, port);
  10861. cli.enable_server_certificate_verification(false);
  10862. UploadFormDataItems items{
  10863. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10864. {"hello", "world", "", ""},
  10865. };
  10866. auto res = cli.Post("/post", items);
  10867. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10868. ASSERT_EQ(StatusCode::OK_200, res->status);
  10869. }
  10870. }
  10871. TEST(MultipartFormDataTest, DataProviderItems) {
  10872. std::random_device seed_gen;
  10873. std::mt19937 random(seed_gen());
  10874. std::string rand1;
  10875. rand1.resize(1000);
  10876. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  10877. std::string rand2;
  10878. rand2.resize(3000);
  10879. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  10880. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10881. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  10882. const ContentReader &content_reader) {
  10883. ASSERT_FALSE(req.is_multipart_form_data());
  10884. std::string body;
  10885. content_reader([&](const char *data, size_t data_length) {
  10886. body.append(data, data_length);
  10887. return true;
  10888. });
  10889. EXPECT_EQ(body, "");
  10890. });
  10891. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  10892. const ContentReader &content_reader) {
  10893. ASSERT_TRUE(req.is_multipart_form_data());
  10894. std::vector<FormData> items;
  10895. content_reader(
  10896. [&](const FormData &file) {
  10897. items.push_back(file);
  10898. return true;
  10899. },
  10900. [&](const char *data, size_t data_length) {
  10901. items.back().content.append(data, data_length);
  10902. return true;
  10903. });
  10904. ASSERT_TRUE(items.size() == 2);
  10905. EXPECT_EQ(std::string(items[0].name), "name1");
  10906. EXPECT_EQ(items[0].content, "Testing123");
  10907. EXPECT_EQ(items[0].filename, "filename1");
  10908. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  10909. EXPECT_EQ(items[1].name, "name2");
  10910. EXPECT_EQ(items[1].content, "Testing456");
  10911. EXPECT_EQ(items[1].filename, "");
  10912. EXPECT_EQ(items[1].content_type, "");
  10913. });
  10914. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  10915. const ContentReader &content_reader) {
  10916. ASSERT_TRUE(req.is_multipart_form_data());
  10917. std::vector<FormData> items;
  10918. content_reader(
  10919. [&](const FormData &file) {
  10920. items.push_back(file);
  10921. return true;
  10922. },
  10923. [&](const char *data, size_t data_length) {
  10924. items.back().content.append(data, data_length);
  10925. return true;
  10926. });
  10927. ASSERT_TRUE(items.size() == 2);
  10928. EXPECT_EQ(items[0].name, "name3");
  10929. EXPECT_EQ(items[0].content, rand1);
  10930. EXPECT_EQ(items[0].filename, "filename3");
  10931. EXPECT_EQ(items[0].content_type, "");
  10932. EXPECT_EQ(items[1].name, "name4");
  10933. EXPECT_EQ(items[1].content, rand2);
  10934. EXPECT_EQ(items[1].filename, "filename4");
  10935. EXPECT_EQ(items[1].content_type, "");
  10936. });
  10937. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  10938. const ContentReader &content_reader) {
  10939. ASSERT_TRUE(req.is_multipart_form_data());
  10940. std::vector<FormData> items;
  10941. content_reader(
  10942. [&](const FormData &file) {
  10943. items.push_back(file);
  10944. return true;
  10945. },
  10946. [&](const char *data, size_t data_length) {
  10947. items.back().content.append(data, data_length);
  10948. return true;
  10949. });
  10950. ASSERT_TRUE(items.size() == 4);
  10951. EXPECT_EQ(std::string(items[0].name), "name1");
  10952. EXPECT_EQ(items[0].content, "Testing123");
  10953. EXPECT_EQ(items[0].filename, "filename1");
  10954. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  10955. EXPECT_EQ(items[1].name, "name2");
  10956. EXPECT_EQ(items[1].content, "Testing456");
  10957. EXPECT_EQ(items[1].filename, "");
  10958. EXPECT_EQ(items[1].content_type, "");
  10959. EXPECT_EQ(items[2].name, "name3");
  10960. EXPECT_EQ(items[2].content, rand1);
  10961. EXPECT_EQ(items[2].filename, "filename3");
  10962. EXPECT_EQ(items[2].content_type, "");
  10963. EXPECT_EQ(items[3].name, "name4");
  10964. EXPECT_EQ(items[3].content, rand2);
  10965. EXPECT_EQ(items[3].filename, "filename4");
  10966. EXPECT_EQ(items[3].content_type, "");
  10967. });
  10968. auto port = svr.bind_to_any_port("localhost");
  10969. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10970. auto se = detail::scope_exit([&] {
  10971. svr.stop();
  10972. t.join();
  10973. ASSERT_FALSE(svr.is_running());
  10974. });
  10975. svr.wait_until_ready();
  10976. {
  10977. SSLClient cli("localhost", port);
  10978. cli.enable_server_certificate_verification(false);
  10979. UploadFormDataItems items{
  10980. {"name1", "Testing123", "filename1", "application/octet-stream"},
  10981. {"name2", "Testing456", "", ""}, // not a file
  10982. };
  10983. {
  10984. auto res = cli.Post("/post-none", {}, {}, {});
  10985. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10986. ASSERT_EQ(StatusCode::OK_200, res->status);
  10987. }
  10988. FormDataProviderItems providers;
  10989. {
  10990. auto res =
  10991. cli.Post("/post-items", {}, items, providers); // empty providers
  10992. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10993. ASSERT_EQ(StatusCode::OK_200, res->status);
  10994. }
  10995. providers.push_back({"name3",
  10996. [&](size_t offset, httplib::DataSink &sink) -> bool {
  10997. // test the offset is given correctly at each step
  10998. if (!offset)
  10999. sink.os.write(rand1.data(), 30);
  11000. else if (offset == 30)
  11001. sink.os.write(rand1.data() + 30, 300);
  11002. else if (offset == 330)
  11003. sink.os.write(rand1.data() + 330, 670);
  11004. else if (offset == rand1.size())
  11005. sink.done();
  11006. return true;
  11007. },
  11008. "filename3",
  11009. {}});
  11010. providers.push_back({"name4",
  11011. [&](size_t offset, httplib::DataSink &sink) -> bool {
  11012. // test the offset is given correctly at each step
  11013. if (!offset)
  11014. sink.os.write(rand2.data(), 2000);
  11015. else if (offset == 2000)
  11016. sink.os.write(rand2.data() + 2000, 1);
  11017. else if (offset == 2001)
  11018. sink.os.write(rand2.data() + 2001, 999);
  11019. else if (offset == rand2.size())
  11020. sink.done();
  11021. return true;
  11022. },
  11023. "filename4",
  11024. {}});
  11025. {
  11026. auto res = cli.Post("/post-providers", {}, {}, providers);
  11027. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11028. ASSERT_EQ(StatusCode::OK_200, res->status);
  11029. }
  11030. {
  11031. auto res = cli.Post("/post-both", {}, items, providers);
  11032. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11033. ASSERT_EQ(StatusCode::OK_200, res->status);
  11034. }
  11035. }
  11036. }
  11037. TEST(MultipartFormDataTest, BadHeader) {
  11038. Server svr;
  11039. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  11040. res.set_content("ok", "text/plain");
  11041. });
  11042. thread t = thread([&] { svr.listen(HOST, PORT); });
  11043. auto se = detail::scope_exit([&] {
  11044. svr.stop();
  11045. t.join();
  11046. ASSERT_FALSE(svr.is_running());
  11047. });
  11048. svr.wait_until_ready();
  11049. const std::string body =
  11050. "This is the preamble. It is to be ignored, though it\r\n"
  11051. "is a handy place for composition agents to include an\r\n"
  11052. "explanatory note to non-MIME conformant readers.\r\n"
  11053. "\r\n"
  11054. "\r\n"
  11055. "--simple boundary\r\n"
  11056. "Content-Disposition: form-data; name=\"field1\"\r\n"
  11057. ": BAD...\r\n"
  11058. "\r\n"
  11059. "value1\r\n"
  11060. "--simple boundary\r\n"
  11061. "Content-Disposition: form-data; name=\"field2\"; "
  11062. "filename=\"example.txt\"\r\n"
  11063. "\r\n"
  11064. "value2\r\n"
  11065. "--simple boundary--\r\n"
  11066. "This is the epilogue. It is also to be ignored.\r\n";
  11067. std::string content_type =
  11068. R"(multipart/form-data; boundary="simple boundary")";
  11069. Client cli(HOST, PORT);
  11070. auto res = cli.Post("/post", body, content_type.c_str());
  11071. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11072. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  11073. }
  11074. TEST(MultipartFormDataTest, WithPreamble) {
  11075. Server svr;
  11076. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  11077. res.set_content("ok", "text/plain");
  11078. });
  11079. thread t = thread([&] { svr.listen(HOST, PORT); });
  11080. auto se = detail::scope_exit([&] {
  11081. svr.stop();
  11082. t.join();
  11083. ASSERT_FALSE(svr.is_running());
  11084. });
  11085. svr.wait_until_ready();
  11086. const std::string body =
  11087. "This is the preamble. It is to be ignored, though it\r\n"
  11088. "is a handy place for composition agents to include an\r\n"
  11089. "explanatory note to non-MIME conformant readers.\r\n"
  11090. "\r\n"
  11091. "\r\n"
  11092. "--simple boundary\r\n"
  11093. "Content-Disposition: form-data; name=\"field1\"\r\n"
  11094. "\r\n"
  11095. "value1\r\n"
  11096. "--simple boundary\r\n"
  11097. "Content-Disposition: form-data; name=\"field2\"; "
  11098. "filename=\"example.txt\"\r\n"
  11099. "\r\n"
  11100. "value2\r\n"
  11101. "--simple boundary--\r\n"
  11102. "This is the epilogue. It is also to be ignored.\r\n";
  11103. std::string content_type =
  11104. R"(multipart/form-data; boundary="simple boundary")";
  11105. Client cli(HOST, PORT);
  11106. auto res = cli.Post("/post", body, content_type.c_str());
  11107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11108. EXPECT_EQ(StatusCode::OK_200, res->status);
  11109. }
  11110. TEST(MultipartFormDataTest, PostCustomBoundary) {
  11111. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11112. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  11113. const ContentReader &content_reader) {
  11114. if (req.is_multipart_form_data()) {
  11115. std::vector<FormData> items;
  11116. content_reader(
  11117. [&](const FormData &file) {
  11118. items.push_back(file);
  11119. return true;
  11120. },
  11121. [&](const char *data, size_t data_length) {
  11122. items.back().content.append(data, data_length);
  11123. return true;
  11124. });
  11125. EXPECT_TRUE(std::string(items[0].name) == "document");
  11126. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  11127. EXPECT_TRUE(items[0].filename == "2MB_data");
  11128. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  11129. EXPECT_TRUE(items[1].name == "hello");
  11130. EXPECT_TRUE(items[1].content == "world");
  11131. EXPECT_TRUE(items[1].filename == "");
  11132. EXPECT_TRUE(items[1].content_type == "");
  11133. } else {
  11134. std::string body;
  11135. content_reader([&](const char *data, size_t data_length) {
  11136. body.append(data, data_length);
  11137. return true;
  11138. });
  11139. }
  11140. });
  11141. auto port = svr.bind_to_any_port("localhost");
  11142. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11143. auto se = detail::scope_exit([&] {
  11144. svr.stop();
  11145. t.join();
  11146. ASSERT_FALSE(svr.is_running());
  11147. });
  11148. svr.wait_until_ready();
  11149. {
  11150. std::string data(1024 * 1024 * 2, '.');
  11151. std::stringstream buffer;
  11152. buffer << data;
  11153. SSLClient cli("localhost", port);
  11154. cli.enable_server_certificate_verification(false);
  11155. UploadFormDataItems items{
  11156. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11157. {"hello", "world", "", ""},
  11158. };
  11159. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  11160. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11161. ASSERT_EQ(StatusCode::OK_200, res->status);
  11162. }
  11163. }
  11164. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  11165. std::string data(1024 * 1024 * 2, '&');
  11166. std::stringstream buffer;
  11167. buffer << data;
  11168. Client cli("https://localhost:8080");
  11169. UploadFormDataItems items{
  11170. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11171. {"hello", "world", "", ""},
  11172. };
  11173. for (const char &c : " \t\r\n") {
  11174. auto res =
  11175. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  11176. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  11177. ASSERT_FALSE(res);
  11178. }
  11179. }
  11180. TEST(MultipartFormDataTest, PutFormData) {
  11181. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11182. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  11183. const ContentReader &content_reader) {
  11184. if (req.is_multipart_form_data()) {
  11185. std::vector<FormData> items;
  11186. content_reader(
  11187. [&](const FormData &file) {
  11188. items.push_back(file);
  11189. return true;
  11190. },
  11191. [&](const char *data, size_t data_length) {
  11192. items.back().content.append(data, data_length);
  11193. return true;
  11194. });
  11195. EXPECT_TRUE(std::string(items[0].name) == "document");
  11196. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  11197. EXPECT_TRUE(items[0].filename == "2MB_data");
  11198. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  11199. EXPECT_TRUE(items[1].name == "hello");
  11200. EXPECT_TRUE(items[1].content == "world");
  11201. EXPECT_TRUE(items[1].filename == "");
  11202. EXPECT_TRUE(items[1].content_type == "");
  11203. } else {
  11204. std::string body;
  11205. content_reader([&](const char *data, size_t data_length) {
  11206. body.append(data, data_length);
  11207. return true;
  11208. });
  11209. }
  11210. });
  11211. auto port = svr.bind_to_any_port("localhost");
  11212. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11213. auto se = detail::scope_exit([&] {
  11214. svr.stop();
  11215. t.join();
  11216. ASSERT_FALSE(svr.is_running());
  11217. });
  11218. svr.wait_until_ready();
  11219. {
  11220. std::string data(1024 * 1024 * 2, '&');
  11221. std::stringstream buffer;
  11222. buffer << data;
  11223. SSLClient cli("localhost", port);
  11224. cli.enable_server_certificate_verification(false);
  11225. UploadFormDataItems items{
  11226. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11227. {"hello", "world", "", ""},
  11228. };
  11229. auto res = cli.Put("/put", items);
  11230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11231. ASSERT_EQ(StatusCode::OK_200, res->status);
  11232. }
  11233. }
  11234. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  11235. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11236. svr.Put("/put_customboundary",
  11237. [&](const Request &req, const Response & /*res*/,
  11238. const ContentReader &content_reader) {
  11239. if (req.is_multipart_form_data()) {
  11240. std::vector<FormData> items;
  11241. content_reader(
  11242. [&](const FormData &file) {
  11243. items.push_back(file);
  11244. return true;
  11245. },
  11246. [&](const char *data, size_t data_length) {
  11247. items.back().content.append(data, data_length);
  11248. return true;
  11249. });
  11250. EXPECT_TRUE(std::string(items[0].name) == "document");
  11251. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  11252. EXPECT_TRUE(items[0].filename == "2MB_data");
  11253. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  11254. EXPECT_TRUE(items[1].name == "hello");
  11255. EXPECT_TRUE(items[1].content == "world");
  11256. EXPECT_TRUE(items[1].filename == "");
  11257. EXPECT_TRUE(items[1].content_type == "");
  11258. } else {
  11259. std::string body;
  11260. content_reader([&](const char *data, size_t data_length) {
  11261. body.append(data, data_length);
  11262. return true;
  11263. });
  11264. }
  11265. });
  11266. auto port = svr.bind_to_any_port("localhost");
  11267. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11268. auto se = detail::scope_exit([&] {
  11269. svr.stop();
  11270. t.join();
  11271. ASSERT_FALSE(svr.is_running());
  11272. });
  11273. svr.wait_until_ready();
  11274. {
  11275. std::string data(1024 * 1024 * 2, '&');
  11276. std::stringstream buffer;
  11277. buffer << data;
  11278. SSLClient cli("localhost", port);
  11279. cli.enable_server_certificate_verification(false);
  11280. UploadFormDataItems items{
  11281. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11282. {"hello", "world", "", ""},
  11283. };
  11284. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  11285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11286. ASSERT_EQ(StatusCode::OK_200, res->status);
  11287. }
  11288. }
  11289. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  11290. std::string data(1024 * 1024 * 2, '&');
  11291. std::stringstream buffer;
  11292. buffer << data;
  11293. Client cli("https://localhost:8080");
  11294. cli.enable_server_certificate_verification(false);
  11295. UploadFormDataItems items{
  11296. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11297. {"hello", "world", "", ""},
  11298. };
  11299. for (const char &c : " \t\r\n") {
  11300. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  11301. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  11302. ASSERT_FALSE(res);
  11303. }
  11304. }
  11305. TEST(MultipartFormDataTest, AlternateFilename) {
  11306. auto handled = false;
  11307. Server svr;
  11308. svr.Post("/test", [&](const Request &req, Response &res) {
  11309. ASSERT_EQ(2u, req.form.files.size());
  11310. ASSERT_EQ(1u, req.form.fields.size());
  11311. // Test files
  11312. const auto &file1 = req.form.get_file("file1");
  11313. ASSERT_EQ("file1", file1.name);
  11314. ASSERT_EQ("A.txt", file1.filename);
  11315. ASSERT_EQ("text/plain", file1.content_type);
  11316. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  11317. const auto &file2 = req.form.get_file("file2");
  11318. ASSERT_EQ("file2", file2.name);
  11319. ASSERT_EQ("a.html", file2.filename);
  11320. ASSERT_EQ("text/html", file2.content_type);
  11321. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  11322. file2.content);
  11323. // Test text field
  11324. const auto &text = req.form.get_field("text");
  11325. ASSERT_EQ("text default", text);
  11326. res.set_content("ok", "text/plain");
  11327. handled = true;
  11328. });
  11329. thread t = thread([&] { svr.listen(HOST, PORT); });
  11330. auto se = detail::scope_exit([&] {
  11331. svr.stop();
  11332. t.join();
  11333. ASSERT_FALSE(svr.is_running());
  11334. ASSERT_TRUE(handled);
  11335. });
  11336. svr.wait_until_ready();
  11337. auto req = "POST /test HTTP/1.1\r\n"
  11338. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11339. "Content-Length: 399\r\n"
  11340. "\r\n"
  11341. "----------\r\n"
  11342. "Content-Disposition: form-data; name=\"text\"\r\n"
  11343. "\r\n"
  11344. "text default\r\n"
  11345. "----------\r\n"
  11346. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  11347. "filename=\"a.txt\"; name=\"file1\"\r\n"
  11348. "Content-Type: text/plain\r\n"
  11349. "\r\n"
  11350. "Content of a.txt.\r\n"
  11351. "\r\n"
  11352. "----------\r\n"
  11353. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  11354. "\"a.html\"\r\n"
  11355. "Content-Type: text/html\r\n"
  11356. "\r\n"
  11357. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  11358. "\r\n"
  11359. "------------\r\n";
  11360. ASSERT_TRUE(send_request(1, req));
  11361. }
  11362. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  11363. auto handled = false;
  11364. Server svr;
  11365. svr.Post("/test", [&](const Request &req, Response &res) {
  11366. // Case-insensitive "utf-8''" prefix with a long value
  11367. const auto &file = req.form.get_file("file1");
  11368. ASSERT_EQ("file1", file.name);
  11369. // 8000 chars exercises both the Content-Disposition parser and the
  11370. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  11371. // Prior to the fix, std::regex_match on this header would cause O(N)
  11372. // stack recursion in libstdc++, leading to SIGSEGV.
  11373. std::string expected_filename(8000, 'A');
  11374. ASSERT_EQ(expected_filename, file.filename);
  11375. res.set_content("ok", "text/plain");
  11376. handled = true;
  11377. });
  11378. thread t = thread([&] { svr.listen(HOST, PORT); });
  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. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  11387. // Regression test for GHSA-qq6v-r583-3h69
  11388. std::string long_filename(8000, 'A');
  11389. std::string body = "----------\r\n"
  11390. "Content-Disposition: form-data; name=\"file1\"; "
  11391. "filename*=\"Utf-8''" +
  11392. long_filename +
  11393. "\"\r\n"
  11394. "\r\n"
  11395. "hello\r\n"
  11396. "------------\r\n";
  11397. auto req = "POST /test HTTP/1.1\r\n"
  11398. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11399. "Content-Length: " +
  11400. std::to_string(body.size()) + "\r\n\r\n" + body;
  11401. ASSERT_TRUE(send_request(1, req));
  11402. }
  11403. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  11404. auto handled = false;
  11405. Server svr;
  11406. svr.Post("/test", [&](const Request &req, Response &) {
  11407. ASSERT_EQ(2u, req.form.fields.size());
  11408. const auto &text1 = req.form.get_field("text1");
  11409. ASSERT_EQ("text1", text1);
  11410. const auto &text2 = req.form.get_field("text2");
  11411. ASSERT_EQ("text2", text2);
  11412. handled = true;
  11413. });
  11414. thread t = thread([&] { svr.listen(HOST, PORT); });
  11415. auto se = detail::scope_exit([&] {
  11416. svr.stop();
  11417. t.join();
  11418. ASSERT_FALSE(svr.is_running());
  11419. ASSERT_TRUE(handled);
  11420. });
  11421. svr.wait_until_ready();
  11422. auto req = "POST /test HTTP/1.1\r\n"
  11423. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11424. "Content-Length: 146\r\n"
  11425. "\r\n----------\r\n"
  11426. "Content-Disposition: form-data; name=\"text1\"\r\n"
  11427. "\r\n"
  11428. "text1"
  11429. "\r\n----------\r\n"
  11430. "Content-Disposition: form-data; name=\"text2\"\r\n"
  11431. "\r\n"
  11432. "text2"
  11433. "\r\n------------";
  11434. std::string response;
  11435. ASSERT_TRUE(send_request(1, req, &response));
  11436. ASSERT_EQ("200", response.substr(9, 3));
  11437. }
  11438. TEST(MultipartFormDataTest, ContentLength) {
  11439. auto handled = false;
  11440. Server svr;
  11441. svr.Post("/test", [&](const Request &req, Response &) {
  11442. ASSERT_EQ(2u, req.form.fields.size());
  11443. const auto &text1 = req.form.get_field("text1");
  11444. ASSERT_EQ("text1", text1);
  11445. const auto &text2 = req.form.get_field("text2");
  11446. ASSERT_EQ("text2", text2);
  11447. handled = true;
  11448. });
  11449. thread t = thread([&] { svr.listen(HOST, PORT); });
  11450. auto se = detail::scope_exit([&] {
  11451. svr.stop();
  11452. t.join();
  11453. ASSERT_FALSE(svr.is_running());
  11454. ASSERT_TRUE(handled);
  11455. });
  11456. svr.wait_until_ready();
  11457. auto req = "POST /test HTTP/1.1\r\n"
  11458. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11459. "Content-Length: 167\r\n"
  11460. "\r\n----------\r\n"
  11461. "Content-Disposition: form-data; name=\"text1\"\r\n"
  11462. "Content-Length: 5\r\n"
  11463. "\r\n"
  11464. "text1"
  11465. "\r\n----------\r\n"
  11466. "Content-Disposition: form-data; name=\"text2\"\r\n"
  11467. "\r\n"
  11468. "text2"
  11469. "\r\n------------\r\n";
  11470. std::string response;
  11471. ASSERT_TRUE(send_request(1, req, &response));
  11472. ASSERT_EQ("200", response.substr(9, 3));
  11473. }
  11474. TEST(MultipartFormDataTest, AccessPartHeaders) {
  11475. auto handled = false;
  11476. Server svr;
  11477. svr.Post("/test", [&](const Request &req, Response &) {
  11478. ASSERT_EQ(2u, req.form.fields.size());
  11479. const auto &text1 = req.form.get_field("text1");
  11480. ASSERT_EQ("text1", text1);
  11481. // TODO: Add header access for text fields if needed
  11482. const auto &text2 = req.form.get_field("text2");
  11483. ASSERT_EQ("text2", text2);
  11484. // TODO: Header access for text fields needs to be implemented
  11485. // auto &headers = it->second.headers;
  11486. // ASSERT_EQ(3U, headers.size());
  11487. // auto custom_header = headers.find("x-whatever");
  11488. // ASSERT_TRUE(custom_header != headers.end());
  11489. // ASSERT_NE("customvalue", custom_header->second);
  11490. // ASSERT_EQ("CustomValue", custom_header->second);
  11491. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  11492. handled = true;
  11493. });
  11494. thread t = thread([&] { svr.listen(HOST, PORT); });
  11495. auto se = detail::scope_exit([&] {
  11496. svr.stop();
  11497. t.join();
  11498. ASSERT_FALSE(svr.is_running());
  11499. ASSERT_TRUE(handled);
  11500. });
  11501. svr.wait_until_ready();
  11502. auto req = "POST /test HTTP/1.1\r\n"
  11503. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11504. "Content-Length: 232\r\n"
  11505. "\r\n----------\r\n"
  11506. "Content-Disposition: form-data; name=\"text1\"\r\n"
  11507. "Content-Length: 5\r\n"
  11508. "X-Test: 1\r\n"
  11509. "\r\n"
  11510. "text1"
  11511. "\r\n----------\r\n"
  11512. "Content-Disposition: form-data; name=\"text2\"\r\n"
  11513. "Content-Type: text/plain\r\n"
  11514. "X-Whatever: CustomValue\r\n"
  11515. "\r\n"
  11516. "text2"
  11517. "\r\n------------\r\n"
  11518. "That should be disregarded. Not even read";
  11519. std::string response;
  11520. ASSERT_TRUE(send_request(1, req, &response));
  11521. ASSERT_EQ("200", response.substr(9, 3));
  11522. }
  11523. TEST(MultipartFormDataTest, LargeHeader) {
  11524. auto handled = false;
  11525. Server svr;
  11526. svr.Post("/test", [&](const Request &req, Response &) {
  11527. ASSERT_EQ(1u, req.form.fields.size());
  11528. const auto &text = req.form.get_field("name1");
  11529. ASSERT_EQ("text1", text);
  11530. handled = true;
  11531. });
  11532. thread t = thread([&] { svr.listen(HOST, PORT); });
  11533. auto se = detail::scope_exit([&] {
  11534. svr.stop();
  11535. t.join();
  11536. ASSERT_FALSE(svr.is_running());
  11537. ASSERT_TRUE(handled);
  11538. });
  11539. svr.wait_until_ready();
  11540. auto boundary = std::string("cpp-httplib-multipart-data");
  11541. std::string content = "--" + boundary +
  11542. "\r\n"
  11543. "Content-Disposition: form-data; name=\"name1\"\r\n"
  11544. "\r\n"
  11545. "text1\r\n"
  11546. "--" +
  11547. boundary + "--\r\n";
  11548. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  11549. "Content-Type: multipart/form-data;boundary=" +
  11550. boundary +
  11551. "\r\n"
  11552. "Content-Length: " +
  11553. std::to_string(content.size()) +
  11554. "\r\n"
  11555. "Dummy-Header: ";
  11556. std::string header_suffix = "\r\n"
  11557. "\r\n";
  11558. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  11559. size_t header_dummy_size =
  11560. read_buff_size -
  11561. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  11562. auto header_dummy = std::string(header_dummy_size, '@');
  11563. auto req = header_prefix + header_dummy + header_suffix + content;
  11564. std::string response;
  11565. ASSERT_TRUE(send_request(1, req, &response));
  11566. ASSERT_EQ("200", response.substr(9, 3));
  11567. }
  11568. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  11569. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  11570. // (not chunked Transfer-Encoding) after the streaming refactor.
  11571. auto handled = false;
  11572. Server svr;
  11573. svr.Post("/upload", [&](const Request &req, Response &res) {
  11574. auto cl_it = req.headers.find("Content-Length");
  11575. EXPECT_TRUE(cl_it != req.headers.end());
  11576. auto te_it = req.headers.find("Transfer-Encoding");
  11577. EXPECT_TRUE(te_it == req.headers.end());
  11578. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  11579. res.set_content("ok", "text/plain");
  11580. handled = true;
  11581. });
  11582. auto port = svr.bind_to_any_port(HOST);
  11583. auto t = thread([&] { svr.listen_after_bind(); });
  11584. auto se = detail::scope_exit([&] {
  11585. svr.stop();
  11586. t.join();
  11587. ASSERT_FALSE(svr.is_running());
  11588. ASSERT_TRUE(handled);
  11589. });
  11590. svr.wait_until_ready();
  11591. UploadFormDataItems items = {
  11592. {"field1", "hello", "", "text/plain"},
  11593. {"file1", "world", "test.txt", "application/octet-stream"},
  11594. };
  11595. Client cli(HOST, port);
  11596. auto res = cli.Post("/upload", {}, items);
  11597. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11598. EXPECT_EQ(StatusCode::OK_200, res->status);
  11599. }
  11600. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  11601. // Verify that make_multipart_content_provider coalesces many small segments
  11602. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  11603. constexpr size_t kItemCount = 1000;
  11604. UploadFormDataItems items;
  11605. items.reserve(kItemCount);
  11606. for (size_t i = 0; i < kItemCount; i++) {
  11607. items.push_back(
  11608. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  11609. }
  11610. const std::string boundary = "----test-boundary";
  11611. auto content_length = detail::get_multipart_content_length(items, boundary);
  11612. auto provider = detail::make_multipart_content_provider(items, boundary);
  11613. // Drive the provider the same way write_content_with_progress does
  11614. size_t write_count = 0;
  11615. size_t total_bytes = 0;
  11616. DataSink sink;
  11617. size_t offset = 0;
  11618. sink.write = [&](const char *d, size_t l) -> bool {
  11619. (void)d;
  11620. write_count++;
  11621. total_bytes += l;
  11622. offset += l;
  11623. return true;
  11624. };
  11625. sink.is_writable = []() -> bool { return true; };
  11626. while (offset < content_length) {
  11627. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  11628. }
  11629. EXPECT_EQ(content_length, total_bytes);
  11630. // The total number of segments is 3 * kItemCount + 1 = 3001.
  11631. // With buffering into 64KB blocks, write_count should be much smaller.
  11632. auto segment_count = 3 * kItemCount + 1;
  11633. EXPECT_LT(write_count, segment_count / 10);
  11634. }
  11635. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  11636. // Integration test: send many UploadFormDataItems and verify the server
  11637. // receives all of them correctly (#2410).
  11638. constexpr size_t kItemCount = 500;
  11639. auto handled = false;
  11640. Server svr;
  11641. svr.Post("/upload", [&](const Request &req, Response &res) {
  11642. EXPECT_EQ(kItemCount, req.form.fields.size());
  11643. for (size_t i = 0; i < kItemCount; i++) {
  11644. auto key = "field" + std::to_string(i);
  11645. auto val = "value" + std::to_string(i);
  11646. auto it = req.form.fields.find(key);
  11647. if (it != req.form.fields.end()) {
  11648. EXPECT_EQ(val, it->second.content);
  11649. } else {
  11650. ADD_FAILURE() << "Missing field: " << key;
  11651. }
  11652. }
  11653. res.set_content("ok", "text/plain");
  11654. handled = true;
  11655. });
  11656. auto port = svr.bind_to_any_port(HOST);
  11657. auto t = thread([&] { svr.listen_after_bind(); });
  11658. auto se = detail::scope_exit([&] {
  11659. svr.stop();
  11660. t.join();
  11661. ASSERT_FALSE(svr.is_running());
  11662. ASSERT_TRUE(handled);
  11663. });
  11664. svr.wait_until_ready();
  11665. UploadFormDataItems items;
  11666. items.reserve(kItemCount);
  11667. for (size_t i = 0; i < kItemCount; i++) {
  11668. items.push_back(
  11669. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  11670. }
  11671. Client cli(HOST, port);
  11672. auto res = cli.Post("/upload", items);
  11673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11674. EXPECT_EQ(StatusCode::OK_200, res->status);
  11675. }
  11676. TEST(MultipartFormDataTest, MakeFileProvider) {
  11677. // Verify make_file_provider sends a file's contents correctly.
  11678. const std::string file_content(4096, 'Z');
  11679. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  11680. {
  11681. std::ofstream ofs(tmp_path, std::ios::binary);
  11682. ofs.write(file_content.data(),
  11683. static_cast<std::streamsize>(file_content.size()));
  11684. }
  11685. auto handled = false;
  11686. Server svr;
  11687. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  11688. const ContentReader &content_reader) {
  11689. ASSERT_TRUE(req.is_multipart_form_data());
  11690. std::vector<FormData> items;
  11691. content_reader(
  11692. [&](const FormData &file) {
  11693. items.push_back(file);
  11694. return true;
  11695. },
  11696. [&](const char *data, size_t data_length) {
  11697. items.back().content.append(data, data_length);
  11698. return true;
  11699. });
  11700. ASSERT_EQ(1u, items.size());
  11701. EXPECT_EQ("myfile", items[0].name);
  11702. EXPECT_EQ("data.bin", items[0].filename);
  11703. EXPECT_EQ("application/octet-stream", items[0].content_type);
  11704. EXPECT_EQ(file_content, items[0].content);
  11705. handled = true;
  11706. });
  11707. auto port = svr.bind_to_any_port(HOST);
  11708. auto t = thread([&] { svr.listen_after_bind(); });
  11709. auto se = detail::scope_exit([&] {
  11710. svr.stop();
  11711. t.join();
  11712. ASSERT_FALSE(svr.is_running());
  11713. ASSERT_TRUE(handled);
  11714. std::remove(tmp_path.c_str());
  11715. });
  11716. svr.wait_until_ready();
  11717. FormDataProviderItems providers;
  11718. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  11719. "application/octet-stream"));
  11720. Client cli(HOST, port);
  11721. auto res = cli.Post("/upload", {}, {}, providers);
  11722. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11723. EXPECT_EQ(StatusCode::OK_200, res->status);
  11724. }
  11725. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  11726. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  11727. // (100) headers is rejected with a 400 Bad Request response.
  11728. Server svr;
  11729. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  11730. res.set_content("ok", "text/plain");
  11731. });
  11732. thread t = thread([&] { svr.listen(HOST, PORT); });
  11733. auto se = detail::scope_exit([&] {
  11734. svr.stop();
  11735. t.join();
  11736. ASSERT_FALSE(svr.is_running());
  11737. });
  11738. svr.wait_until_ready();
  11739. // Build a multipart part with 101 custom headers (exceeding
  11740. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  11741. std::stringstream body;
  11742. body << "--simpleboundary\r\n"
  11743. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  11744. for (int i = 0; i < 101; i++) {
  11745. body << "X-Custom-Header-" << i << ": value\r\n";
  11746. }
  11747. body << "\r\n"
  11748. << "value1\r\n"
  11749. << "--simpleboundary--\r\n";
  11750. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  11751. Client cli(HOST, PORT);
  11752. auto res = cli.Post("/post", body.str(), content_type.c_str());
  11753. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11754. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  11755. }
  11756. TEST(MakeFileBodyTest, Basic) {
  11757. const std::string file_content(4096, 'Z');
  11758. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  11759. {
  11760. std::ofstream ofs(tmp_path, std::ios::binary);
  11761. ofs.write(file_content.data(),
  11762. static_cast<std::streamsize>(file_content.size()));
  11763. }
  11764. auto handled = false;
  11765. Server svr;
  11766. svr.Post("/upload", [&](const Request &req, Response &res) {
  11767. EXPECT_EQ(file_content, req.body);
  11768. handled = true;
  11769. res.status = StatusCode::OK_200;
  11770. });
  11771. auto port = svr.bind_to_any_port(HOST);
  11772. auto t = thread([&] { svr.listen_after_bind(); });
  11773. auto se = detail::scope_exit([&] {
  11774. svr.stop();
  11775. t.join();
  11776. ASSERT_FALSE(svr.is_running());
  11777. ASSERT_TRUE(handled);
  11778. std::remove(tmp_path.c_str());
  11779. });
  11780. svr.wait_until_ready();
  11781. auto fb = make_file_body(tmp_path);
  11782. ASSERT_GT(fb.first, 0u);
  11783. Client cli(HOST, port);
  11784. auto res =
  11785. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  11786. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11787. EXPECT_EQ(StatusCode::OK_200, res->status);
  11788. }
  11789. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  11790. static constexpr unsigned int number_of_tasks{1000000};
  11791. std::atomic_uint count{0};
  11792. std::unique_ptr<TaskQueue> task_queue{
  11793. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  11794. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  11795. auto queued = task_queue->enqueue(
  11796. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  11797. EXPECT_TRUE(queued);
  11798. }
  11799. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  11800. task_queue->shutdown();
  11801. #else
  11802. EXPECT_NO_THROW(task_queue->shutdown());
  11803. #endif
  11804. EXPECT_EQ(number_of_tasks, count.load());
  11805. }
  11806. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  11807. static constexpr unsigned int number_of_tasks{1000000};
  11808. static constexpr unsigned int qlimit{2};
  11809. unsigned int queued_count{0};
  11810. std::atomic_uint count{0};
  11811. std::unique_ptr<TaskQueue> task_queue{
  11812. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  11813. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  11814. if (task_queue->enqueue(
  11815. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  11816. queued_count++;
  11817. }
  11818. }
  11819. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  11820. task_queue->shutdown();
  11821. #else
  11822. EXPECT_NO_THROW(task_queue->shutdown());
  11823. #endif
  11824. EXPECT_EQ(queued_count, count.load());
  11825. EXPECT_TRUE(queued_count <= number_of_tasks);
  11826. EXPECT_TRUE(queued_count >= qlimit);
  11827. }
  11828. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  11829. // Use a short idle timeout so a dynamic thread spawns, times out and
  11830. // exits during the test, and the pool keeps working afterwards.
  11831. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  11832. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  11833. /*idle_timeout_sec=*/1}};
  11834. std::atomic_uint count{0};
  11835. std::condition_variable cv;
  11836. std::mutex mtx;
  11837. bool release = false;
  11838. // Block the base thread so the second task spawns a dynamic thread.
  11839. EXPECT_TRUE(task_queue->enqueue([&] {
  11840. std::unique_lock<std::mutex> lock(mtx);
  11841. while (!release) {
  11842. cv.wait(lock);
  11843. }
  11844. count++;
  11845. }));
  11846. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  11847. // Let the dynamic thread finish its task and exceed the idle timeout.
  11848. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  11849. {
  11850. std::unique_lock<std::mutex> lock(mtx);
  11851. release = true;
  11852. }
  11853. cv.notify_all();
  11854. // The pool must still accept and run tasks after the dynamic thread exited.
  11855. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  11856. task_queue->shutdown();
  11857. EXPECT_EQ(3u, count.load());
  11858. }
  11859. TEST(TaskQueueTest, MaxQueuedRequests) {
  11860. static constexpr unsigned int qlimit{3};
  11861. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  11862. std::condition_variable sem_cv;
  11863. std::mutex sem_mtx;
  11864. int credits = 0;
  11865. bool queued;
  11866. /* Fill up the queue with tasks that will block until we give them credits to
  11867. * complete. */
  11868. for (unsigned int n = 0; n <= qlimit;) {
  11869. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  11870. std::unique_lock<std::mutex> lock(sem_mtx);
  11871. while (credits <= 0) {
  11872. sem_cv.wait(lock);
  11873. }
  11874. /* Consume the credit and signal the test code if they are all gone. */
  11875. if (--credits == 0) { sem_cv.notify_one(); }
  11876. });
  11877. if (n < qlimit) {
  11878. /* The first qlimit enqueues must succeed. */
  11879. EXPECT_TRUE(queued);
  11880. } else {
  11881. /* The last one will succeed only when the worker thread
  11882. * starts and dequeues the first blocking task. Although
  11883. * not necessary for the correctness of this test, we sleep for
  11884. * a short while to avoid busy waiting. */
  11885. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  11886. }
  11887. if (queued) { n++; }
  11888. }
  11889. /* Further enqueues must fail since the queue is full. */
  11890. for (auto i = 0; i < 4; i++) {
  11891. queued = task_queue->enqueue([] {});
  11892. EXPECT_FALSE(queued);
  11893. }
  11894. /* Give the credits to allow the previous tasks to complete. */
  11895. {
  11896. std::unique_lock<std::mutex> lock(sem_mtx);
  11897. credits += qlimit + 1;
  11898. }
  11899. sem_cv.notify_all();
  11900. /* Wait for all the credits to be consumed. */
  11901. {
  11902. std::unique_lock<std::mutex> lock(sem_mtx);
  11903. while (credits > 0) {
  11904. sem_cv.wait(lock);
  11905. }
  11906. }
  11907. /* Check that we are able again to enqueue at least qlimit tasks. */
  11908. for (unsigned int i = 0; i < qlimit; i++) {
  11909. queued = task_queue->enqueue([] {});
  11910. EXPECT_TRUE(queued);
  11911. }
  11912. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  11913. task_queue->shutdown();
  11914. #else
  11915. EXPECT_NO_THROW(task_queue->shutdown());
  11916. #endif
  11917. }
  11918. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  11919. Server svr;
  11920. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11921. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  11922. });
  11923. svr.Get("/hello", [](const Request &req, Response &res) {
  11924. res.set_content(req.get_param_value("key"), "text/plain");
  11925. });
  11926. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11927. auto se = detail::scope_exit([&] {
  11928. svr.stop();
  11929. thread.join();
  11930. ASSERT_FALSE(svr.is_running());
  11931. });
  11932. svr.wait_until_ready();
  11933. {
  11934. Client cli(HOST, PORT);
  11935. cli.set_follow_location(true);
  11936. auto res = cli.Get("/");
  11937. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11938. EXPECT_EQ(StatusCode::OK_200, res->status);
  11939. EXPECT_EQ("val&key2=val2", res->body);
  11940. }
  11941. }
  11942. #endif
  11943. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  11944. Server svr;
  11945. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11946. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  11947. });
  11948. svr.Get("/hello", [](const Request &req, Response &res) {
  11949. res.set_content(req.get_param_value("key"), "text/plain");
  11950. });
  11951. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11952. auto se = detail::scope_exit([&] {
  11953. svr.stop();
  11954. thread.join();
  11955. ASSERT_FALSE(svr.is_running());
  11956. });
  11957. svr.wait_until_ready();
  11958. {
  11959. Client cli(HOST, PORT);
  11960. cli.set_follow_location(true);
  11961. auto res = cli.Get("/");
  11962. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11963. EXPECT_EQ(StatusCode::OK_200, res->status);
  11964. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  11965. }
  11966. }
  11967. TEST(RedirectTest, RedirectWithPlusInPath) {
  11968. Server svr;
  11969. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11970. res.set_redirect("/a+b");
  11971. });
  11972. // Route pattern uses regex; escape + as \\+
  11973. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  11974. res.set_content(req.path, "text/plain");
  11975. });
  11976. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11977. auto se = detail::scope_exit([&] {
  11978. svr.stop();
  11979. thread.join();
  11980. ASSERT_FALSE(svr.is_running());
  11981. });
  11982. svr.wait_until_ready();
  11983. {
  11984. Client cli(HOST, PORT);
  11985. cli.set_follow_location(true);
  11986. auto res = cli.Get("/");
  11987. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11988. EXPECT_EQ(StatusCode::OK_200, res->status);
  11989. EXPECT_EQ("/a+b", res->body);
  11990. }
  11991. }
  11992. #ifdef CPPHTTPLIB_SSL_ENABLED
  11993. TEST(RedirectTest, Issue2185_Online) {
  11994. SSLClient client("github.com");
  11995. client.set_follow_location(true);
  11996. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  11997. "Coollab-Windows.zip");
  11998. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11999. EXPECT_EQ(StatusCode::OK_200, res->status);
  12000. EXPECT_EQ(9920427U, res->body.size());
  12001. }
  12002. #endif
  12003. TEST(VulnerabilityTest, CRLFInjection) {
  12004. Server svr;
  12005. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  12006. res.set_content("Hello 1", "text/plain");
  12007. });
  12008. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  12009. res.set_content("Hello 2", "text/plain");
  12010. });
  12011. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  12012. res.set_content("Hello 3", "text/plain");
  12013. });
  12014. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  12015. res.set_content("Hello 4", "text/plain");
  12016. });
  12017. svr.set_logger([](const Request &req, const Response & /*res*/) {
  12018. for (const auto &x : req.headers) {
  12019. auto key = x.first;
  12020. EXPECT_STRNE("evil", key.c_str());
  12021. }
  12022. });
  12023. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12024. auto se = detail::scope_exit([&] {
  12025. svr.stop();
  12026. thread.join();
  12027. ASSERT_FALSE(svr.is_running());
  12028. });
  12029. svr.wait_until_ready();
  12030. {
  12031. Client cli(HOST, PORT);
  12032. cli.Post("/test1", "A=B",
  12033. "application/x-www-form-urlencoded\r\nevil: hello1");
  12034. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  12035. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  12036. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  12037. }
  12038. }
  12039. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  12040. auto server_thread = std::thread([] {
  12041. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12042. default_socket_options(srv);
  12043. sockaddr_in addr{};
  12044. addr.sin_family = AF_INET;
  12045. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  12046. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12047. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12048. ::listen(srv, 1);
  12049. sockaddr_in cli_addr{};
  12050. socklen_t cli_len = sizeof(cli_addr);
  12051. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12052. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  12053. std::string buf_all;
  12054. char buf[2048];
  12055. ssize_t n;
  12056. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  12057. buf_all.append(buf, static_cast<size_t>(n));
  12058. size_t pos;
  12059. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  12060. auto request_block = buf_all.substr(0, pos + 4); // include separator
  12061. auto e = request_block.find("\r\n");
  12062. if (e != std::string::npos) {
  12063. auto request_line = request_block.substr(0, e);
  12064. std::string msg =
  12065. "CRLF injection detected in request line: '" + request_line + "'";
  12066. EXPECT_FALSE(true) << msg;
  12067. }
  12068. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  12069. ::send(cli,
  12070. #ifdef _WIN32
  12071. static_cast<const char *>(resp.c_str()),
  12072. static_cast<int>(resp.size()),
  12073. #else
  12074. resp.c_str(), resp.size(),
  12075. #endif
  12076. 0);
  12077. buf_all.erase(0, pos + 4);
  12078. }
  12079. }
  12080. detail::close_socket(cli);
  12081. detail::close_socket(srv);
  12082. });
  12083. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12084. auto cli = Client("127.0.0.1", PORT + 1);
  12085. auto headers = Headers{
  12086. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  12087. {"Connection", "keep-alive"}};
  12088. auto res = cli.Get("/hi", headers);
  12089. EXPECT_FALSE(res);
  12090. EXPECT_EQ(Error::InvalidHeaders, res.error());
  12091. server_thread.join();
  12092. }
  12093. TEST(PathParamsTest, StaticMatch) {
  12094. const auto pattern = "/users/all";
  12095. detail::PathParamsMatcher matcher(pattern);
  12096. Request request;
  12097. request.path = "/users/all";
  12098. ASSERT_TRUE(matcher.match(request));
  12099. std::unordered_map<std::string, std::string> expected_params = {};
  12100. EXPECT_EQ(request.path_params, expected_params);
  12101. }
  12102. TEST(PathParamsTest, StaticMismatch) {
  12103. const auto pattern = "/users/all";
  12104. detail::PathParamsMatcher matcher(pattern);
  12105. Request request;
  12106. request.path = "/users/1";
  12107. ASSERT_FALSE(matcher.match(request));
  12108. }
  12109. TEST(PathParamsTest, SingleParamInTheMiddle) {
  12110. const auto pattern = "/users/:id/subscriptions";
  12111. detail::PathParamsMatcher matcher(pattern);
  12112. Request request;
  12113. request.path = "/users/42/subscriptions";
  12114. ASSERT_TRUE(matcher.match(request));
  12115. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  12116. EXPECT_EQ(request.path_params, expected_params);
  12117. }
  12118. TEST(PathParamsTest, SingleParamInTheEnd) {
  12119. const auto pattern = "/users/:id";
  12120. detail::PathParamsMatcher matcher(pattern);
  12121. Request request;
  12122. request.path = "/users/24";
  12123. ASSERT_TRUE(matcher.match(request));
  12124. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  12125. EXPECT_EQ(request.path_params, expected_params);
  12126. }
  12127. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  12128. const auto pattern = "/users/:id/";
  12129. detail::PathParamsMatcher matcher(pattern);
  12130. Request request;
  12131. request.path = "/users/42/";
  12132. ASSERT_TRUE(matcher.match(request));
  12133. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  12134. EXPECT_EQ(request.path_params, expected_params);
  12135. }
  12136. TEST(PathParamsTest, EmptyParam) {
  12137. const auto pattern = "/users/:id/";
  12138. detail::PathParamsMatcher matcher(pattern);
  12139. Request request;
  12140. request.path = "/users//";
  12141. ASSERT_TRUE(matcher.match(request));
  12142. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  12143. EXPECT_EQ(request.path_params, expected_params);
  12144. }
  12145. TEST(PathParamsTest, FragmentMismatch) {
  12146. const auto pattern = "/users/:id/";
  12147. detail::PathParamsMatcher matcher(pattern);
  12148. Request request;
  12149. request.path = "/admins/24/";
  12150. ASSERT_FALSE(matcher.match(request));
  12151. }
  12152. TEST(PathParamsTest, ExtraFragments) {
  12153. const auto pattern = "/users/:id";
  12154. detail::PathParamsMatcher matcher(pattern);
  12155. Request request;
  12156. request.path = "/users/42/subscriptions";
  12157. ASSERT_FALSE(matcher.match(request));
  12158. }
  12159. TEST(PathParamsTest, MissingTrailingParam) {
  12160. const auto pattern = "/users/:id";
  12161. detail::PathParamsMatcher matcher(pattern);
  12162. Request request;
  12163. request.path = "/users";
  12164. ASSERT_FALSE(matcher.match(request));
  12165. }
  12166. TEST(PathParamsTest, MissingParamInTheMiddle) {
  12167. const auto pattern = "/users/:id/subscriptions";
  12168. detail::PathParamsMatcher matcher(pattern);
  12169. Request request;
  12170. request.path = "/users/subscriptions";
  12171. ASSERT_FALSE(matcher.match(request));
  12172. }
  12173. TEST(PathParamsTest, MultipleParams) {
  12174. const auto pattern = "/users/:userid/subscriptions/:subid";
  12175. detail::PathParamsMatcher matcher(pattern);
  12176. Request request;
  12177. request.path = "/users/42/subscriptions/2";
  12178. ASSERT_TRUE(matcher.match(request));
  12179. std::unordered_map<std::string, std::string> expected_params = {
  12180. {"userid", "42"}, {"subid", "2"}};
  12181. EXPECT_EQ(request.path_params, expected_params);
  12182. }
  12183. TEST(PathParamsTest, SequenceOfParams) {
  12184. const auto pattern = "/values/:x/:y/:z";
  12185. detail::PathParamsMatcher matcher(pattern);
  12186. Request request;
  12187. request.path = "/values/1/2/3";
  12188. ASSERT_TRUE(matcher.match(request));
  12189. std::unordered_map<std::string, std::string> expected_params = {
  12190. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  12191. EXPECT_EQ(request.path_params, expected_params);
  12192. }
  12193. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  12194. const auto pattern = "/prefix:suffix";
  12195. detail::PathParamsMatcher matcher(pattern);
  12196. Request request;
  12197. request.path = "/prefix:suffix";
  12198. ASSERT_TRUE(matcher.match(request));
  12199. const std::unordered_map<std::string, std::string> expected_params = {};
  12200. EXPECT_EQ(request.path_params, expected_params);
  12201. }
  12202. TEST(ParseUrlTest, VariousPatterns) {
  12203. {
  12204. detail::UrlComponents uc;
  12205. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  12206. EXPECT_EQ("http", uc.scheme);
  12207. EXPECT_EQ("example.com", uc.host);
  12208. EXPECT_EQ("8080", uc.port);
  12209. EXPECT_EQ("/path", uc.path);
  12210. EXPECT_EQ("?q=1", uc.query);
  12211. }
  12212. {
  12213. detail::UrlComponents uc;
  12214. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  12215. EXPECT_EQ("https", uc.scheme);
  12216. EXPECT_EQ("example.com", uc.host);
  12217. EXPECT_TRUE(uc.port.empty());
  12218. EXPECT_EQ("/path", uc.path);
  12219. }
  12220. {
  12221. detail::UrlComponents uc;
  12222. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  12223. EXPECT_EQ("::1", uc.host);
  12224. EXPECT_EQ("8080", uc.port);
  12225. EXPECT_EQ("/path", uc.path);
  12226. }
  12227. {
  12228. detail::UrlComponents uc;
  12229. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  12230. }
  12231. {
  12232. detail::UrlComponents uc;
  12233. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  12234. EXPECT_TRUE(uc.scheme.empty());
  12235. EXPECT_EQ("example.com", uc.host);
  12236. EXPECT_EQ("/path", uc.path);
  12237. EXPECT_EQ("?q=1", uc.query);
  12238. }
  12239. {
  12240. detail::UrlComponents uc;
  12241. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  12242. EXPECT_TRUE(uc.host.empty());
  12243. EXPECT_EQ("/path", uc.path);
  12244. EXPECT_EQ("?q=1", uc.query);
  12245. }
  12246. {
  12247. detail::UrlComponents uc;
  12248. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  12249. EXPECT_EQ("example.com", uc.host);
  12250. EXPECT_EQ("8080", uc.port);
  12251. }
  12252. {
  12253. // Unix socket path — must not be parsed as host
  12254. detail::UrlComponents uc;
  12255. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  12256. EXPECT_TRUE(uc.host.empty());
  12257. }
  12258. {
  12259. detail::UrlComponents uc;
  12260. ASSERT_TRUE(detail::parse_url("", uc));
  12261. EXPECT_TRUE(uc.host.empty());
  12262. EXPECT_TRUE(uc.path.empty());
  12263. }
  12264. {
  12265. detail::UrlComponents uc;
  12266. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  12267. }
  12268. {
  12269. detail::UrlComponents uc;
  12270. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  12271. }
  12272. {
  12273. // Accepted by parse_url; callers restrict to http/https
  12274. detail::UrlComponents uc;
  12275. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  12276. EXPECT_EQ("ftp", uc.scheme);
  12277. }
  12278. {
  12279. detail::UrlComponents uc;
  12280. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  12281. }
  12282. {
  12283. detail::UrlComponents uc;
  12284. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  12285. }
  12286. }
  12287. TEST(ParseUrlTest, FragmentHandling) {
  12288. {
  12289. detail::UrlComponents uc;
  12290. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  12291. EXPECT_EQ("/path", uc.path);
  12292. EXPECT_TRUE(uc.query.empty());
  12293. }
  12294. {
  12295. detail::UrlComponents uc;
  12296. ASSERT_TRUE(detail::parse_url("#frag", uc));
  12297. EXPECT_TRUE(uc.path.empty());
  12298. EXPECT_TRUE(uc.query.empty());
  12299. }
  12300. }
  12301. TEST(ParseUrlTest, UserinfoHandling) {
  12302. // Userinfo with @ but no colon — host includes @
  12303. detail::UrlComponents uc;
  12304. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  12305. EXPECT_EQ("user@host.com", uc.host);
  12306. EXPECT_EQ("/path", uc.path);
  12307. }
  12308. TEST(ParseUrlTest, IPv6EdgeCases) {
  12309. {
  12310. detail::UrlComponents uc;
  12311. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  12312. EXPECT_TRUE(uc.scheme.empty());
  12313. EXPECT_EQ("::1", uc.host);
  12314. EXPECT_EQ("8080", uc.port);
  12315. }
  12316. {
  12317. // Zone ID '%25' is not in [a-fA-F0-9:]
  12318. detail::UrlComponents uc;
  12319. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  12320. }
  12321. }
  12322. TEST(ParseUrlTest, SchemeEdgeCases) {
  12323. {
  12324. detail::UrlComponents uc;
  12325. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  12326. }
  12327. {
  12328. detail::UrlComponents uc;
  12329. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  12330. }
  12331. {
  12332. detail::UrlComponents uc;
  12333. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  12334. }
  12335. }
  12336. TEST(ParseUrlTest, PortEdgeCases) {
  12337. {
  12338. detail::UrlComponents uc;
  12339. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  12340. EXPECT_TRUE(uc.port.empty());
  12341. EXPECT_EQ("/path", uc.path);
  12342. }
  12343. {
  12344. // parse_url accepts any port string; validation is done by parse_port
  12345. detail::UrlComponents uc;
  12346. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  12347. EXPECT_EQ("abc", uc.port);
  12348. }
  12349. }
  12350. TEST(ParseUrlTest, WebSocketPatterns) {
  12351. {
  12352. detail::UrlComponents uc;
  12353. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  12354. EXPECT_EQ("ws", uc.scheme);
  12355. EXPECT_EQ("echo.example.com", uc.host);
  12356. EXPECT_EQ("8080", uc.port);
  12357. EXPECT_EQ("/ws", uc.path);
  12358. }
  12359. {
  12360. detail::UrlComponents uc;
  12361. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  12362. EXPECT_EQ("wss", uc.scheme);
  12363. EXPECT_EQ("echo.example.com", uc.host);
  12364. EXPECT_TRUE(uc.port.empty());
  12365. EXPECT_EQ("/ws", uc.path);
  12366. }
  12367. }
  12368. TEST(ParseUrlTest, QueryOnly) {
  12369. detail::UrlComponents uc;
  12370. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  12371. EXPECT_TRUE(uc.host.empty());
  12372. EXPECT_TRUE(uc.path.empty());
  12373. EXPECT_EQ("?q=1&r=2", uc.query);
  12374. }
  12375. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  12376. detail::UrlComponents uc;
  12377. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  12378. EXPECT_TRUE(uc.scheme.empty());
  12379. EXPECT_EQ("example.com", uc.host);
  12380. EXPECT_EQ("443", uc.port);
  12381. EXPECT_EQ("/path", uc.path);
  12382. }
  12383. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  12384. // If ipv6 regex working, regex match codepath is taken.
  12385. // else port will default to 80 in Client impl
  12386. int clientImplMagicPort = 80;
  12387. int port = 4321;
  12388. // above ports must be different to avoid false negative
  12389. EXPECT_NE(clientImplMagicPort, port);
  12390. std::string ipV6TestURL = "http://[ff06::c3]";
  12391. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  12392. CLIENT_PRIVATE_KEY_FILE);
  12393. EXPECT_EQ(cli.port(), port);
  12394. }
  12395. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  12396. auto file_path = "./www/dir/index.html";
  12397. auto dir_path = "./www/dir";
  12398. detail::FileStat stat_file(file_path);
  12399. EXPECT_TRUE(stat_file.is_file());
  12400. EXPECT_FALSE(stat_file.is_dir());
  12401. detail::FileStat stat_dir(dir_path);
  12402. EXPECT_FALSE(stat_dir.is_file());
  12403. EXPECT_TRUE(stat_dir.is_dir());
  12404. }
  12405. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  12406. // IPv4 with default HTTP port (80)
  12407. EXPECT_EQ("example.com",
  12408. detail::make_host_and_port_string("example.com", 80, false));
  12409. // IPv4 with default HTTPS port (443)
  12410. EXPECT_EQ("example.com",
  12411. detail::make_host_and_port_string("example.com", 443, true));
  12412. // IPv4 with non-default HTTP port
  12413. EXPECT_EQ("example.com:8080",
  12414. detail::make_host_and_port_string("example.com", 8080, false));
  12415. // IPv4 with non-default HTTPS port
  12416. EXPECT_EQ("example.com:8443",
  12417. detail::make_host_and_port_string("example.com", 8443, true));
  12418. // IPv6 with default HTTP port (80)
  12419. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  12420. // IPv6 with default HTTPS port (443)
  12421. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  12422. // IPv6 with non-default HTTP port
  12423. EXPECT_EQ("[::1]:8080",
  12424. detail::make_host_and_port_string("::1", 8080, false));
  12425. // IPv6 with non-default HTTPS port
  12426. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  12427. // IPv6 full address with default port
  12428. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  12429. detail::make_host_and_port_string(
  12430. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  12431. // IPv6 full address with non-default port
  12432. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  12433. detail::make_host_and_port_string(
  12434. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  12435. // IPv6 localhost with non-default port
  12436. EXPECT_EQ("[::1]:3000",
  12437. detail::make_host_and_port_string("::1", 3000, false));
  12438. // IPv6 with zone ID (link-local address) with default port
  12439. EXPECT_EQ("[fe80::1%eth0]",
  12440. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  12441. // IPv6 with zone ID (link-local address) with non-default port
  12442. EXPECT_EQ("[fe80::1%eth0]:8080",
  12443. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  12444. // Edge case: Port 443 with is_ssl=false (should add port)
  12445. EXPECT_EQ("example.com:443",
  12446. detail::make_host_and_port_string("example.com", 443, false));
  12447. // Edge case: Port 80 with is_ssl=true (should add port)
  12448. EXPECT_EQ("example.com:80",
  12449. detail::make_host_and_port_string("example.com", 80, true));
  12450. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  12451. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  12452. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  12453. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  12454. // Security fix: Already bracketed IPv6 should not get double brackets
  12455. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  12456. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  12457. EXPECT_EQ("[::1]:8080",
  12458. detail::make_host_and_port_string("[::1]", 8080, false));
  12459. EXPECT_EQ("[2001:db8::1]:8080",
  12460. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  12461. EXPECT_EQ("[fe80::1%eth0]",
  12462. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  12463. EXPECT_EQ("[fe80::1%eth0]:8080",
  12464. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  12465. // Edge case: Empty host (should return as-is)
  12466. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  12467. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  12468. // This is a known limitation but shouldn't crash
  12469. EXPECT_EQ("[host:name]",
  12470. detail::make_host_and_port_string("host:name", 80, false));
  12471. // Port number edge cases (no validation, but should not crash)
  12472. EXPECT_EQ("example.com:0",
  12473. detail::make_host_and_port_string("example.com", 0, false));
  12474. EXPECT_EQ("example.com:-1",
  12475. detail::make_host_and_port_string("example.com", -1, false));
  12476. EXPECT_EQ("example.com:65535",
  12477. detail::make_host_and_port_string("example.com", 65535, false));
  12478. EXPECT_EQ("example.com:65536",
  12479. detail::make_host_and_port_string("example.com", 65536, false));
  12480. }
  12481. #ifdef CPPHTTPLIB_SSL_ENABLED
  12482. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  12483. httplib::SSLClient cli("roblox.com", 443);
  12484. cli.set_follow_location(true);
  12485. auto res = cli.Get("/");
  12486. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12487. EXPECT_EQ(StatusCode::OK_200, res->status);
  12488. }
  12489. #endif
  12490. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  12491. Server svr;
  12492. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  12493. EXPECT_EQ(res.status, 400);
  12494. });
  12495. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12496. auto se = detail::scope_exit([&] {
  12497. svr.stop();
  12498. thread.join();
  12499. ASSERT_FALSE(svr.is_running());
  12500. });
  12501. svr.wait_until_ready();
  12502. Client cli(HOST, PORT);
  12503. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  12504. }
  12505. TEST(InvalidHeaderCharsTest, is_field_name) {
  12506. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  12507. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  12508. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  12509. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  12510. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  12511. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  12512. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  12513. EXPECT_FALSE(detail::fields::is_field_name(""));
  12514. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  12515. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  12516. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  12517. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  12518. }
  12519. TEST(InvalidHeaderCharsTest, is_field_value) {
  12520. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  12521. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  12522. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  12523. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  12524. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  12525. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  12526. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  12527. EXPECT_TRUE(detail::fields::is_field_value(""));
  12528. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  12529. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  12530. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  12531. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  12532. EXPECT_TRUE(detail::fields::is_field_value("0"));
  12533. }
  12534. TEST(InvalidHeaderCharsTest, OnServer) {
  12535. Server svr;
  12536. svr.Get("/test_name", [&](const Request &req, Response &res) {
  12537. std::string header = "Not Set";
  12538. if (req.has_param("header")) { header = req.get_param_value("header"); }
  12539. res.set_header(header, "value");
  12540. res.set_content("Page Content Page Content", "text/plain");
  12541. });
  12542. svr.Get("/test_value", [&](const Request &req, Response &res) {
  12543. std::string header = "Not Set";
  12544. if (req.has_param("header")) { header = req.get_param_value("header"); }
  12545. res.set_header("X-Test", header);
  12546. res.set_content("Page Content Page Content", "text/plain");
  12547. });
  12548. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12549. auto se = detail::scope_exit([&] {
  12550. svr.stop();
  12551. thread.join();
  12552. ASSERT_FALSE(svr.is_running());
  12553. });
  12554. svr.wait_until_ready();
  12555. Client cli(HOST, PORT);
  12556. {
  12557. auto res = cli.Get(
  12558. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  12559. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12560. EXPECT_EQ("Page Content Page Content", res->body);
  12561. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  12562. }
  12563. {
  12564. auto res = cli.Get(
  12565. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  12566. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12567. EXPECT_EQ("Page Content Page Content", res->body);
  12568. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  12569. }
  12570. }
  12571. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  12572. auto handled = false;
  12573. Server svr;
  12574. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  12575. thread t = thread([&] { svr.listen(HOST, PORT); });
  12576. auto se = detail::scope_exit([&] {
  12577. svr.stop();
  12578. t.join();
  12579. ASSERT_FALSE(svr.is_running());
  12580. ASSERT_FALSE(handled);
  12581. });
  12582. svr.wait_until_ready();
  12583. auto req = "POST /test HTTP/1.1\r\n"
  12584. "Content-Length: x\r\n"
  12585. "\r\n";
  12586. std::string response;
  12587. ASSERT_TRUE(send_request(1, req, &response));
  12588. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  12589. response.substr(0, response.find("\r\n")));
  12590. }
  12591. #ifndef _WIN32
  12592. TEST(Expect100ContinueTest, ServerClosesConnection) {
  12593. static constexpr char reject[] = "Unauthorized";
  12594. static constexpr char accept[] = "Upload accepted";
  12595. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  12596. Server svr;
  12597. svr.set_expect_100_continue_handler(
  12598. [](const Request & /*req*/, Response &res) {
  12599. res.status = StatusCode::Unauthorized_401;
  12600. res.set_content(reject, "text/plain");
  12601. return res.status;
  12602. });
  12603. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  12604. res.set_content(accept, "text/plain");
  12605. });
  12606. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12607. auto se = detail::scope_exit([&] {
  12608. svr.stop();
  12609. thread.join();
  12610. ASSERT_FALSE(svr.is_running());
  12611. });
  12612. svr.wait_until_ready();
  12613. {
  12614. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  12615. curl_easy_init(), &curl_easy_cleanup};
  12616. ASSERT_NE(curl, nullptr);
  12617. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  12618. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  12619. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  12620. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  12621. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  12622. &curl_slist_free_all};
  12623. ASSERT_NE(list, nullptr);
  12624. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  12625. struct read_data {
  12626. size_t read_size;
  12627. size_t total_size;
  12628. } data = {0, total_size};
  12629. using read_callback_t =
  12630. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  12631. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  12632. void *userdata) -> size_t {
  12633. read_data *d = (read_data *)userdata;
  12634. if (!userdata || d->read_size >= d->total_size) { return 0; }
  12635. std::fill_n(ptr, size * nmemb, 'A');
  12636. d->read_size += size * nmemb;
  12637. return size * nmemb;
  12638. };
  12639. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  12640. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  12641. std::vector<char> buffer;
  12642. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  12643. using write_callback_t =
  12644. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  12645. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  12646. void *userdata) -> size_t {
  12647. std::vector<char> *buf = (std::vector<char> *)userdata;
  12648. buf->reserve(buf->size() + size * nmemb + 1);
  12649. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  12650. return size * nmemb;
  12651. };
  12652. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  12653. {
  12654. const auto res = curl_easy_perform(curl.get());
  12655. ASSERT_EQ(res, CURLE_OK);
  12656. }
  12657. {
  12658. auto response_code = long{};
  12659. const auto res =
  12660. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  12661. ASSERT_EQ(res, CURLE_OK);
  12662. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  12663. }
  12664. {
  12665. auto dl = curl_off_t{};
  12666. const auto res =
  12667. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  12668. ASSERT_EQ(res, CURLE_OK);
  12669. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  12670. }
  12671. {
  12672. buffer.push_back('\0');
  12673. ASSERT_STRCASEEQ(buffer.data(), reject);
  12674. }
  12675. }
  12676. }
  12677. #endif
  12678. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  12679. // Regression test for #2458.
  12680. //
  12681. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  12682. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  12683. // ticket can make the client socket spuriously readable during the
  12684. // 100-continue wait. If the readiness is mistaken for an incoming response,
  12685. // the client withholds the body and then blocks reading a response that never
  12686. // comes, failing with `Failed to read connection`.
  12687. //
  12688. // A correct client (like curl) sends the body once no `100 Continue` arrives
  12689. // within the timeout. This raw OpenSSL server deliberately never sends
  12690. // `100 Continue`; the client must still deliver the body and receive 200.
  12691. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  12692. signal(SIGPIPE, SIG_IGN);
  12693. const auto port = PORT + 4;
  12694. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12695. ASSERT_NE(srv, INVALID_SOCKET);
  12696. int opt = 1;
  12697. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  12698. sockaddr_in addr{};
  12699. addr.sin_family = AF_INET;
  12700. addr.sin_port = htons(static_cast<uint16_t>(port));
  12701. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12702. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  12703. ASSERT_EQ(0, ::listen(srv, 1));
  12704. std::atomic<size_t> server_body_bytes{0};
  12705. auto server_thread = std::thread([&] {
  12706. sockaddr_in cli_addr{};
  12707. socklen_t cli_len = sizeof(cli_addr);
  12708. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12709. if (cli == INVALID_SOCKET) { return; }
  12710. // Bound the lifetime of the server side so a buggy client (which never
  12711. // sends the body) cannot make this thread block forever on join.
  12712. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  12713. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  12714. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  12715. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  12716. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  12717. SSL *ssl = SSL_new(ctx);
  12718. SSL_set_fd(ssl, static_cast<int>(cli));
  12719. if (SSL_accept(ssl) > 0) {
  12720. // Read the request headers. Reading here also flushes the TLS 1.3
  12721. // session tickets to the client. Deliberately do NOT send
  12722. // `100 Continue`.
  12723. std::string buf;
  12724. char tmp[1024];
  12725. while (buf.find("\r\n\r\n") == std::string::npos) {
  12726. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  12727. if (n <= 0) { break; }
  12728. buf.append(tmp, static_cast<size_t>(n));
  12729. }
  12730. // A correct client sends the body now; count what arrives.
  12731. auto pos = buf.find("\r\n\r\n");
  12732. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  12733. while (body < 4096) {
  12734. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  12735. if (n <= 0) { break; }
  12736. body += static_cast<size_t>(n);
  12737. }
  12738. server_body_bytes = body;
  12739. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  12740. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  12741. SSL_shutdown(ssl);
  12742. }
  12743. SSL_free(ssl);
  12744. detail::close_socket(cli);
  12745. SSL_CTX_free(ctx);
  12746. });
  12747. auto se = detail::scope_exit([&] {
  12748. server_thread.join();
  12749. detail::close_socket(srv);
  12750. });
  12751. SSLClient cli("127.0.0.1", port);
  12752. cli.enable_server_certificate_verification(false);
  12753. cli.set_connection_timeout(5, 0);
  12754. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  12755. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  12756. std::string body(4096, 'A');
  12757. auto res = cli.Put("/api/test", body, "application/json");
  12758. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  12759. EXPECT_EQ(StatusCode::OK_200, res->status);
  12760. EXPECT_EQ(body.size(), server_body_bytes.load());
  12761. }
  12762. #endif
  12763. template <typename S, typename C>
  12764. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  12765. svr.Get("/stream", [&](const Request &, Response &res) {
  12766. auto data = new std::string("01234567890123456789");
  12767. res.set_content_provider(
  12768. data->size(), "text/plain",
  12769. [&, data](size_t offset, size_t length, DataSink &sink) {
  12770. const size_t DATA_CHUNK_SIZE = 4;
  12771. const auto &d = *data;
  12772. std::this_thread::sleep_for(std::chrono::seconds(1));
  12773. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  12774. return true;
  12775. },
  12776. [data](bool success) {
  12777. EXPECT_FALSE(success);
  12778. delete data;
  12779. });
  12780. });
  12781. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  12782. auto i = new size_t(0);
  12783. res.set_content_provider(
  12784. "text/plain",
  12785. [i](size_t, DataSink &sink) {
  12786. if (*i < 5) {
  12787. std::this_thread::sleep_for(std::chrono::seconds(1));
  12788. sink.write("abcd", 4);
  12789. (*i)++;
  12790. } else {
  12791. sink.done();
  12792. }
  12793. return true;
  12794. },
  12795. [i](bool success) {
  12796. EXPECT_FALSE(success);
  12797. delete i;
  12798. });
  12799. });
  12800. svr.Get("/chunked", [&](const Request &, Response &res) {
  12801. auto i = new size_t(0);
  12802. res.set_chunked_content_provider(
  12803. "text/plain",
  12804. [i](size_t, DataSink &sink) {
  12805. if (*i < 5) {
  12806. std::this_thread::sleep_for(std::chrono::seconds(1));
  12807. sink.os << "abcd";
  12808. (*i)++;
  12809. } else {
  12810. sink.done();
  12811. }
  12812. return true;
  12813. },
  12814. [i](bool success) {
  12815. EXPECT_FALSE(success);
  12816. delete i;
  12817. });
  12818. });
  12819. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12820. auto se = detail::scope_exit([&] {
  12821. svr.stop();
  12822. listen_thread.join();
  12823. ASSERT_FALSE(svr.is_running());
  12824. });
  12825. svr.wait_until_ready();
  12826. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  12827. {
  12828. auto start = std::chrono::steady_clock::now();
  12829. auto res = cli.Get("/stream");
  12830. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12831. std::chrono::steady_clock::now() - start)
  12832. .count();
  12833. ASSERT_FALSE(res);
  12834. EXPECT_EQ(Error::Read, res.error());
  12835. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  12836. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  12837. }
  12838. {
  12839. auto start = std::chrono::steady_clock::now();
  12840. auto res = cli.Get("/stream_without_length");
  12841. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12842. std::chrono::steady_clock::now() - start)
  12843. .count();
  12844. ASSERT_FALSE(res);
  12845. EXPECT_EQ(Error::Read, res.error());
  12846. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  12847. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  12848. }
  12849. {
  12850. auto start = std::chrono::steady_clock::now();
  12851. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  12852. EXPECT_EQ("abcd", string(data, data_length));
  12853. return true;
  12854. });
  12855. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12856. std::chrono::steady_clock::now() - start)
  12857. .count();
  12858. ASSERT_FALSE(res);
  12859. EXPECT_EQ(Error::Read, res.error());
  12860. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  12861. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  12862. }
  12863. }
  12864. TEST(MaxTimeoutTest, ContentStream) {
  12865. time_t timeout = 2000;
  12866. time_t threshold = 200;
  12867. Server svr;
  12868. Client cli("localhost", PORT);
  12869. max_timeout_test(svr, cli, timeout, threshold);
  12870. }
  12871. #ifdef CPPHTTPLIB_SSL_ENABLED
  12872. TEST(MaxTimeoutTest, ContentStreamSSL) {
  12873. time_t timeout = 2000;
  12874. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  12875. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12876. SSLClient cli("localhost", PORT);
  12877. cli.enable_server_certificate_verification(false);
  12878. max_timeout_test(svr, cli, timeout, threshold);
  12879. }
  12880. #endif
  12881. class EventDispatcher {
  12882. public:
  12883. EventDispatcher() {}
  12884. bool wait_event(DataSink *sink) {
  12885. unique_lock<mutex> lk(m_);
  12886. int id = id_;
  12887. // Wait with timeout to prevent hanging if client disconnects
  12888. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  12889. [&] { return cid_ == id; })) {
  12890. return false; // Timeout occurred
  12891. }
  12892. sink->write(message_.data(), message_.size());
  12893. return true;
  12894. }
  12895. void send_event(const string &message) {
  12896. lock_guard<mutex> lk(m_);
  12897. cid_ = id_++;
  12898. message_ = message;
  12899. cv_.notify_all();
  12900. }
  12901. private:
  12902. mutex m_;
  12903. condition_variable cv_;
  12904. atomic_int id_{0};
  12905. atomic_int cid_{-1};
  12906. string message_;
  12907. };
  12908. TEST(ClientInThreadTest, Issue2068) {
  12909. EventDispatcher ed;
  12910. Server svr;
  12911. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  12912. res.set_chunked_content_provider("text/event-stream",
  12913. [&](size_t /*offset*/, DataSink &sink) {
  12914. return ed.wait_event(&sink);
  12915. });
  12916. });
  12917. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  12918. svr.wait_until_ready();
  12919. thread event_thread([&] {
  12920. int id = 0;
  12921. while (svr.is_running()) {
  12922. this_thread::sleep_for(chrono::milliseconds(500));
  12923. std::stringstream ss;
  12924. ss << "data: " << id << "\n\n";
  12925. ed.send_event(ss.str());
  12926. id++;
  12927. }
  12928. });
  12929. auto se = detail::scope_exit([&] {
  12930. svr.stop();
  12931. listen_thread.join();
  12932. event_thread.join();
  12933. ASSERT_FALSE(svr.is_running());
  12934. });
  12935. {
  12936. auto client = detail::make_unique<Client>(HOST, PORT);
  12937. client->set_read_timeout(std::chrono::minutes(10));
  12938. std::atomic<bool> stop{false};
  12939. std::thread t([&] {
  12940. client->Get("/event1",
  12941. [&](const char *, size_t) -> bool { return !stop; });
  12942. });
  12943. std::this_thread::sleep_for(std::chrono::seconds(2));
  12944. stop = true;
  12945. client->stop();
  12946. t.join();
  12947. // Reset client after thread has finished
  12948. client.reset();
  12949. }
  12950. }
  12951. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  12952. auto handled = false;
  12953. Server svr;
  12954. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  12955. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12956. auto se = detail::scope_exit([&] {
  12957. svr.stop();
  12958. t.join();
  12959. ASSERT_FALSE(svr.is_running());
  12960. ASSERT_FALSE(handled);
  12961. });
  12962. svr.wait_until_ready();
  12963. // Two Content-Length headers with different values — must be rejected
  12964. auto req = "POST /test HTTP/1.1\r\n"
  12965. "Content-Length: 5\r\n"
  12966. "Content-Length: 10\r\n"
  12967. "\r\n"
  12968. "hello";
  12969. std::string response;
  12970. ASSERT_TRUE(send_request(1, req, &response));
  12971. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  12972. response.substr(0, response.find("\r\n")));
  12973. }
  12974. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  12975. auto handled = false;
  12976. Server svr;
  12977. svr.Post("/test", [&](const Request &, Response &res) {
  12978. handled = true;
  12979. res.set_content("ok", "text/plain");
  12980. });
  12981. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12982. auto se = detail::scope_exit([&] {
  12983. svr.stop();
  12984. t.join();
  12985. ASSERT_FALSE(svr.is_running());
  12986. ASSERT_TRUE(handled);
  12987. });
  12988. svr.wait_until_ready();
  12989. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  12990. auto req = "POST /test HTTP/1.1\r\n"
  12991. "Content-Length: 5\r\n"
  12992. "Content-Length: 5\r\n"
  12993. "\r\n"
  12994. "hello";
  12995. std::string response;
  12996. ASSERT_TRUE(send_request(1, req, &response));
  12997. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  12998. }
  12999. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  13000. Server svr;
  13001. svr.Get("/", [](const Request &req, Response &res) {
  13002. EXPECT_EQ(2U, req.trailers.size());
  13003. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  13004. // Denied
  13005. EXPECT_FALSE(req.has_trailer("Content-Length"));
  13006. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  13007. // Accepted
  13008. EXPECT_TRUE(req.has_trailer("X-Hello"));
  13009. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  13010. EXPECT_TRUE(req.has_trailer("X-World"));
  13011. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  13012. res.set_content("ok", "text/plain");
  13013. });
  13014. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13015. auto se = detail::scope_exit([&] {
  13016. svr.stop();
  13017. t.join();
  13018. ASSERT_FALSE(svr.is_running());
  13019. });
  13020. svr.wait_until_ready();
  13021. const std::string req = "GET / HTTP/1.1\r\n"
  13022. "Transfer-Encoding: chunked\r\n"
  13023. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  13024. "\r\n"
  13025. "0\r\n"
  13026. "Content-Length: 10\r\n"
  13027. "Host: internal.local\r\n"
  13028. "Content-Type: malicious/content\r\n"
  13029. "Cookie: any\r\n"
  13030. "Set-Cookie: any\r\n"
  13031. "X-Forwarded-For: attacker.com\r\n"
  13032. "X-Real-Ip: 1.1.1.1\r\n"
  13033. "X-Hello: hello\r\n"
  13034. "X-World: world\r\n"
  13035. "\r\n";
  13036. std::string res;
  13037. ASSERT_TRUE(send_request(1, req, &res));
  13038. }
  13039. // A direct client that is not listed in trusted_proxies must not be able to
  13040. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  13041. // the peer address on the actual TCP connection determines whether the
  13042. // header is honored.
  13043. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  13044. Server svr;
  13045. // Deliberately does NOT include the loopback address the test client
  13046. // actually connects from, so the direct connection is not a trusted proxy.
  13047. svr.set_trusted_proxies({"203.0.113.66"});
  13048. std::string observed_remote_addr;
  13049. svr.Get("/ip", [&](const Request &req, Response &res) {
  13050. observed_remote_addr = req.remote_addr;
  13051. res.set_content("ok", "text/plain");
  13052. });
  13053. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13054. auto se = detail::scope_exit([&] {
  13055. svr.stop();
  13056. t.join();
  13057. ASSERT_FALSE(svr.is_running());
  13058. });
  13059. svr.wait_until_ready();
  13060. Client cli(HOST, PORT);
  13061. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  13062. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13063. EXPECT_EQ(StatusCode::OK_200, res->status);
  13064. // The connecting peer is not a trusted proxy, so the spoofed header must be
  13065. // ignored entirely and the real connection-level address retained.
  13066. EXPECT_TRUE(observed_remote_addr == "::1" ||
  13067. observed_remote_addr == "127.0.0.1");
  13068. }
  13069. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  13070. Server svr;
  13071. std::string observed_remote_addr;
  13072. std::string observed_xff;
  13073. svr.Get("/ip", [&](const Request &req, Response &res) {
  13074. observed_remote_addr = req.remote_addr;
  13075. observed_xff = req.get_header_value("X-Forwarded-For");
  13076. res.set_content("ok", "text/plain");
  13077. });
  13078. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13079. auto se = detail::scope_exit([&] {
  13080. svr.stop();
  13081. t.join();
  13082. ASSERT_FALSE(svr.is_running());
  13083. });
  13084. svr.wait_until_ready();
  13085. Client cli(HOST, PORT);
  13086. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  13087. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13088. EXPECT_EQ(StatusCode::OK_200, res->status);
  13089. EXPECT_EQ(observed_xff, "203.0.113.66");
  13090. EXPECT_TRUE(observed_remote_addr == "::1" ||
  13091. observed_remote_addr == "127.0.0.1");
  13092. }
  13093. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  13094. Server svr;
  13095. svr.set_trusted_proxies({"203.0.113.66"});
  13096. std::string observed_remote_addr;
  13097. std::string observed_xff;
  13098. svr.Get("/ip", [&](const Request &req, Response &res) {
  13099. observed_remote_addr = req.remote_addr;
  13100. observed_xff = req.get_header_value("X-Forwarded-For");
  13101. res.set_content("ok", "text/plain");
  13102. });
  13103. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13104. auto se = detail::scope_exit([&] {
  13105. svr.stop();
  13106. t.join();
  13107. ASSERT_FALSE(svr.is_running());
  13108. });
  13109. svr.wait_until_ready();
  13110. Client cli(HOST, PORT);
  13111. auto res = cli.Get("/ip");
  13112. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13113. EXPECT_EQ(StatusCode::OK_200, res->status);
  13114. EXPECT_EQ(observed_xff, "");
  13115. EXPECT_TRUE(observed_remote_addr == "::1" ||
  13116. observed_remote_addr == "127.0.0.1");
  13117. }
  13118. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  13119. Server svr;
  13120. // Include the loopback address the test client actually connects from, so
  13121. // the direct connection itself is recognized as the trusted proxy hop.
  13122. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  13123. std::string observed_remote_addr;
  13124. std::string observed_xff;
  13125. svr.Get("/ip", [&](const Request &req, Response &res) {
  13126. observed_remote_addr = req.remote_addr;
  13127. observed_xff = req.get_header_value("X-Forwarded-For");
  13128. res.set_content("ok", "text/plain");
  13129. });
  13130. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13131. auto se = detail::scope_exit([&] {
  13132. svr.stop();
  13133. t.join();
  13134. ASSERT_FALSE(svr.is_running());
  13135. });
  13136. svr.wait_until_ready();
  13137. Client cli(HOST, PORT);
  13138. auto res = cli.Get(
  13139. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  13140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13141. EXPECT_EQ(StatusCode::OK_200, res->status);
  13142. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  13143. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  13144. }
  13145. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  13146. Server svr;
  13147. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  13148. std::string observed_remote_addr;
  13149. std::string observed_xff;
  13150. svr.Get("/ip", [&](const Request &req, Response &res) {
  13151. observed_remote_addr = req.remote_addr;
  13152. observed_xff = req.get_header_value("X-Forwarded-For");
  13153. res.set_content("ok", "text/plain");
  13154. });
  13155. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13156. auto se = detail::scope_exit([&] {
  13157. svr.stop();
  13158. t.join();
  13159. ASSERT_FALSE(svr.is_running());
  13160. });
  13161. svr.wait_until_ready();
  13162. Client cli(HOST, PORT);
  13163. auto res = cli.Get(
  13164. "/ip",
  13165. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  13166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13167. EXPECT_EQ(StatusCode::OK_200, res->status);
  13168. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  13169. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  13170. }
  13171. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  13172. Server svr;
  13173. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  13174. std::string observed_remote_addr;
  13175. std::string observed_xff;
  13176. svr.Get("/ip", [&](const Request &req, Response &res) {
  13177. observed_remote_addr = req.remote_addr;
  13178. observed_xff = req.get_header_value("X-Forwarded-For");
  13179. res.set_content("ok", "text/plain");
  13180. });
  13181. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13182. auto se = detail::scope_exit([&] {
  13183. svr.stop();
  13184. t.join();
  13185. ASSERT_FALSE(svr.is_running());
  13186. });
  13187. svr.wait_until_ready();
  13188. Client cli(HOST, PORT);
  13189. auto res = cli.Get(
  13190. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  13191. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13192. EXPECT_EQ(StatusCode::OK_200, res->status);
  13193. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  13194. // by the closest hop) is used. The leftmost entry is fully client-controlled
  13195. // and must not be selected.
  13196. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  13197. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  13198. }
  13199. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  13200. Server svr;
  13201. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  13202. std::string observed_remote_addr;
  13203. svr.Get("/ip", [&](const Request &req, Response &res) {
  13204. observed_remote_addr = req.remote_addr;
  13205. res.set_content("ok", "text/plain");
  13206. });
  13207. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13208. auto se = detail::scope_exit([&] {
  13209. svr.stop();
  13210. t.join();
  13211. ASSERT_FALSE(svr.is_running());
  13212. });
  13213. svr.wait_until_ready();
  13214. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  13215. // a forged address and the trusted proxy's own address; the forged value must
  13216. // not win over the address the trusted proxy actually recorded.
  13217. Client cli(HOST, PORT);
  13218. auto res = cli.Get(
  13219. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  13220. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13221. EXPECT_EQ(StatusCode::OK_200, res->status);
  13222. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  13223. }
  13224. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  13225. Server svr;
  13226. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  13227. std::string observed_remote_addr;
  13228. std::string observed_xff;
  13229. svr.Get("/ip", [&](const Request &req, Response &res) {
  13230. observed_remote_addr = req.remote_addr;
  13231. observed_xff = req.get_header_value("X-Forwarded-For");
  13232. res.set_content("ok", "text/plain");
  13233. });
  13234. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13235. auto se = detail::scope_exit([&] {
  13236. svr.stop();
  13237. t.join();
  13238. ASSERT_FALSE(svr.is_running());
  13239. });
  13240. svr.wait_until_ready();
  13241. Client cli(HOST, PORT);
  13242. auto res = cli.Get(
  13243. "/ip",
  13244. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  13245. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13246. EXPECT_EQ(StatusCode::OK_200, res->status);
  13247. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  13248. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  13249. }
  13250. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  13251. Server svr;
  13252. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  13253. std::string observed_remote_addr;
  13254. std::string observed_xff;
  13255. svr.Get("/ip", [&](const Request &req, Response &res) {
  13256. observed_remote_addr = req.remote_addr;
  13257. observed_xff = req.get_header_value("X-Forwarded-For");
  13258. res.set_content("ok", "text/plain");
  13259. });
  13260. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13261. auto se = detail::scope_exit([&] {
  13262. svr.stop();
  13263. t.join();
  13264. ASSERT_FALSE(svr.is_running());
  13265. });
  13266. svr.wait_until_ready();
  13267. std::string raw_req =
  13268. "GET /ip HTTP/1.1\r\n"
  13269. "Host: localhost\r\n"
  13270. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  13271. "Connection: close\r\n"
  13272. "\r\n";
  13273. std::string out;
  13274. ASSERT_TRUE(send_request(5, raw_req, &out));
  13275. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  13276. // Header parser trims surrounding whitespace of the header value
  13277. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  13278. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  13279. }
  13280. // An X-Forwarded-For header whose value parses to zero IP segments must not
  13281. // crash the server (it used to call front() on an empty vector inside
  13282. // get_client_ip). The connection-level remote address must be retained instead.
  13283. static void run_malformed_xff_test(const std::string &xff_value) {
  13284. Server svr;
  13285. svr.set_trusted_proxies({"192.0.2.45"});
  13286. std::string observed_remote_addr;
  13287. svr.Get("/ip", [&](const Request &req, Response &res) {
  13288. observed_remote_addr = req.remote_addr;
  13289. res.set_content("ok", "text/plain");
  13290. });
  13291. int port = 0;
  13292. thread t = thread([&]() {
  13293. port = svr.bind_to_any_port(HOST);
  13294. svr.listen_after_bind();
  13295. });
  13296. auto se = detail::scope_exit([&] {
  13297. svr.stop();
  13298. t.join();
  13299. ASSERT_FALSE(svr.is_running());
  13300. });
  13301. svr.wait_until_ready();
  13302. Client cli(HOST, port);
  13303. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  13304. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13305. EXPECT_EQ(StatusCode::OK_200, res->status);
  13306. EXPECT_TRUE(observed_remote_addr == "::1" ||
  13307. observed_remote_addr == "127.0.0.1");
  13308. }
  13309. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  13310. run_malformed_xff_test("");
  13311. }
  13312. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  13313. run_malformed_xff_test(",");
  13314. }
  13315. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  13316. run_malformed_xff_test(", , ,");
  13317. }
  13318. #ifndef _WIN32
  13319. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  13320. Server svr;
  13321. svr.Post("/post", [&](const Request &req, Response &res) {
  13322. res.set_content(req.body, "text/plain");
  13323. });
  13324. svr.Put("/put", [&](const Request &req, Response &res) {
  13325. res.set_content(req.body, "text/plain");
  13326. });
  13327. svr.Patch("/patch", [&](const Request &req, Response &res) {
  13328. res.set_content(req.body, "text/plain");
  13329. });
  13330. svr.Delete("/delete", [&](const Request &req, Response &res) {
  13331. res.set_content(req.body, "text/plain");
  13332. });
  13333. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13334. auto se = detail::scope_exit([&] {
  13335. svr.stop();
  13336. t.join();
  13337. ASSERT_FALSE(svr.is_running());
  13338. });
  13339. svr.wait_until_ready();
  13340. std::string resp;
  13341. // POST without Content-Length
  13342. ASSERT_TRUE(send_request(5,
  13343. "POST /post HTTP/1.1\r\n"
  13344. "Host: localhost\r\n"
  13345. "Connection: close\r\n"
  13346. "\r\n",
  13347. &resp));
  13348. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  13349. // PUT without Content-Length
  13350. resp.clear();
  13351. ASSERT_TRUE(send_request(5,
  13352. "PUT /put HTTP/1.1\r\n"
  13353. "Host: localhost\r\n"
  13354. "Connection: close\r\n"
  13355. "\r\n",
  13356. &resp));
  13357. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  13358. // PATCH without Content-Length
  13359. resp.clear();
  13360. ASSERT_TRUE(send_request(5,
  13361. "PATCH /patch HTTP/1.1\r\n"
  13362. "Host: localhost\r\n"
  13363. "Connection: close\r\n"
  13364. "\r\n",
  13365. &resp));
  13366. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  13367. // DELETE without Content-Length
  13368. resp.clear();
  13369. ASSERT_TRUE(send_request(5,
  13370. "DELETE /delete HTTP/1.1\r\n"
  13371. "Host: localhost\r\n"
  13372. "Connection: close\r\n"
  13373. "\r\n",
  13374. &resp));
  13375. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  13376. }
  13377. #endif
  13378. //==============================================================================
  13379. // open_stream() Tests
  13380. //==============================================================================
  13381. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  13382. std::string result;
  13383. char buf[8192];
  13384. ssize_t n;
  13385. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13386. result.append(buf, static_cast<size_t>(n));
  13387. }
  13388. return result;
  13389. }
  13390. // Mock stream for unit tests
  13391. class MockStream : public Stream {
  13392. public:
  13393. std::string data;
  13394. size_t pos = 0;
  13395. ssize_t error_after = -1; // -1 = no error
  13396. explicit MockStream(const std::string &d, ssize_t err = -1)
  13397. : data(d), error_after(err) {}
  13398. bool is_readable() const override { return true; }
  13399. bool wait_readable() const override { return true; }
  13400. bool wait_writable() const override { return true; }
  13401. ssize_t read(char *ptr, size_t size) override {
  13402. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  13403. if (pos >= data.size()) return 0;
  13404. size_t limit =
  13405. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  13406. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  13407. std::memcpy(ptr, data.data() + pos, to_read);
  13408. pos += to_read;
  13409. return static_cast<ssize_t>(to_read);
  13410. }
  13411. ssize_t write(const char *, size_t) override { return -1; }
  13412. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  13413. ip = "127.0.0.1";
  13414. port = 0;
  13415. }
  13416. void get_local_ip_and_port(std::string &ip, int &port) const override {
  13417. ip = "127.0.0.1";
  13418. port = 0;
  13419. }
  13420. socket_t socket() const override { return INVALID_SOCKET; }
  13421. time_t duration() const override { return 0; }
  13422. };
  13423. TEST(StreamHandleTest, Basic) {
  13424. ClientImpl::StreamHandle handle;
  13425. EXPECT_FALSE(handle.is_valid());
  13426. handle.response = detail::make_unique<Response>();
  13427. handle.error = Error::Connection;
  13428. EXPECT_FALSE(handle.is_valid());
  13429. handle.error = Error::Success;
  13430. EXPECT_TRUE(handle.is_valid());
  13431. }
  13432. TEST(BodyReaderTest, Basic) {
  13433. MockStream stream("Hello, World!");
  13434. detail::BodyReader reader;
  13435. reader.stream = &stream;
  13436. reader.content_length = 13;
  13437. char buf[32];
  13438. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  13439. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  13440. EXPECT_TRUE(reader.eof);
  13441. }
  13442. TEST(BodyReaderTest, NoStream) {
  13443. detail::BodyReader reader;
  13444. char buf[32];
  13445. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  13446. EXPECT_EQ(Error::Connection, reader.last_error);
  13447. }
  13448. TEST(BodyReaderTest, Error) {
  13449. MockStream stream("Hello, World!", 5);
  13450. detail::BodyReader reader;
  13451. reader.stream = &stream;
  13452. reader.content_length = 13;
  13453. char buf[32];
  13454. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  13455. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  13456. EXPECT_EQ(Error::Read, reader.last_error);
  13457. }
  13458. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  13459. // Mock-based StreamHandle tests relying on private internals are removed.
  13460. class OpenStreamTest : public ::testing::Test {
  13461. protected:
  13462. void SetUp() override {
  13463. svr_.Get("/hello", [](const Request &, Response &res) {
  13464. res.set_content("Hello World!", "text/plain");
  13465. });
  13466. svr_.Get("/large", [](const Request &, Response &res) {
  13467. res.set_content(std::string(10000, 'X'), "text/plain");
  13468. });
  13469. svr_.Get("/chunked", [](const Request &, Response &res) {
  13470. res.set_chunked_content_provider("text/plain",
  13471. [](size_t offset, DataSink &sink) {
  13472. if (offset < 15) {
  13473. sink.write("chunk", 5);
  13474. return true;
  13475. }
  13476. sink.done();
  13477. return true;
  13478. });
  13479. });
  13480. svr_.Get("/compressible", [](const Request &, Response &res) {
  13481. res.set_chunked_content_provider("text/plain", [](size_t offset,
  13482. DataSink &sink) {
  13483. if (offset < 100 * 1024) {
  13484. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  13485. sink.write(chunk.data(), chunk.size());
  13486. return true;
  13487. }
  13488. sink.done();
  13489. return true;
  13490. });
  13491. });
  13492. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  13493. [](const Request & /*req*/, Response &res) {
  13494. auto i = new int(0);
  13495. res.set_header("Trailer", "Content-Length, X-Allowed");
  13496. res.set_chunked_content_provider(
  13497. "text/plain",
  13498. [i](size_t /*offset*/, DataSink &sink) {
  13499. switch (*i) {
  13500. case 0: sink.os << "123"; break;
  13501. case 1: sink.os << "456"; break;
  13502. case 2: sink.os << "789"; break;
  13503. case 3: {
  13504. sink.done_with_trailer(
  13505. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  13506. } break;
  13507. }
  13508. (*i)++;
  13509. return true;
  13510. },
  13511. [i](bool success) {
  13512. EXPECT_TRUE(success);
  13513. delete i;
  13514. });
  13515. });
  13516. // Echo headers endpoint for header-related tests
  13517. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  13518. std::string body;
  13519. for (const auto &h : req.headers) {
  13520. body.append(h.first);
  13521. body.push_back(':');
  13522. body.append(h.second);
  13523. body.push_back('\n');
  13524. }
  13525. res.set_content(body, "text/plain");
  13526. });
  13527. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  13528. std::string body;
  13529. for (const auto &h : req.headers) {
  13530. body.append(h.first);
  13531. body.push_back(':');
  13532. body.append(h.second);
  13533. body.push_back('\n');
  13534. }
  13535. res.set_content(body, "text/plain");
  13536. });
  13537. port_ = svr_.bind_to_any_port("127.0.0.1");
  13538. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  13539. svr_.wait_until_ready();
  13540. }
  13541. void TearDown() override {
  13542. svr_.stop();
  13543. if (thread_.joinable()) thread_.join();
  13544. }
  13545. Server svr_;
  13546. std::thread thread_;
  13547. int port_ = 0;
  13548. };
  13549. TEST_F(OpenStreamTest, Basic) {
  13550. Client cli("127.0.0.1", port_);
  13551. auto handle = cli.open_stream("GET", "/hello");
  13552. EXPECT_TRUE(handle.is_valid());
  13553. EXPECT_EQ("Hello World!", read_all(handle));
  13554. }
  13555. TEST_F(OpenStreamTest, SmallBuffer) {
  13556. Client cli("127.0.0.1", port_);
  13557. auto handle = cli.open_stream("GET", "/hello");
  13558. std::string result;
  13559. char buf[4];
  13560. ssize_t n;
  13561. while ((n = handle.read(buf, sizeof(buf))) > 0)
  13562. result.append(buf, static_cast<size_t>(n));
  13563. EXPECT_EQ("Hello World!", result);
  13564. }
  13565. TEST_F(OpenStreamTest, DefaultHeaders) {
  13566. Client cli("127.0.0.1", port_);
  13567. // open_stream GET should include Host, User-Agent and Accept-Encoding
  13568. {
  13569. auto handle = cli.open_stream("GET", "/echo-headers");
  13570. ASSERT_TRUE(handle.is_valid());
  13571. auto body = read_all(handle);
  13572. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  13573. std::string::npos);
  13574. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  13575. std::string::npos);
  13576. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  13577. }
  13578. // open_stream POST with body and no explicit content_type should NOT add
  13579. // text/plain Content-Type (behavior differs from non-streaming path), but
  13580. // should include Content-Length
  13581. {
  13582. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  13583. ASSERT_TRUE(handle.is_valid());
  13584. auto body = read_all(handle);
  13585. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  13586. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  13587. }
  13588. // open_stream POST with explicit Content-Type should preserve it
  13589. {
  13590. auto handle = cli.open_stream("POST", "/echo-headers", {},
  13591. {{"Content-Type", "application/custom"}},
  13592. "{}", "application/custom");
  13593. ASSERT_TRUE(handle.is_valid());
  13594. auto body = read_all(handle);
  13595. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  13596. }
  13597. // User-specified User-Agent must not be overwritten for stream API
  13598. {
  13599. auto handle = cli.open_stream("GET", "/echo-headers", {},
  13600. {{"User-Agent", "MyAgent/1.2"}});
  13601. ASSERT_TRUE(handle.is_valid());
  13602. auto body = read_all(handle);
  13603. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  13604. }
  13605. }
  13606. TEST_F(OpenStreamTest, Large) {
  13607. Client cli("127.0.0.1", port_);
  13608. auto handle = cli.open_stream("GET", "/large");
  13609. EXPECT_EQ(10000u, read_all(handle).size());
  13610. }
  13611. TEST_F(OpenStreamTest, ConnectionError) {
  13612. Client cli("127.0.0.1", 9999);
  13613. auto handle = cli.open_stream("GET", "/hello");
  13614. EXPECT_FALSE(handle.is_valid());
  13615. }
  13616. TEST_F(OpenStreamTest, Chunked) {
  13617. Client cli("127.0.0.1", port_);
  13618. auto handle = cli.open_stream("GET", "/chunked");
  13619. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  13620. "Transfer-Encoding") == "chunked");
  13621. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  13622. }
  13623. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  13624. Client cli("127.0.0.1", port_);
  13625. auto handle =
  13626. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  13627. ASSERT_TRUE(handle.is_valid());
  13628. // Consume body to allow trailers to be received/parsed
  13629. auto body = read_all(handle);
  13630. // Explicitly parse trailers (ensure trailers are available for assertion)
  13631. handle.parse_trailers_if_needed();
  13632. EXPECT_EQ(std::string("123456789"), body);
  13633. // The response should include a Trailer header declaring both names
  13634. ASSERT_TRUE(handle.response);
  13635. EXPECT_TRUE(handle.response->has_header("Trailer"));
  13636. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  13637. handle.response->get_header_value("Trailer"));
  13638. // Prohibited trailer must not be present
  13639. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  13640. // Allowed trailer should be present
  13641. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  13642. EXPECT_EQ(std::string("yes"),
  13643. handle.response->get_trailer_value("X-Allowed"));
  13644. // Verify trailers are NOT present as regular headers
  13645. EXPECT_EQ(std::string(""),
  13646. handle.response->get_header_value("Content-Length"));
  13647. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  13648. }
  13649. static std::thread serve_single_response(std::promise<int> &port_promise,
  13650. const std::string &response) {
  13651. return std::thread([&port_promise, response] {
  13652. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13653. default_socket_options(srv);
  13654. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13655. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13656. sockaddr_in addr{};
  13657. addr.sin_family = AF_INET;
  13658. addr.sin_port = htons(0); // Let OS assign a free port
  13659. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13660. int opt = 1;
  13661. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13662. #ifdef _WIN32
  13663. reinterpret_cast<const char *>(&opt),
  13664. #else
  13665. &opt,
  13666. #endif
  13667. sizeof(opt));
  13668. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  13669. ::listen(srv, 1) != 0) {
  13670. port_promise.set_value(-1);
  13671. detail::close_socket(srv);
  13672. return;
  13673. }
  13674. socklen_t addr_len = sizeof(addr);
  13675. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  13676. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  13677. sockaddr_in cli_addr{};
  13678. socklen_t cli_len = sizeof(cli_addr);
  13679. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13680. if (cli != INVALID_SOCKET) {
  13681. // Read the complete HTTP request (until the blank line that terminates
  13682. // headers) before sending the response. If the server closes the socket
  13683. // while the client's request data is still unread in the kernel receive
  13684. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  13685. // connection on both sides: it discards the client's receive buffer
  13686. // (which already holds our response) and causes any in-progress write on
  13687. // the client to fail with ECONNRESET. Reading all request data first
  13688. // ensures close() emits a graceful FIN.
  13689. {
  13690. char rbuf[256];
  13691. std::string req;
  13692. while (req.find("\r\n\r\n") == std::string::npos) {
  13693. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  13694. if (n <= 0) { break; }
  13695. req.append(rbuf, static_cast<size_t>(n));
  13696. }
  13697. }
  13698. ::send(cli,
  13699. #ifdef _WIN32
  13700. static_cast<const char *>(response.c_str()),
  13701. static_cast<int>(response.size()),
  13702. #else
  13703. response.c_str(), response.size(),
  13704. #endif
  13705. 0);
  13706. detail::close_socket(cli);
  13707. }
  13708. detail::close_socket(srv);
  13709. });
  13710. }
  13711. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  13712. #ifndef _WIN32
  13713. signal(SIGPIPE, SIG_IGN);
  13714. #endif
  13715. std::promise<int> port_promise;
  13716. auto port_future = port_promise.get_future();
  13717. auto server_thread =
  13718. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  13719. "Content-Type: text/plain\r\n"
  13720. "Content-Length: not-a-number\r\n"
  13721. "Connection: close\r\n"
  13722. "\r\n"
  13723. "hello");
  13724. auto port = port_future.get();
  13725. ASSERT_GT(port, 0);
  13726. Client cli("127.0.0.1", port);
  13727. auto handle = cli.open_stream("GET", "/");
  13728. EXPECT_FALSE(handle.is_valid());
  13729. server_thread.join();
  13730. }
  13731. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  13732. #ifndef _WIN32
  13733. signal(SIGPIPE, SIG_IGN);
  13734. #endif
  13735. std::promise<int> port_promise;
  13736. auto port_future = port_promise.get_future();
  13737. auto server_thread = serve_single_response(
  13738. port_promise, "HTTP/1.1 200 OK\r\n"
  13739. "Content-Type: text/plain\r\n"
  13740. "Content-Length: 99999999999999999999999999\r\n"
  13741. "Connection: close\r\n"
  13742. "\r\n"
  13743. "hello");
  13744. auto port = port_future.get();
  13745. ASSERT_GT(port, 0);
  13746. // Historically std::stoull would throw std::out_of_range here and crash
  13747. // the process, then parsing silently clamped to a bogus framing length and
  13748. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  13749. // so the stream fails to open, matching the not-a-number case above. The
  13750. // process still must NOT terminate.
  13751. Client cli("127.0.0.1", port);
  13752. auto handle = cli.open_stream("GET", "/");
  13753. EXPECT_FALSE(handle.is_valid());
  13754. server_thread.join();
  13755. }
  13756. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13757. TEST_F(OpenStreamTest, Gzip) {
  13758. Client cli("127.0.0.1", port_);
  13759. auto handle = cli.open_stream("GET", "/compressible", {},
  13760. {{"Accept-Encoding", "gzip"}});
  13761. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  13762. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  13763. }
  13764. #endif
  13765. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  13766. TEST_F(OpenStreamTest, Brotli) {
  13767. Client cli("127.0.0.1", port_);
  13768. auto handle =
  13769. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  13770. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  13771. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  13772. }
  13773. #endif
  13774. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  13775. TEST_F(OpenStreamTest, Zstd) {
  13776. Client cli("127.0.0.1", port_);
  13777. auto handle = cli.open_stream("GET", "/compressible", {},
  13778. {{"Accept-Encoding", "zstd"}});
  13779. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  13780. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  13781. }
  13782. #endif
  13783. #ifdef CPPHTTPLIB_SSL_ENABLED
  13784. class SSLOpenStreamTest : public ::testing::Test {
  13785. protected:
  13786. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  13787. void SetUp() override {
  13788. svr_.Get("/hello", [](const Request &, Response &res) {
  13789. res.set_content("Hello SSL World!", "text/plain");
  13790. });
  13791. svr_.Get("/chunked", [](const Request &, Response &res) {
  13792. res.set_chunked_content_provider("text/plain",
  13793. [](size_t offset, DataSink &sink) {
  13794. if (offset < 15) {
  13795. sink.write("chunk", 5);
  13796. return true;
  13797. }
  13798. sink.done();
  13799. return true;
  13800. });
  13801. });
  13802. svr_.Post("/echo", [](const Request &req, Response &res) {
  13803. res.set_content(req.body, req.get_header_value("Content-Type"));
  13804. });
  13805. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  13806. std::string body = req.body;
  13807. res.set_chunked_content_provider(
  13808. "text/plain", [body](size_t offset, DataSink &sink) {
  13809. if (offset < body.size()) {
  13810. sink.write(body.data() + offset, body.size() - offset);
  13811. }
  13812. sink.done();
  13813. return true;
  13814. });
  13815. });
  13816. port_ = svr_.bind_to_any_port("127.0.0.1");
  13817. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  13818. svr_.wait_until_ready();
  13819. }
  13820. void TearDown() override {
  13821. svr_.stop();
  13822. if (thread_.joinable()) thread_.join();
  13823. }
  13824. SSLServer svr_;
  13825. std::thread thread_;
  13826. int port_ = 0;
  13827. };
  13828. TEST_F(SSLOpenStreamTest, Basic) {
  13829. SSLClient cli("127.0.0.1", port_);
  13830. cli.enable_server_certificate_verification(false);
  13831. auto handle = cli.open_stream("GET", "/hello");
  13832. ASSERT_TRUE(handle.is_valid());
  13833. EXPECT_EQ("Hello SSL World!", read_all(handle));
  13834. }
  13835. TEST_F(SSLOpenStreamTest, Chunked) {
  13836. SSLClient cli("127.0.0.1", port_);
  13837. cli.enable_server_certificate_verification(false);
  13838. auto handle = cli.open_stream("GET", "/chunked");
  13839. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  13840. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  13841. "Transfer-Encoding") == "chunked");
  13842. auto body = read_all(handle);
  13843. EXPECT_EQ("chunkchunkchunk", body);
  13844. }
  13845. TEST_F(SSLOpenStreamTest, Post) {
  13846. SSLClient cli("127.0.0.1", port_);
  13847. cli.enable_server_certificate_verification(false);
  13848. auto handle =
  13849. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  13850. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  13851. EXPECT_EQ(200, handle.response->status);
  13852. auto body = read_all(handle);
  13853. EXPECT_EQ("Hello SSL POST", body);
  13854. }
  13855. TEST_F(SSLOpenStreamTest, PostChunked) {
  13856. SSLClient cli("127.0.0.1", port_);
  13857. cli.enable_server_certificate_verification(false);
  13858. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  13859. "Chunked SSL Data", "text/plain");
  13860. ASSERT_TRUE(handle.is_valid());
  13861. EXPECT_EQ(200, handle.response->status);
  13862. auto body = read_all(handle);
  13863. EXPECT_EQ("Chunked SSL Data", body);
  13864. }
  13865. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  13866. // Content-Length is terminated by the server closing the connection. When the
  13867. // SSL peer sends a close_notify after the body, the client must treat it as a
  13868. // clean EOF and return a successful response rather than an error.
  13869. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  13870. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13871. ASSERT_TRUE(svr.is_valid());
  13872. svr.set_keep_alive_max_count(1);
  13873. const std::string expected_body = "Hello from connection-close response!";
  13874. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  13875. res.set_content_provider("text/plain",
  13876. [&](size_t offset, DataSink &sink) -> bool {
  13877. if (offset < expected_body.size()) {
  13878. sink.write(expected_body.data() + offset,
  13879. expected_body.size() - offset);
  13880. }
  13881. sink.done();
  13882. return true;
  13883. });
  13884. });
  13885. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  13886. auto se = detail::scope_exit([&] {
  13887. svr.stop();
  13888. listen_thread.join();
  13889. ASSERT_FALSE(svr.is_running());
  13890. });
  13891. svr.wait_until_ready();
  13892. SSLClient cli(HOST, PORT);
  13893. cli.enable_server_certificate_verification(false);
  13894. auto res = cli.Get("/no-content-length");
  13895. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  13896. EXPECT_EQ(StatusCode::OK_200, res->status);
  13897. EXPECT_EQ(expected_body, res->body);
  13898. }
  13899. #endif // CPPHTTPLIB_SSL_ENABLED
  13900. //==============================================================================
  13901. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  13902. // results for various scenarios.
  13903. //==============================================================================
  13904. TEST(ParityTest, GetVsOpenStream) {
  13905. Server svr;
  13906. const std::string path = "/parity";
  13907. const std::string content = "Parity test content: hello world";
  13908. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  13909. res.set_content(content, "text/plain");
  13910. });
  13911. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13912. auto se = detail::scope_exit([&] {
  13913. svr.stop();
  13914. t.join();
  13915. ASSERT_FALSE(svr.is_running());
  13916. });
  13917. svr.wait_until_ready();
  13918. Client cli(HOST, PORT);
  13919. // Non-stream path
  13920. auto r1 = cli.Get(path);
  13921. ASSERT_TRUE(r1);
  13922. EXPECT_EQ(StatusCode::OK_200, r1->status);
  13923. // Stream path
  13924. auto h = cli.open_stream("GET", path);
  13925. ASSERT_TRUE(h.is_valid());
  13926. EXPECT_EQ(r1->body, read_all(h));
  13927. }
  13928. // Helper to compress data with provided compressor type T
  13929. template <typename Compressor>
  13930. static std::string compress_payload_for_parity(const std::string &in) {
  13931. std::string out;
  13932. Compressor compressor;
  13933. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  13934. [&](const char *data, size_t n) {
  13935. out.append(data, n);
  13936. return true;
  13937. });
  13938. EXPECT_TRUE(ok);
  13939. return out;
  13940. }
  13941. // Helper function for compression parity tests
  13942. template <typename Compressor>
  13943. static void test_compression_parity(const std::string &original,
  13944. const std::string &path,
  13945. const std::string &encoding) {
  13946. const std::string compressed =
  13947. compress_payload_for_parity<Compressor>(original);
  13948. Server svr;
  13949. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  13950. res.set_content(compressed, "application/octet-stream");
  13951. res.set_header("Content-Encoding", encoding);
  13952. });
  13953. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  13954. auto se = detail::scope_exit([&] {
  13955. svr.stop();
  13956. t.join();
  13957. ASSERT_FALSE(svr.is_running());
  13958. });
  13959. svr.wait_until_ready();
  13960. Client cli(HOST, PORT);
  13961. // Non-streaming
  13962. {
  13963. auto res = cli.Get(path);
  13964. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13965. EXPECT_EQ(StatusCode::OK_200, res->status);
  13966. EXPECT_EQ(original, res->body);
  13967. }
  13968. // Streaming
  13969. {
  13970. auto h = cli.open_stream("GET", path);
  13971. ASSERT_TRUE(h.is_valid());
  13972. EXPECT_EQ(original, read_all(h));
  13973. }
  13974. }
  13975. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13976. TEST(ParityTest, Gzip) {
  13977. test_compression_parity<detail::gzip_compressor>(
  13978. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  13979. }
  13980. #endif
  13981. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  13982. TEST(ParityTest, Brotli) {
  13983. test_compression_parity<detail::brotli_compressor>(
  13984. "Hello, brotli parity test payload", "/parity-br", "br");
  13985. }
  13986. #endif
  13987. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  13988. TEST(ParityTest, Zstd) {
  13989. test_compression_parity<detail::zstd_compressor>(
  13990. "Zstandard parity test payload", "/parity-zstd", "zstd");
  13991. }
  13992. #endif
  13993. //==============================================================================
  13994. // New Stream API Tests
  13995. //==============================================================================
  13996. inline std::string read_body(httplib::stream::Result &result) {
  13997. std::string body;
  13998. while (result.next()) {
  13999. body.append(result.data(), result.size());
  14000. }
  14001. return body;
  14002. }
  14003. TEST(ClientConnectionTest, Basic) {
  14004. httplib::ClientConnection conn;
  14005. EXPECT_FALSE(conn.is_open());
  14006. conn.sock = 1;
  14007. EXPECT_TRUE(conn.is_open());
  14008. httplib::ClientConnection conn2(std::move(conn));
  14009. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  14010. conn2.sock = INVALID_SOCKET;
  14011. }
  14012. // Unified test server for all stream::* tests
  14013. class StreamApiTest : public ::testing::Test {
  14014. protected:
  14015. void SetUp() override {
  14016. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  14017. res.set_content("Hello World!", "text/plain");
  14018. });
  14019. svr_.Get("/echo-params",
  14020. [](const httplib::Request &req, httplib::Response &res) {
  14021. std::string r;
  14022. for (const auto &p : req.params) {
  14023. if (!r.empty()) r += "&";
  14024. r += p.first + "=" + p.second;
  14025. }
  14026. res.set_content(r, "text/plain");
  14027. });
  14028. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  14029. res.set_content(req.body, req.get_header_value("Content-Type"));
  14030. });
  14031. svr_.Post("/echo-headers",
  14032. [](const httplib::Request &req, httplib::Response &res) {
  14033. std::string r;
  14034. for (const auto &h : req.headers)
  14035. r += h.first + ": " + h.second + "\n";
  14036. res.set_content(r, "text/plain");
  14037. });
  14038. svr_.Post("/echo-params",
  14039. [](const httplib::Request &req, httplib::Response &res) {
  14040. std::string r = "params:";
  14041. for (const auto &p : req.params)
  14042. r += p.first + "=" + p.second + ";";
  14043. res.set_content(r + " body:" + req.body, "text/plain");
  14044. });
  14045. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  14046. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  14047. });
  14048. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  14049. res.set_content("PUT:" + req.body, "text/plain");
  14050. });
  14051. svr_.Patch("/echo",
  14052. [](const httplib::Request &req, httplib::Response &res) {
  14053. res.set_content("PATCH:" + req.body, "text/plain");
  14054. });
  14055. svr_.Delete(
  14056. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  14057. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  14058. "text/plain");
  14059. });
  14060. svr_.Get("/head-test",
  14061. [](const httplib::Request &, httplib::Response &res) {
  14062. res.set_content("body for HEAD", "text/plain");
  14063. });
  14064. svr_.Options("/options",
  14065. [](const httplib::Request &, httplib::Response &res) {
  14066. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  14067. });
  14068. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  14069. svr_.wait_until_ready();
  14070. }
  14071. void TearDown() override {
  14072. svr_.stop();
  14073. if (thread_.joinable()) thread_.join();
  14074. }
  14075. httplib::Server svr_;
  14076. std::thread thread_;
  14077. };
  14078. // stream::Get tests
  14079. TEST_F(StreamApiTest, GetBasic) {
  14080. httplib::Client cli(HOST, PORT);
  14081. auto result = httplib::stream::Get(cli, "/hello");
  14082. ASSERT_TRUE(result.is_valid());
  14083. EXPECT_EQ(200, result.status());
  14084. EXPECT_EQ("Hello World!", read_body(result));
  14085. }
  14086. TEST_F(StreamApiTest, GetWithParams) {
  14087. httplib::Client cli(HOST, PORT);
  14088. httplib::Params params{{"foo", "bar"}};
  14089. auto result = httplib::stream::Get(cli, "/echo-params", params);
  14090. ASSERT_TRUE(result.is_valid());
  14091. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  14092. }
  14093. TEST_F(StreamApiTest, GetConnectionError) {
  14094. httplib::Client cli(HOST, 9999);
  14095. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  14096. }
  14097. TEST_F(StreamApiTest, Get404) {
  14098. httplib::Client cli(HOST, PORT);
  14099. auto result = httplib::stream::Get(cli, "/nonexistent");
  14100. EXPECT_TRUE(result.is_valid());
  14101. EXPECT_EQ(404, result.status());
  14102. }
  14103. // stream::Post tests
  14104. TEST_F(StreamApiTest, PostBasic) {
  14105. httplib::Client cli(HOST, PORT);
  14106. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  14107. "application/json");
  14108. ASSERT_TRUE(result.is_valid());
  14109. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  14110. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  14111. }
  14112. TEST_F(StreamApiTest, PostWithHeaders) {
  14113. httplib::Client cli(HOST, PORT);
  14114. httplib::Headers headers{{"X-Custom", "value"}};
  14115. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  14116. "text/plain");
  14117. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  14118. }
  14119. TEST_F(StreamApiTest, PostWithParams) {
  14120. httplib::Client cli(HOST, PORT);
  14121. httplib::Params params{{"k", "v"}};
  14122. auto result =
  14123. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  14124. auto body = read_body(result);
  14125. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  14126. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  14127. }
  14128. TEST_F(StreamApiTest, PostLarge) {
  14129. httplib::Client cli(HOST, PORT);
  14130. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  14131. size_t total = 0;
  14132. while (result.next()) {
  14133. total += result.size();
  14134. }
  14135. EXPECT_EQ(100u * 1024u, total);
  14136. }
  14137. // stream::Put/Patch tests
  14138. TEST_F(StreamApiTest, PutAndPatch) {
  14139. httplib::Client cli(HOST, PORT);
  14140. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  14141. EXPECT_EQ("PUT:test", read_body(put));
  14142. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  14143. EXPECT_EQ("PATCH:test", read_body(patch));
  14144. }
  14145. // stream::Delete tests
  14146. TEST_F(StreamApiTest, Delete) {
  14147. httplib::Client cli(HOST, PORT);
  14148. auto del1 = httplib::stream::Delete(cli, "/resource");
  14149. EXPECT_EQ("Deleted", read_body(del1));
  14150. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  14151. EXPECT_EQ("Deleted:data", read_body(del2));
  14152. }
  14153. // stream::Head/Options tests
  14154. TEST_F(StreamApiTest, HeadAndOptions) {
  14155. httplib::Client cli(HOST, PORT);
  14156. auto head = httplib::stream::Head(cli, "/head-test");
  14157. EXPECT_TRUE(head.is_valid());
  14158. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  14159. auto opts = httplib::stream::Options(cli, "/options");
  14160. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  14161. }
  14162. // SSL stream::* tests
  14163. #ifdef CPPHTTPLIB_SSL_ENABLED
  14164. class SSLStreamApiTest : public ::testing::Test {
  14165. protected:
  14166. void SetUp() override {
  14167. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  14168. res.set_content("Hello SSL!", "text/plain");
  14169. });
  14170. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  14171. res.set_content(req.body, "text/plain");
  14172. });
  14173. port_ = svr_.bind_to_any_port("127.0.0.1");
  14174. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  14175. svr_.wait_until_ready();
  14176. }
  14177. void TearDown() override {
  14178. svr_.stop();
  14179. if (thread_.joinable()) thread_.join();
  14180. }
  14181. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  14182. std::thread thread_;
  14183. int port_ = 0;
  14184. };
  14185. TEST_F(SSLStreamApiTest, GetAndPost) {
  14186. httplib::SSLClient cli("127.0.0.1", port_);
  14187. cli.enable_server_certificate_verification(false);
  14188. auto get = httplib::stream::Get(cli, "/hello");
  14189. EXPECT_EQ("Hello SSL!", read_body(get));
  14190. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  14191. EXPECT_EQ("test", read_body(post));
  14192. }
  14193. #endif
  14194. // Tests for Error::Timeout and Error::ConnectionClosed error types
  14195. // These errors are set in SocketStream/SSLSocketStream and propagated through
  14196. // BodyReader
  14197. TEST(ErrorHandlingTest, StreamReadTimeout) {
  14198. // Test that read timeout during streaming is detected
  14199. // Use a large content-length response where server delays mid-stream
  14200. Server svr;
  14201. svr.Get("/slow-stream", [](const Request &, Response &res) {
  14202. // Send a large response with delay in the middle
  14203. res.set_content_provider(
  14204. 1000, // content_length
  14205. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  14206. if (offset < 100) {
  14207. // Send first 100 bytes immediately
  14208. std::string data(100, 'A');
  14209. sink.write(data.c_str(), data.size());
  14210. return true;
  14211. }
  14212. // Then delay longer than client timeout
  14213. std::this_thread::sleep_for(std::chrono::seconds(3));
  14214. std::string data(900, 'B');
  14215. sink.write(data.c_str(), data.size());
  14216. return true;
  14217. });
  14218. });
  14219. auto port = 8091;
  14220. std::thread t([&]() { svr.listen("localhost", port); });
  14221. svr.wait_until_ready();
  14222. Client cli("localhost", port);
  14223. cli.set_read_timeout(1, 0); // 1 second timeout
  14224. auto handle = cli.open_stream("GET", "/slow-stream");
  14225. ASSERT_TRUE(handle.is_valid());
  14226. char buf[256];
  14227. ssize_t total = 0;
  14228. ssize_t n;
  14229. bool got_error = false;
  14230. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  14231. total += n;
  14232. }
  14233. if (n < 0) {
  14234. got_error = true;
  14235. // Should be timeout or read error
  14236. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  14237. handle.get_read_error() == Error::Read)
  14238. << "Actual error: " << to_string(handle.get_read_error());
  14239. }
  14240. // Either we got an error, or we got less data than expected
  14241. EXPECT_TRUE(got_error || total < 1000)
  14242. << "Expected timeout but got all " << total << " bytes";
  14243. svr.stop();
  14244. t.join();
  14245. }
  14246. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  14247. // Test connection closed detection via BodyReader
  14248. Server svr;
  14249. std::atomic<bool> close_now{false};
  14250. svr.Get("/will-close", [&](const Request &, Response &res) {
  14251. res.set_content_provider(
  14252. 10000, // Large content_length that we won't fully send
  14253. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  14254. if (offset < 100) {
  14255. std::string data(100, 'X');
  14256. sink.write(data.c_str(), data.size());
  14257. return true;
  14258. }
  14259. // Wait for signal then abort
  14260. while (!close_now) {
  14261. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  14262. }
  14263. return false; // Abort - server will close connection
  14264. });
  14265. });
  14266. auto port = 8092;
  14267. std::thread t([&]() { svr.listen("localhost", port); });
  14268. svr.wait_until_ready();
  14269. Client cli("localhost", port);
  14270. auto handle = cli.open_stream("GET", "/will-close");
  14271. ASSERT_TRUE(handle.is_valid());
  14272. char buf[256];
  14273. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  14274. EXPECT_GT(n, 0) << "First read should succeed";
  14275. // Signal server to close
  14276. close_now = true;
  14277. // Keep reading until error or EOF
  14278. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  14279. // Keep reading
  14280. }
  14281. // Should get an error since content_length wasn't satisfied
  14282. if (n < 0) {
  14283. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  14284. handle.get_read_error() == Error::Read)
  14285. << "Actual error: " << to_string(handle.get_read_error());
  14286. }
  14287. svr.stop();
  14288. t.join();
  14289. }
  14290. #ifdef CPPHTTPLIB_SSL_ENABLED
  14291. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  14292. // Test that read timeout during SSL streaming is detected
  14293. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14294. svr.Get("/slow-stream", [](const Request &, Response &res) {
  14295. res.set_content_provider(
  14296. 1000, "text/plain",
  14297. [](size_t offset, size_t /*length*/, DataSink &sink) {
  14298. if (offset < 100) {
  14299. std::string data(100, 'A');
  14300. sink.write(data.c_str(), data.size());
  14301. return true;
  14302. }
  14303. std::this_thread::sleep_for(std::chrono::seconds(3));
  14304. std::string data(900, 'B');
  14305. sink.write(data.c_str(), data.size());
  14306. return true;
  14307. });
  14308. });
  14309. auto port = 8093;
  14310. std::thread t([&]() { svr.listen("localhost", port); });
  14311. svr.wait_until_ready();
  14312. SSLClient cli("localhost", port);
  14313. cli.enable_server_certificate_verification(false);
  14314. cli.set_read_timeout(1, 0); // 1 second timeout
  14315. auto handle = cli.open_stream("GET", "/slow-stream");
  14316. ASSERT_TRUE(handle.is_valid());
  14317. char buf[256];
  14318. ssize_t total = 0;
  14319. ssize_t n;
  14320. bool got_error = false;
  14321. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  14322. total += n;
  14323. }
  14324. if (n < 0) {
  14325. got_error = true;
  14326. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  14327. handle.get_read_error() == Error::Read)
  14328. << "Actual error: " << to_string(handle.get_read_error());
  14329. }
  14330. EXPECT_TRUE(got_error || total < 1000)
  14331. << "Expected timeout but got all " << total << " bytes";
  14332. svr.stop();
  14333. t.join();
  14334. }
  14335. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  14336. // Test SSL connection closed detection
  14337. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14338. std::atomic<bool> close_now{false};
  14339. svr.Get("/will-close", [&](const Request &, Response &res) {
  14340. res.set_content_provider(
  14341. 10000, "text/plain",
  14342. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  14343. if (offset < 100) {
  14344. std::string data(100, 'X');
  14345. sink.write(data.c_str(), data.size());
  14346. return true;
  14347. }
  14348. while (!close_now) {
  14349. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  14350. }
  14351. return false;
  14352. });
  14353. });
  14354. auto port = 8094;
  14355. std::thread t([&]() { svr.listen("localhost", port); });
  14356. svr.wait_until_ready();
  14357. SSLClient cli("localhost", port);
  14358. cli.enable_server_certificate_verification(false);
  14359. auto handle = cli.open_stream("GET", "/will-close");
  14360. ASSERT_TRUE(handle.is_valid());
  14361. char buf[256];
  14362. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  14363. EXPECT_GT(n, 0);
  14364. // Signal server to close
  14365. close_now = true;
  14366. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  14367. // Keep reading
  14368. }
  14369. if (n < 0) {
  14370. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  14371. handle.get_read_error() == Error::Read)
  14372. << "Actual error: " << to_string(handle.get_read_error());
  14373. }
  14374. svr.stop();
  14375. t.join();
  14376. }
  14377. #endif
  14378. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  14379. using namespace httplib;
  14380. // Create a test file
  14381. const char *fname = "etag_testfile.txt";
  14382. const char *content = "etag-content";
  14383. {
  14384. std::ofstream ofs(fname);
  14385. ofs << content;
  14386. ASSERT_TRUE(ofs.good());
  14387. }
  14388. Server svr;
  14389. svr.set_mount_point("/static", ".");
  14390. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  14391. svr.wait_until_ready();
  14392. Client cli(HOST, PORT);
  14393. // First request: should get 200 with ETag header
  14394. auto res1 = cli.Get("/static/etag_testfile.txt");
  14395. ASSERT_TRUE(res1);
  14396. ASSERT_EQ(200, res1->status);
  14397. ASSERT_TRUE(res1->has_header("ETag"));
  14398. std::string etag = res1->get_header_value("ETag");
  14399. EXPECT_FALSE(etag.empty());
  14400. // Verify ETag format: W/"hex-hex"
  14401. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  14402. EXPECT_EQ('W', etag[0]);
  14403. EXPECT_EQ('/', etag[1]);
  14404. EXPECT_EQ('"', etag[2]);
  14405. EXPECT_EQ('"', etag.back());
  14406. // Exact match: expect 304 Not Modified
  14407. Headers h2 = {{"If-None-Match", etag}};
  14408. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  14409. ASSERT_TRUE(res2);
  14410. EXPECT_EQ(304, res2->status);
  14411. // Wildcard match: expect 304 Not Modified
  14412. Headers h3 = {{"If-None-Match", "*"}};
  14413. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  14414. ASSERT_TRUE(res3);
  14415. EXPECT_EQ(304, res3->status);
  14416. // Non-matching ETag: expect 200
  14417. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  14418. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  14419. ASSERT_TRUE(res4);
  14420. EXPECT_EQ(200, res4->status);
  14421. // Multiple ETags with one matching: expect 304
  14422. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  14423. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  14424. ASSERT_TRUE(res5);
  14425. EXPECT_EQ(304, res5->status);
  14426. svr.stop();
  14427. t.join();
  14428. std::remove(fname);
  14429. }
  14430. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  14431. using namespace httplib;
  14432. Server svr;
  14433. svr.set_mount_point("/static", ".");
  14434. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14435. svr.wait_until_ready();
  14436. Client cli(HOST, PORT);
  14437. // Send If-None-Match: * to a non-existent file
  14438. Headers h = {{"If-None-Match", "*"}};
  14439. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  14440. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14441. EXPECT_EQ(404, res->status);
  14442. svr.stop();
  14443. t.join();
  14444. }
  14445. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  14446. using namespace httplib;
  14447. // Create a test file
  14448. const char *fname = "etag_boundary_testfile.txt";
  14449. const char *content = "boundary-test";
  14450. {
  14451. std::ofstream ofs(fname);
  14452. ofs << content;
  14453. ASSERT_TRUE(ofs.good());
  14454. }
  14455. Server svr;
  14456. svr.set_mount_point("/static", ".");
  14457. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  14458. svr.wait_until_ready();
  14459. Client cli(HOST, PORT);
  14460. // Get the actual ETag
  14461. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  14462. ASSERT_TRUE(res1);
  14463. ASSERT_EQ(200, res1->status);
  14464. ASSERT_TRUE(res1->has_header("ETag"));
  14465. std::string etag = res1->get_header_value("ETag");
  14466. // Test 1: Very long ETag value (longer than actual ETag)
  14467. // Should NOT match and return 200 (not trigger out-of-bounds read)
  14468. Headers h1 = {{"If-None-Match", "W/"
  14469. "\"very-long-etag-value-that-is-much-longer-"
  14470. "than-the-actual-etag-value\""}};
  14471. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  14472. ASSERT_TRUE(res2);
  14473. EXPECT_EQ(200, res2->status); // Should not match
  14474. // Test 2: Long string followed by wildcard
  14475. // Should match on "*" and return 304 (without out-of-bounds read on the long
  14476. // string)
  14477. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  14478. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  14479. ASSERT_TRUE(res3);
  14480. EXPECT_EQ(304, res3->status); // Should match on "*"
  14481. // Test 3: Wildcard followed by long string
  14482. // Should match on "*" immediately and return 304
  14483. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  14484. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  14485. ASSERT_TRUE(res4);
  14486. EXPECT_EQ(304, res4->status); // Should match on "*"
  14487. // Test 4: Multiple long non-matching values
  14488. // Should NOT match and return 200 (test that all comparisons are safe)
  14489. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  14490. "W/\"second-long-non-matching-value\", "
  14491. "W/\"third-long-non-matching-value\""}};
  14492. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  14493. ASSERT_TRUE(res5);
  14494. EXPECT_EQ(200, res5->status); // Should not match
  14495. // Test 5: Single character that is not "*" (edge case)
  14496. Headers h5 = {{"If-None-Match", "X"}};
  14497. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  14498. ASSERT_TRUE(res6);
  14499. EXPECT_EQ(200, res6->status); // Should not match
  14500. svr.stop();
  14501. t.join();
  14502. std::remove(fname);
  14503. }
  14504. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  14505. using namespace httplib;
  14506. // Create a test file
  14507. const char *fname = "ims_testfile.txt";
  14508. const char *content = "if-modified-since-test";
  14509. {
  14510. std::ofstream ofs(fname);
  14511. ofs << content;
  14512. ASSERT_TRUE(ofs.good());
  14513. }
  14514. Server svr;
  14515. svr.set_mount_point("/static", ".");
  14516. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14517. svr.wait_until_ready();
  14518. Client cli(HOST, PORT);
  14519. // First request: should get 200 with Last-Modified header
  14520. auto res1 = cli.Get("/static/ims_testfile.txt");
  14521. ASSERT_TRUE(res1);
  14522. ASSERT_EQ(200, res1->status);
  14523. ASSERT_TRUE(res1->has_header("Last-Modified"));
  14524. std::string last_modified = res1->get_header_value("Last-Modified");
  14525. EXPECT_FALSE(last_modified.empty());
  14526. // If-Modified-Since with same time: expect 304
  14527. Headers h2 = {{"If-Modified-Since", last_modified}};
  14528. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  14529. ASSERT_TRUE(res2);
  14530. EXPECT_EQ(304, res2->status);
  14531. // If-Modified-Since with future time: expect 304
  14532. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  14533. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  14534. ASSERT_TRUE(res3);
  14535. EXPECT_EQ(304, res3->status);
  14536. // If-Modified-Since with past time: expect 200
  14537. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  14538. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  14539. ASSERT_TRUE(res4);
  14540. EXPECT_EQ(200, res4->status);
  14541. // If-None-Match takes precedence over If-Modified-Since
  14542. // (send matching ETag with old If-Modified-Since -> should still be 304)
  14543. ASSERT_TRUE(res1->has_header("ETag"));
  14544. std::string etag = res1->get_header_value("ETag");
  14545. Headers h5 = {{"If-None-Match", etag},
  14546. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  14547. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  14548. ASSERT_TRUE(res5);
  14549. EXPECT_EQ(304, res5->status);
  14550. svr.stop();
  14551. t.join();
  14552. std::remove(fname);
  14553. }
  14554. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  14555. using namespace httplib;
  14556. Server svr;
  14557. // Endpoint that returns compressible content
  14558. svr.Get("/compressible", [](const Request &, Response &res) {
  14559. // Return a large enough body to trigger compression
  14560. std::string body(1000, 'a');
  14561. res.set_content(body, "text/plain");
  14562. });
  14563. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14564. svr.wait_until_ready();
  14565. Client cli(HOST, PORT);
  14566. // Request with gzip support: should get Vary header when compressed
  14567. cli.set_compress(true);
  14568. auto res1 = cli.Get("/compressible");
  14569. ASSERT_TRUE(res1);
  14570. EXPECT_EQ(200, res1->status);
  14571. // If Content-Encoding is set, Vary should also be set
  14572. if (res1->has_header("Content-Encoding")) {
  14573. EXPECT_TRUE(res1->has_header("Vary"));
  14574. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  14575. }
  14576. // Request without Accept-Encoding header: should not have compression
  14577. Headers h_no_compress;
  14578. auto res2 = cli.Get("/compressible", h_no_compress);
  14579. ASSERT_TRUE(res2);
  14580. EXPECT_EQ(200, res2->status);
  14581. // Verify Vary header is present when compression is applied
  14582. // (the exact behavior depends on server configuration)
  14583. svr.stop();
  14584. t.join();
  14585. }
  14586. TEST(ETagTest, IfRangeWithETag) {
  14587. using namespace httplib;
  14588. // Create a test file with known content
  14589. const char *fname = "if_range_testfile.txt";
  14590. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  14591. {
  14592. std::ofstream ofs(fname);
  14593. ofs << content;
  14594. ASSERT_TRUE(ofs.good());
  14595. }
  14596. Server svr;
  14597. svr.set_mount_point("/static", ".");
  14598. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14599. svr.wait_until_ready();
  14600. Client cli(HOST, PORT);
  14601. // First request: get ETag
  14602. auto res1 = cli.Get("/static/if_range_testfile.txt");
  14603. ASSERT_TRUE(res1);
  14604. ASSERT_EQ(200, res1->status);
  14605. ASSERT_TRUE(res1->has_header("ETag"));
  14606. std::string etag = res1->get_header_value("ETag");
  14607. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  14608. // Since our server generates weak ETags (W/"..."), If-Range with our
  14609. // ETag should NOT result in partial content - it should return full content.
  14610. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  14611. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  14612. ASSERT_TRUE(res2);
  14613. // Weak ETag in If-Range -> full content (200), not partial (206)
  14614. EXPECT_EQ(200, res2->status);
  14615. EXPECT_EQ(content, res2->body);
  14616. EXPECT_FALSE(res2->has_header("Content-Range"));
  14617. // Range request with non-matching If-Range (ETag): should get 200 (full
  14618. // content)
  14619. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  14620. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  14621. ASSERT_TRUE(res3);
  14622. EXPECT_EQ(200, res3->status);
  14623. EXPECT_EQ(content, res3->body);
  14624. EXPECT_FALSE(res3->has_header("Content-Range"));
  14625. // Range request with strong ETag (hypothetical - our server doesn't generate
  14626. // strong ETags, but if client sends a strong ETag that doesn't match, it
  14627. // should return full content)
  14628. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  14629. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  14630. ASSERT_TRUE(res4);
  14631. EXPECT_EQ(200, res4->status);
  14632. EXPECT_EQ(content, res4->body);
  14633. EXPECT_FALSE(res4->has_header("Content-Range"));
  14634. svr.stop();
  14635. t.join();
  14636. std::remove(fname);
  14637. }
  14638. TEST(ETagTest, IfRangeWithDate) {
  14639. using namespace httplib;
  14640. // Create a test file
  14641. const char *fname = "if_range_date_testfile.txt";
  14642. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  14643. {
  14644. std::ofstream ofs(fname);
  14645. ofs << content;
  14646. ASSERT_TRUE(ofs.good());
  14647. }
  14648. Server svr;
  14649. svr.set_mount_point("/static", ".");
  14650. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14651. svr.wait_until_ready();
  14652. Client cli(HOST, PORT);
  14653. // First request: get Last-Modified
  14654. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  14655. ASSERT_TRUE(res1);
  14656. ASSERT_EQ(200, res1->status);
  14657. ASSERT_TRUE(res1->has_header("Last-Modified"));
  14658. std::string last_modified = res1->get_header_value("Last-Modified");
  14659. // Range request with matching If-Range (date): should get 206
  14660. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  14661. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  14662. ASSERT_TRUE(res2);
  14663. EXPECT_EQ(206, res2->status);
  14664. EXPECT_EQ("FGHIJ", res2->body);
  14665. // Range request with old If-Range date: should get 200 (full content)
  14666. Headers h3 = {{"Range", "bytes=5-9"},
  14667. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  14668. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  14669. ASSERT_TRUE(res3);
  14670. EXPECT_EQ(200, res3->status);
  14671. EXPECT_EQ(content, res3->body);
  14672. // Range request with future If-Range date: should get 206
  14673. Headers h4 = {{"Range", "bytes=0-4"},
  14674. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  14675. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  14676. ASSERT_TRUE(res4);
  14677. EXPECT_EQ(206, res4->status);
  14678. EXPECT_EQ("ABCDE", res4->body);
  14679. svr.stop();
  14680. t.join();
  14681. std::remove(fname);
  14682. }
  14683. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  14684. using namespace httplib;
  14685. const char *fname = "etag_malformed.txt";
  14686. const char *content = "malformed-etag";
  14687. {
  14688. std::ofstream ofs(fname);
  14689. ofs << content;
  14690. ASSERT_TRUE(ofs.good());
  14691. }
  14692. Server svr;
  14693. svr.set_mount_point("/static", ".");
  14694. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14695. svr.wait_until_ready();
  14696. Client cli(HOST, PORT);
  14697. // baseline: should get 200 and an ETag
  14698. auto res1 = cli.Get("/static/etag_malformed.txt");
  14699. ASSERT_TRUE(res1);
  14700. ASSERT_EQ(200, res1->status);
  14701. ASSERT_TRUE(res1->has_header("ETag"));
  14702. // Malformed ETag value (missing quotes) should be treated as non-matching
  14703. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  14704. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  14705. ASSERT_TRUE(res_bad);
  14706. EXPECT_EQ(200, res_bad->status);
  14707. // Whitespace-only header value should be considered invalid / non-matching
  14708. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  14709. "Host: localhost\r\n"
  14710. "If-None-Match: \r\n"
  14711. "Connection: close\r\n"
  14712. "\r\n";
  14713. std::string out;
  14714. ASSERT_TRUE(send_request(5, raw_req, &out));
  14715. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  14716. svr.stop();
  14717. t.join();
  14718. std::remove(fname);
  14719. }
  14720. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  14721. using namespace httplib;
  14722. const char *fname = "ims_invalid_format.txt";
  14723. const char *content = "ims-bad-format";
  14724. {
  14725. std::ofstream ofs(fname);
  14726. ofs << content;
  14727. ASSERT_TRUE(ofs.good());
  14728. }
  14729. Server svr;
  14730. svr.set_mount_point("/static", ".");
  14731. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14732. svr.wait_until_ready();
  14733. Client cli(HOST, PORT);
  14734. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  14735. ASSERT_TRUE(res1);
  14736. ASSERT_EQ(200, res1->status);
  14737. ASSERT_TRUE(res1->has_header("Last-Modified"));
  14738. // If-Modified-Since with invalid format should not result in 304
  14739. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  14740. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  14741. ASSERT_TRUE(res_bad);
  14742. EXPECT_EQ(200, res_bad->status);
  14743. // If-Range with invalid date format should be treated as mismatch -> full
  14744. // content (200)
  14745. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  14746. {"If-Range", "invalid-date"}};
  14747. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  14748. ASSERT_TRUE(res_ifrange);
  14749. EXPECT_EQ(200, res_ifrange->status);
  14750. svr.stop();
  14751. t.join();
  14752. std::remove(fname);
  14753. }
  14754. TEST(ETagTest, IfRangeWithMalformedETag) {
  14755. using namespace httplib;
  14756. const char *fname = "ifrange_malformed.txt";
  14757. const std::string content = "0123456789";
  14758. {
  14759. std::ofstream ofs(fname);
  14760. ofs << content;
  14761. ASSERT_TRUE(ofs.good());
  14762. }
  14763. Server svr;
  14764. svr.set_mount_point("/static", ".");
  14765. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14766. svr.wait_until_ready();
  14767. Client cli(HOST, PORT);
  14768. // First request: get ETag
  14769. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  14770. ASSERT_TRUE(res1);
  14771. ASSERT_EQ(200, res1->status);
  14772. ASSERT_TRUE(res1->has_header("ETag"));
  14773. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  14774. // full content (200)
  14775. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  14776. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  14777. ASSERT_TRUE(res2);
  14778. EXPECT_EQ(200, res2->status);
  14779. EXPECT_EQ(content, res2->body);
  14780. svr.stop();
  14781. t.join();
  14782. std::remove(fname);
  14783. }
  14784. TEST(ETagTest, ExtremeLargeDateValues) {
  14785. using namespace httplib;
  14786. const char *fname = "ims_extreme_date.txt";
  14787. const char *content = "ims-extreme-date";
  14788. {
  14789. std::ofstream ofs(fname);
  14790. ofs << content;
  14791. ASSERT_TRUE(ofs.good());
  14792. }
  14793. Server svr;
  14794. svr.set_mount_point("/static", ".");
  14795. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14796. svr.wait_until_ready();
  14797. Client cli(HOST, PORT);
  14798. auto res1 = cli.Get(std::string("/static/") + fname);
  14799. ASSERT_TRUE(res1);
  14800. ASSERT_EQ(200, res1->status);
  14801. ASSERT_TRUE(res1->has_header("Last-Modified"));
  14802. // Extremely large year that may overflow date parsing routines.
  14803. Headers h_large_date = {
  14804. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  14805. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  14806. ASSERT_TRUE(res_bad);
  14807. // Expect server to treat this as invalid/mismatch and return full content
  14808. EXPECT_EQ(200, res_bad->status);
  14809. // If-Range with extremely large date should be treated as mismatch -> full
  14810. // content (200)
  14811. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  14812. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  14813. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  14814. ASSERT_TRUE(res_ifrange);
  14815. EXPECT_EQ(200, res_ifrange->status);
  14816. svr.stop();
  14817. t.join();
  14818. std::remove(fname);
  14819. }
  14820. TEST(ETagTest, NegativeFileModificationTime) {
  14821. using namespace httplib;
  14822. const char *fname = "ims_negative_mtime.txt";
  14823. const std::string content = "negative-mtime";
  14824. {
  14825. std::ofstream ofs(fname);
  14826. ofs << content;
  14827. ASSERT_TRUE(ofs.good());
  14828. }
  14829. // Try to set file mtime to a negative value. This may fail on some
  14830. // platforms/filesystems; if it fails, the test will still verify server
  14831. // behaves safely by performing a regular conditional request.
  14832. #if defined(__APPLE__) || defined(__linux__)
  14833. bool set_negative = false;
  14834. do {
  14835. struct timeval times[2];
  14836. // access time: now
  14837. times[0].tv_sec = time(nullptr);
  14838. times[0].tv_usec = 0;
  14839. // modification time: negative (e.g., -1)
  14840. times[1].tv_sec = -1;
  14841. times[1].tv_usec = 0;
  14842. if (utimes(fname, times) == 0) { set_negative = true; }
  14843. } while (0);
  14844. #else
  14845. bool set_negative = false;
  14846. #endif
  14847. Server svr;
  14848. svr.set_mount_point("/static", ".");
  14849. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14850. svr.wait_until_ready();
  14851. Client cli(HOST, PORT);
  14852. auto res1 = cli.Get(std::string("/static/") + fname);
  14853. ASSERT_TRUE(res1);
  14854. ASSERT_EQ(200, res1->status);
  14855. bool has_last_modified = res1->has_header("Last-Modified");
  14856. std::string last_modified;
  14857. if (has_last_modified) {
  14858. last_modified = res1->get_header_value("Last-Modified");
  14859. }
  14860. if (set_negative) {
  14861. // If we successfully set a negative mtime, ensure server returns a
  14862. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  14863. // with an old date and ensure server handles it without crash.
  14864. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  14865. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  14866. ASSERT_TRUE(res2);
  14867. // Behavior may vary; at minimum ensure server responds (200 or 304).
  14868. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  14869. } else {
  14870. // Could not set negative mtime on this platform; fall back to verifying
  14871. // that normal invalid/malformed dates are treated safely (non-304).
  14872. Headers h_bad_date = {
  14873. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  14874. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  14875. ASSERT_TRUE(res_bad);
  14876. EXPECT_EQ(200, res_bad->status);
  14877. }
  14878. svr.stop();
  14879. t.join();
  14880. std::remove(fname);
  14881. }
  14882. //==============================================================================
  14883. // SSE Parsing Tests
  14884. //==============================================================================
  14885. class SSEParsingTest : public ::testing::Test {
  14886. protected:
  14887. // Test helper that mimics SSE parsing behavior
  14888. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  14889. int &retry_ms) {
  14890. // Blank line signals end of event
  14891. if (line.empty() || line == "\r") { return true; }
  14892. // Lines starting with ':' are comments (ignored)
  14893. if (!line.empty() && line[0] == ':') { return false; }
  14894. // Find the colon separator
  14895. auto colon_pos = line.find(':');
  14896. if (colon_pos == std::string::npos) {
  14897. // Line with no colon is treated as field name with empty value
  14898. return false;
  14899. }
  14900. std::string field = line.substr(0, colon_pos);
  14901. std::string value;
  14902. // Value starts after colon, skip optional single space
  14903. if (colon_pos + 1 < line.size()) {
  14904. size_t value_start = colon_pos + 1;
  14905. if (line[value_start] == ' ') { value_start++; }
  14906. value = line.substr(value_start);
  14907. // Remove trailing \r if present
  14908. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  14909. }
  14910. // Handle known fields
  14911. if (field == "event") {
  14912. msg.event = value;
  14913. } else if (field == "data") {
  14914. // Multiple data lines are concatenated with newlines
  14915. if (!msg.data.empty()) { msg.data += "\n"; }
  14916. msg.data += value;
  14917. } else if (field == "id") {
  14918. // Empty id is valid (clears the last event ID)
  14919. msg.id = value;
  14920. } else if (field == "retry") {
  14921. // Parse retry interval in milliseconds
  14922. {
  14923. int v = 0;
  14924. auto res =
  14925. detail::from_chars(value.data(), value.data() + value.size(), v);
  14926. if (res.ec == std::errc{}) { retry_ms = v; }
  14927. }
  14928. }
  14929. // Unknown fields are ignored per SSE spec
  14930. return false;
  14931. }
  14932. };
  14933. // Test: Single-line data
  14934. TEST_F(SSEParsingTest, SingleLineData) {
  14935. sse::SSEMessage msg;
  14936. int retry_ms = 3000;
  14937. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  14938. EXPECT_EQ(msg.data, "hello");
  14939. EXPECT_EQ(msg.event, "message");
  14940. // Blank line ends event
  14941. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  14942. }
  14943. // Test: Multi-line data
  14944. TEST_F(SSEParsingTest, MultiLineData) {
  14945. sse::SSEMessage msg;
  14946. int retry_ms = 3000;
  14947. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  14948. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  14949. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  14950. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  14951. }
  14952. // Test: Custom event types
  14953. TEST_F(SSEParsingTest, CustomEventType) {
  14954. sse::SSEMessage msg;
  14955. int retry_ms = 3000;
  14956. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  14957. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  14958. EXPECT_EQ(msg.event, "update");
  14959. EXPECT_EQ(msg.data, "payload");
  14960. }
  14961. // Test: Event ID handling
  14962. TEST_F(SSEParsingTest, EventIdHandling) {
  14963. sse::SSEMessage msg;
  14964. int retry_ms = 3000;
  14965. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  14966. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  14967. EXPECT_EQ(msg.id, "12345");
  14968. }
  14969. // Test: Empty event ID (clears last event ID)
  14970. TEST_F(SSEParsingTest, EmptyEventId) {
  14971. sse::SSEMessage msg;
  14972. msg.id = "previous";
  14973. int retry_ms = 3000;
  14974. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  14975. EXPECT_EQ(msg.id, "");
  14976. }
  14977. // Test: Retry field parsing
  14978. TEST_F(SSEParsingTest, RetryFieldParsing) {
  14979. sse::SSEMessage msg;
  14980. int retry_ms = 3000;
  14981. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  14982. EXPECT_EQ(retry_ms, 5000);
  14983. }
  14984. // Test: Invalid retry value
  14985. TEST_F(SSEParsingTest, InvalidRetryValue) {
  14986. sse::SSEMessage msg;
  14987. int retry_ms = 3000;
  14988. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  14989. EXPECT_EQ(retry_ms, 3000); // Unchanged
  14990. }
  14991. // Test: Comments (lines starting with :)
  14992. TEST_F(SSEParsingTest, CommentsIgnored) {
  14993. sse::SSEMessage msg;
  14994. int retry_ms = 3000;
  14995. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  14996. EXPECT_EQ(msg.data, "");
  14997. EXPECT_EQ(msg.event, "message");
  14998. }
  14999. // Test: Colon in value
  15000. TEST_F(SSEParsingTest, ColonInValue) {
  15001. sse::SSEMessage msg;
  15002. int retry_ms = 3000;
  15003. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  15004. EXPECT_EQ(msg.data, "hello:world:test");
  15005. }
  15006. // Test: Line with no colon (field name only)
  15007. TEST_F(SSEParsingTest, FieldNameOnly) {
  15008. sse::SSEMessage msg;
  15009. int retry_ms = 3000;
  15010. // According to SSE spec, this is treated as field name with empty value
  15011. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  15012. // Since we don't recognize "data" without colon, data should be empty
  15013. EXPECT_EQ(msg.data, "");
  15014. }
  15015. // Test: Trailing \r handling
  15016. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  15017. sse::SSEMessage msg;
  15018. int retry_ms = 3000;
  15019. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  15020. EXPECT_EQ(msg.data, "hello");
  15021. }
  15022. // Test: Unknown fields ignored
  15023. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  15024. sse::SSEMessage msg;
  15025. int retry_ms = 3000;
  15026. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  15027. EXPECT_EQ(msg.data, "");
  15028. EXPECT_EQ(msg.event, "message");
  15029. }
  15030. // Test: Space after colon is optional
  15031. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  15032. sse::SSEMessage msg1, msg2;
  15033. int retry_ms = 3000;
  15034. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  15035. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  15036. EXPECT_EQ(msg1.data, "hello");
  15037. EXPECT_EQ(msg2.data, "hello");
  15038. }
  15039. // Test: SSEMessage clear
  15040. TEST_F(SSEParsingTest, MessageClear) {
  15041. sse::SSEMessage msg;
  15042. msg.event = "custom";
  15043. msg.data = "some data";
  15044. msg.id = "123";
  15045. msg.clear();
  15046. EXPECT_EQ(msg.event, "message");
  15047. EXPECT_EQ(msg.data, "");
  15048. EXPECT_EQ(msg.id, "");
  15049. }
  15050. // Test: Complete event parsing
  15051. TEST_F(SSEParsingTest, CompleteEventParsing) {
  15052. sse::SSEMessage msg;
  15053. int retry_ms = 3000;
  15054. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  15055. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  15056. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  15057. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  15058. // Blank line ends event
  15059. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  15060. EXPECT_EQ(msg.event, "notification");
  15061. EXPECT_EQ(msg.id, "evt-42");
  15062. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  15063. EXPECT_EQ(retry_ms, 1000);
  15064. }
  15065. //==============================================================================
  15066. // Integration Tests with Server
  15067. //==============================================================================
  15068. class SSEIntegrationTest : public ::testing::Test {
  15069. protected:
  15070. void SetUp() override {
  15071. stop_server_.store(false);
  15072. events_.clear();
  15073. server_ = httplib::detail::make_unique<Server>();
  15074. setup_server();
  15075. start_server();
  15076. }
  15077. void TearDown() override {
  15078. stop_server_.store(true);
  15079. event_cv_.notify_all();
  15080. server_->stop();
  15081. if (server_thread_.joinable()) { server_thread_.join(); }
  15082. }
  15083. void setup_server() {
  15084. // Simple SSE endpoint
  15085. server_->Get("/events", [this](const Request &req, Response &res) {
  15086. auto last_id = req.get_header_value("Last-Event-ID");
  15087. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  15088. res.set_chunked_content_provider(
  15089. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  15090. std::unique_lock<std::mutex> lock(event_mutex_);
  15091. if (event_cv_.wait_for(
  15092. lock, std::chrono::milliseconds(200), [this] {
  15093. return !events_.empty() || stop_server_.load();
  15094. })) {
  15095. if (stop_server_.load()) { return false; }
  15096. if (!events_.empty()) {
  15097. std::string event = events_.front();
  15098. events_.erase(events_.begin());
  15099. sink.write(event.data(), event.size());
  15100. return true;
  15101. }
  15102. }
  15103. return !stop_server_.load();
  15104. });
  15105. });
  15106. // Endpoint that returns error
  15107. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  15108. res.status = 500;
  15109. res.set_content("Internal Server Error", "text/plain");
  15110. });
  15111. // Endpoint for custom event types
  15112. server_->Get("/custom-events", [](const Request &, Response &res) {
  15113. res.set_chunked_content_provider(
  15114. "text/event-stream", [](size_t offset, DataSink &sink) {
  15115. if (offset == 0) {
  15116. std::string event = "event: update\ndata: updated\n\n"
  15117. "event: delete\ndata: deleted\n\n";
  15118. sink.write(event.data(), event.size());
  15119. }
  15120. return false; // End stream after sending
  15121. });
  15122. });
  15123. }
  15124. void start_server() {
  15125. port_ = server_->bind_to_any_port(HOST);
  15126. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  15127. // Wait for server to start
  15128. while (!server_->is_running()) {
  15129. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  15130. }
  15131. }
  15132. int get_port() const { return port_; }
  15133. void send_event(const std::string &event) {
  15134. std::lock_guard<std::mutex> lock(event_mutex_);
  15135. events_.push_back(event);
  15136. event_cv_.notify_all();
  15137. }
  15138. std::unique_ptr<Server> server_;
  15139. std::thread server_thread_;
  15140. std::mutex event_mutex_;
  15141. std::condition_variable event_cv_;
  15142. std::vector<std::string> events_;
  15143. std::atomic<bool> stop_server_{false};
  15144. std::string last_received_event_id_;
  15145. int port_ = 0;
  15146. };
  15147. // Test: Successful connection and on_open callback
  15148. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  15149. // Add a simple endpoint that sends one event and closes
  15150. server_->Get("/simple-event", [](const Request &, Response &res) {
  15151. res.set_chunked_content_provider(
  15152. "text/event-stream", [](size_t offset, DataSink &sink) {
  15153. if (offset == 0) {
  15154. std::string event = "data: hello\n\n";
  15155. sink.write(event.data(), event.size());
  15156. }
  15157. return false; // Close stream after sending
  15158. });
  15159. });
  15160. Client client("localhost", get_port());
  15161. sse::SSEClient sse(client, "/simple-event");
  15162. std::atomic<bool> open_called{false};
  15163. std::atomic<bool> message_received{false};
  15164. sse.on_open([&open_called]() { open_called.store(true); });
  15165. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  15166. if (msg.data == "hello") { message_received.store(true); }
  15167. });
  15168. sse.set_reconnect_interval(100);
  15169. sse.set_max_reconnect_attempts(1);
  15170. // Start async
  15171. sse.start_async();
  15172. // Wait for message to be processed
  15173. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  15174. sse.stop();
  15175. EXPECT_TRUE(open_called.load());
  15176. EXPECT_TRUE(message_received.load());
  15177. }
  15178. // Test: on_message callback
  15179. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  15180. // Endpoint that sends multiple events then closes
  15181. server_->Get("/multi-event", [](const Request &, Response &res) {
  15182. res.set_chunked_content_provider(
  15183. "text/event-stream", [](size_t offset, DataSink &sink) {
  15184. if (offset == 0) {
  15185. std::string events = "data: message1\n\ndata: message2\n\n";
  15186. sink.write(events.data(), events.size());
  15187. }
  15188. return false;
  15189. });
  15190. });
  15191. Client client("localhost", get_port());
  15192. sse::SSEClient sse(client, "/multi-event");
  15193. std::vector<std::string> received_messages;
  15194. std::mutex messages_mutex;
  15195. sse.on_message([&](const sse::SSEMessage &msg) {
  15196. std::lock_guard<std::mutex> lock(messages_mutex);
  15197. received_messages.push_back(msg.data);
  15198. });
  15199. sse.set_reconnect_interval(100);
  15200. sse.set_max_reconnect_attempts(1);
  15201. sse.start_async();
  15202. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  15203. sse.stop();
  15204. std::lock_guard<std::mutex> lock(messages_mutex);
  15205. EXPECT_GE(received_messages.size(), 2u);
  15206. if (received_messages.size() >= 2) {
  15207. EXPECT_EQ(received_messages[0], "message1");
  15208. EXPECT_EQ(received_messages[1], "message2");
  15209. }
  15210. }
  15211. // Test: on_event for specific types
  15212. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  15213. Client client("localhost", get_port());
  15214. sse::SSEClient sse(client, "/custom-events");
  15215. std::atomic<bool> update_received{false};
  15216. std::atomic<bool> delete_received{false};
  15217. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  15218. if (msg.data == "updated") { update_received.store(true); }
  15219. });
  15220. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  15221. if (msg.data == "deleted") { delete_received.store(true); }
  15222. });
  15223. sse.set_max_reconnect_attempts(1);
  15224. sse.start_async();
  15225. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  15226. sse.stop();
  15227. EXPECT_TRUE(update_received.load());
  15228. EXPECT_TRUE(delete_received.load());
  15229. }
  15230. // Test: on_error callback on connection failure
  15231. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  15232. // Connect to a non-existent port
  15233. Client client("localhost", 59999);
  15234. sse::SSEClient sse(client, "/events");
  15235. std::atomic<bool> error_called{false};
  15236. Error received_error = Error::Success;
  15237. sse.on_error([&](Error err) {
  15238. error_called.store(true);
  15239. received_error = err;
  15240. });
  15241. sse.set_reconnect_interval(50);
  15242. sse.set_max_reconnect_attempts(1);
  15243. sse.start_async();
  15244. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  15245. sse.stop();
  15246. EXPECT_TRUE(error_called.load());
  15247. EXPECT_NE(received_error, Error::Success);
  15248. }
  15249. // Test: Last-Event-ID header sent on reconnect
  15250. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  15251. // Endpoint that sends event with ID
  15252. server_->Get("/event-with-id", [](const Request &, Response &res) {
  15253. res.set_chunked_content_provider(
  15254. "text/event-stream", [](size_t offset, DataSink &sink) {
  15255. if (offset == 0) {
  15256. std::string event = "id: evt-123\ndata: test\n\n";
  15257. sink.write(event.data(), event.size());
  15258. }
  15259. return false;
  15260. });
  15261. });
  15262. Client client("localhost", get_port());
  15263. sse::SSEClient sse(client, "/event-with-id");
  15264. std::atomic<bool> id_received{false};
  15265. sse.on_message([&](const sse::SSEMessage &msg) {
  15266. if (!msg.id.empty()) { id_received.store(true); }
  15267. });
  15268. sse.set_reconnect_interval(100);
  15269. sse.set_max_reconnect_attempts(1);
  15270. sse.start_async();
  15271. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  15272. sse.stop();
  15273. EXPECT_TRUE(id_received.load());
  15274. EXPECT_EQ(sse.last_event_id(), "evt-123");
  15275. }
  15276. // Test: Manual stop
  15277. TEST_F(SSEIntegrationTest, ManualStop) {
  15278. // Endpoint that sends one event and stays open briefly
  15279. std::atomic<bool> handler_running{true};
  15280. server_->Get("/stay-open", [&handler_running](const Request &,
  15281. Response &res) {
  15282. res.set_chunked_content_provider(
  15283. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  15284. if (offset == 0) {
  15285. std::string event = "data: connected\n\n";
  15286. sink.write(event.data(), event.size());
  15287. }
  15288. // Keep connection open while handler_running is true
  15289. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  15290. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  15291. }
  15292. return false;
  15293. });
  15294. });
  15295. Client client("localhost", get_port());
  15296. sse::SSEClient sse(client, "/stay-open");
  15297. std::atomic<bool> connected{false};
  15298. sse.on_open([&connected]() { connected.store(true); });
  15299. sse.set_reconnect_interval(100);
  15300. sse.set_max_reconnect_attempts(1);
  15301. sse.start_async();
  15302. // Wait for connection to establish
  15303. for (int i = 0; i < 20 && !connected.load(); ++i) {
  15304. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  15305. }
  15306. EXPECT_TRUE(connected.load());
  15307. EXPECT_TRUE(sse.is_connected());
  15308. // Signal handler to stop
  15309. handler_running.store(false);
  15310. // Stop SSE client
  15311. sse.stop();
  15312. EXPECT_FALSE(sse.is_connected());
  15313. }
  15314. // Test: SSEClient with custom headers
  15315. TEST_F(SSEIntegrationTest, CustomHeaders) {
  15316. // Setup a server endpoint that checks for custom header
  15317. std::atomic<bool> header_received{false};
  15318. server_->Get("/header-check", [&](const Request &req, Response &res) {
  15319. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  15320. header_received.store(true);
  15321. }
  15322. res.set_chunked_content_provider("text/event-stream",
  15323. [](size_t, DataSink &) { return false; });
  15324. });
  15325. Client client("localhost", get_port());
  15326. Headers headers = {{"X-Custom-Header", "custom-value"}};
  15327. sse::SSEClient sse(client, "/header-check", headers);
  15328. sse.set_max_reconnect_attempts(1);
  15329. sse.start_async();
  15330. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  15331. sse.stop();
  15332. EXPECT_TRUE(header_received.load());
  15333. }
  15334. // Test: Reconnect interval configuration
  15335. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  15336. Client client("localhost", get_port());
  15337. sse::SSEClient sse(client, "/events");
  15338. auto &result = sse.set_reconnect_interval(500);
  15339. // Builder pattern should return reference to self
  15340. EXPECT_EQ(&result, &sse);
  15341. }
  15342. // Test: Max reconnect attempts
  15343. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  15344. // Connect to non-existent port to force reconnects
  15345. Client client("localhost", 59998);
  15346. sse::SSEClient sse(client, "/events");
  15347. std::atomic<int> error_count{0};
  15348. sse.on_error([&](Error) { error_count.fetch_add(1); });
  15349. sse.set_reconnect_interval(50);
  15350. sse.set_max_reconnect_attempts(2);
  15351. auto start = std::chrono::steady_clock::now();
  15352. sse.start(); // Blocking call
  15353. auto end = std::chrono::steady_clock::now();
  15354. // Should have stopped after 2 failed attempts
  15355. EXPECT_GE(error_count.load(), 2);
  15356. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  15357. auto duration =
  15358. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  15359. #ifdef _WIN32
  15360. // Windows is much slower for socket connection failures
  15361. EXPECT_LT(duration.count(), 7000);
  15362. #else
  15363. EXPECT_LT(duration.count(), 1000);
  15364. #endif
  15365. }
  15366. // Test: Multi-line data in integration
  15367. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  15368. // Endpoint with multi-line data
  15369. server_->Get("/multiline-data", [](const Request &, Response &res) {
  15370. res.set_chunked_content_provider(
  15371. "text/event-stream", [](size_t offset, DataSink &sink) {
  15372. if (offset == 0) {
  15373. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  15374. sink.write(event.data(), event.size());
  15375. }
  15376. return false;
  15377. });
  15378. });
  15379. Client client("localhost", get_port());
  15380. sse::SSEClient sse(client, "/multiline-data");
  15381. std::string received_data;
  15382. std::mutex data_mutex;
  15383. sse.on_message([&](const sse::SSEMessage &msg) {
  15384. std::lock_guard<std::mutex> lock(data_mutex);
  15385. received_data = msg.data;
  15386. });
  15387. sse.set_reconnect_interval(100);
  15388. sse.set_max_reconnect_attempts(1);
  15389. sse.start_async();
  15390. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  15391. sse.stop();
  15392. std::lock_guard<std::mutex> lock(data_mutex);
  15393. EXPECT_EQ(received_data, "line1\nline2\nline3");
  15394. }
  15395. // Test: Auto-reconnect after server disconnection
  15396. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  15397. std::atomic<int> connection_count{0};
  15398. std::atomic<int> message_count{0};
  15399. // Endpoint that sends one event and closes, forcing reconnect
  15400. server_->Get("/reconnect-test",
  15401. [&connection_count](const Request &, Response &res) {
  15402. connection_count.fetch_add(1);
  15403. res.set_chunked_content_provider(
  15404. "text/event-stream", [](size_t offset, DataSink &sink) {
  15405. if (offset == 0) {
  15406. std::string event = "data: hello\n\n";
  15407. sink.write(event.data(), event.size());
  15408. }
  15409. return false; // Close connection after sending
  15410. });
  15411. });
  15412. Client client("localhost", get_port());
  15413. sse::SSEClient sse(client, "/reconnect-test");
  15414. sse.on_message([&message_count](const sse::SSEMessage &) {
  15415. message_count.fetch_add(1);
  15416. });
  15417. sse.set_reconnect_interval(100);
  15418. sse.set_max_reconnect_attempts(3);
  15419. sse.start_async();
  15420. // Wait long enough for multiple reconnects
  15421. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  15422. sse.stop();
  15423. // Should have connected multiple times (initial + reconnects)
  15424. EXPECT_GE(connection_count.load(), 2);
  15425. // Should have received messages from multiple connections
  15426. EXPECT_GE(message_count.load(), 2);
  15427. }
  15428. // Test: Last-Event-ID sent on reconnect
  15429. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  15430. std::atomic<int> connection_count{0};
  15431. std::vector<std::string> received_last_event_ids;
  15432. std::mutex id_mutex;
  15433. // Endpoint that checks Last-Event-ID header and sends event with ID
  15434. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  15435. int conn = connection_count.fetch_add(1);
  15436. // Capture the Last-Event-ID header from each connection
  15437. {
  15438. std::lock_guard<std::mutex> lock(id_mutex);
  15439. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  15440. }
  15441. res.set_chunked_content_provider(
  15442. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  15443. if (offset == 0) {
  15444. std::string event =
  15445. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  15446. sink.write(event.data(), event.size());
  15447. }
  15448. return false;
  15449. });
  15450. });
  15451. Client client("localhost", get_port());
  15452. sse::SSEClient sse(client, "/reconnect-with-id");
  15453. sse.set_reconnect_interval(100);
  15454. sse.set_max_reconnect_attempts(3);
  15455. sse.start_async();
  15456. // Wait for at least 2 connections
  15457. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  15458. sse.stop();
  15459. // Verify behavior
  15460. std::lock_guard<std::mutex> lock(id_mutex);
  15461. EXPECT_GE(received_last_event_ids.size(), 2u);
  15462. // First connection should have no Last-Event-ID
  15463. if (!received_last_event_ids.empty()) {
  15464. EXPECT_EQ(received_last_event_ids[0], "");
  15465. }
  15466. // Second connection should have Last-Event-ID from first connection
  15467. if (received_last_event_ids.size() >= 2) {
  15468. EXPECT_EQ(received_last_event_ids[1], "event-0");
  15469. }
  15470. }
  15471. // Test: set_headers updates headers used on reconnect
  15472. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  15473. std::vector<std::string> received_tokens;
  15474. std::mutex token_mutex;
  15475. // Endpoint that captures Authorization header
  15476. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  15477. {
  15478. std::lock_guard<std::mutex> lock(token_mutex);
  15479. received_tokens.push_back(req.get_header_value("Authorization"));
  15480. }
  15481. res.set_chunked_content_provider(
  15482. "text/event-stream", [](size_t offset, DataSink &sink) {
  15483. if (offset == 0) {
  15484. std::string event = "data: hello\n\n";
  15485. sink.write(event.data(), event.size());
  15486. }
  15487. return false; // Close connection to trigger reconnect
  15488. });
  15489. });
  15490. Client client("localhost", get_port());
  15491. Headers headers = {{"Authorization", "Bearer old-token"}};
  15492. sse::SSEClient sse(client, "/auth-check", headers);
  15493. // Update headers on each successful connection
  15494. sse.on_open(
  15495. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  15496. sse.set_reconnect_interval(100);
  15497. sse.set_max_reconnect_attempts(3);
  15498. sse.start_async();
  15499. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  15500. sse.stop();
  15501. std::lock_guard<std::mutex> lock(token_mutex);
  15502. ASSERT_GE(received_tokens.size(), 2u);
  15503. // First connection uses original header
  15504. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  15505. // Second connection uses updated header from set_headers
  15506. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  15507. }
  15508. // Test: 401 allows reconnection (so on_error can refresh headers)
  15509. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  15510. std::atomic<int> connection_count{0};
  15511. // Endpoint: returns 401 on first attempt, 200 on second
  15512. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  15513. int conn = connection_count.fetch_add(1);
  15514. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  15515. res.status = StatusCode::Unauthorized_401;
  15516. res.set_content("Unauthorized", "text/plain");
  15517. return;
  15518. }
  15519. res.set_chunked_content_provider(
  15520. "text/event-stream", [](size_t offset, DataSink &sink) {
  15521. if (offset == 0) {
  15522. std::string event = "data: authenticated\n\n";
  15523. sink.write(event.data(), event.size());
  15524. }
  15525. return false;
  15526. });
  15527. });
  15528. Client client("localhost", get_port());
  15529. Headers headers = {{"Authorization", "Bearer expired"}};
  15530. sse::SSEClient sse(client, "/auth-retry", headers);
  15531. std::atomic<bool> message_received{false};
  15532. // Refresh token on error
  15533. sse.on_error(
  15534. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  15535. sse.on_message([&](const sse::SSEMessage &msg) {
  15536. if (msg.data == "authenticated") { message_received.store(true); }
  15537. });
  15538. sse.set_reconnect_interval(100);
  15539. sse.set_max_reconnect_attempts(3);
  15540. sse.start_async();
  15541. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  15542. sse.stop();
  15543. // Should have reconnected after 401 and succeeded with new token
  15544. EXPECT_GE(connection_count.load(), 2);
  15545. EXPECT_TRUE(message_received.load());
  15546. }
  15547. TEST(Issue2318Test, EmptyHostString) {
  15548. {
  15549. httplib::Client cli_empty("", PORT);
  15550. auto res = cli_empty.Get("/");
  15551. ASSERT_FALSE(res);
  15552. EXPECT_EQ(httplib::Error::Connection, res.error());
  15553. }
  15554. {
  15555. httplib::Client cli(" ", PORT);
  15556. auto res = cli.Get("/");
  15557. ASSERT_FALSE(res);
  15558. EXPECT_EQ(httplib::Error::Connection, res.error());
  15559. }
  15560. }
  15561. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  15562. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  15563. Server svr;
  15564. // Set a small payload limit (1KB)
  15565. svr.set_payload_max_length(1024);
  15566. svr.Post("/test", [&](const Request &req, Response &res) {
  15567. res.set_content("Body size: " + std::to_string(req.body.size()),
  15568. "text/plain");
  15569. });
  15570. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15571. auto se = detail::scope_exit([&] {
  15572. svr.stop();
  15573. listen_thread.join();
  15574. });
  15575. svr.wait_until_ready();
  15576. // Create data that compresses well but exceeds limit when decompressed
  15577. // 8KB of repeated null bytes compresses to a very small size
  15578. std::string original_data(8 * 1024, '\0');
  15579. // Compress the data using gzip
  15580. std::string compressed_data;
  15581. detail::gzip_compressor compressor;
  15582. compressor.compress(original_data.data(), original_data.size(), true,
  15583. [&](const char *data, size_t size) {
  15584. compressed_data.append(data, size);
  15585. return true;
  15586. });
  15587. // Verify compression worked (compressed should be much smaller)
  15588. ASSERT_LT(compressed_data.size(), original_data.size());
  15589. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  15590. // Send compressed data with Content-Encoding: gzip
  15591. Client cli(HOST, PORT);
  15592. Headers headers = {{"Content-Encoding", "gzip"}};
  15593. auto res =
  15594. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  15595. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  15596. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15597. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  15598. }
  15599. #endif
  15600. // ============================================================================
  15601. // OpenSSL-Specific Tests
  15602. // ============================================================================
  15603. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  15604. X509 *readCertificate(const std::string &strFileName) {
  15605. std::ifstream inStream(strFileName);
  15606. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  15607. std::istreambuf_iterator<char>());
  15608. if (strCertPEM.empty()) return (nullptr);
  15609. BIO *pbCert = BIO_new(BIO_s_mem());
  15610. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  15611. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  15612. BIO_free(pbCert);
  15613. return (pCert);
  15614. }
  15615. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  15616. std::ifstream inStream(strFileName);
  15617. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  15618. std::istreambuf_iterator<char>());
  15619. if (strPrivateKeyPEM.empty()) return (nullptr);
  15620. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  15621. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  15622. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  15623. BIO_free(pbPrivKey);
  15624. return (pPrivateKey);
  15625. }
  15626. TEST(BindServerTest, UpdateCerts) {
  15627. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  15628. int port = svr.bind_to_any_port("0.0.0.0");
  15629. ASSERT_TRUE(svr.is_valid());
  15630. ASSERT_TRUE(port > 0);
  15631. X509 *cert = readCertificate(SERVER_CERT_FILE);
  15632. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  15633. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  15634. ASSERT_TRUE(cert != nullptr);
  15635. ASSERT_TRUE(ca_cert != nullptr);
  15636. ASSERT_TRUE(key != nullptr);
  15637. X509_STORE *cert_store = X509_STORE_new();
  15638. X509_STORE_add_cert(cert_store, ca_cert);
  15639. // svr.update_certs(cert, key, cert_store); // deprecated
  15640. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  15641. CLIENT_CA_CERT_FILE);
  15642. ASSERT_TRUE(svr.is_valid());
  15643. svr.stop();
  15644. X509_STORE_free(cert_store);
  15645. X509_free(cert);
  15646. X509_free(ca_cert);
  15647. EVP_PKEY_free(key);
  15648. }
  15649. // Test that update_certs() updates client CA list correctly
  15650. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  15651. // Start with file-based constructor
  15652. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15653. ASSERT_TRUE(svr.is_valid());
  15654. // Initially no client CA list should be set
  15655. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  15656. ASSERT_TRUE(ssl_ctx != nullptr);
  15657. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  15658. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  15659. EXPECT_EQ(0, count_before);
  15660. // Now update with client CA (PEM string)
  15661. std::string cert_pem, key_pem, ca_pem;
  15662. read_file(SERVER_CERT_FILE, cert_pem);
  15663. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  15664. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  15665. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  15666. ASSERT_TRUE(svr.is_valid());
  15667. // Now client CA list should be set
  15668. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  15669. ASSERT_TRUE(ca_list_after != nullptr);
  15670. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  15671. }
  15672. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  15673. // Test that the file-path SSLServer constructor properly sets the client CA
  15674. // list that is sent to clients during the TLS handshake (CertificateRequest)
  15675. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  15676. ASSERT_TRUE(svr.is_valid());
  15677. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  15678. ASSERT_TRUE(ssl_ctx != nullptr);
  15679. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  15680. ASSERT_TRUE(ca_list != nullptr);
  15681. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  15682. }
  15683. #endif
  15684. // ============================================================================
  15685. // MbedTLS-Specific Tests
  15686. // ============================================================================
  15687. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  15688. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  15689. using namespace httplib::tls;
  15690. // Track if callback was invoked
  15691. bool callback_invoked = false;
  15692. // The callback receives void* ctx which is actually MbedTlsContext*
  15693. // We can access the mbedtls_ssl_config via the context
  15694. auto setup_callback = [&callback_invoked](void *ctx) {
  15695. callback_invoked = true;
  15696. // Cast to MbedTlsContext* to access the ssl config
  15697. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  15698. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  15699. // Use static variables to hold certificate data (simplified for test)
  15700. static mbedtls_x509_crt own_cert;
  15701. static mbedtls_pk_context own_key;
  15702. static mbedtls_x509_crt ca_chain;
  15703. static bool initialized = false;
  15704. if (!initialized) {
  15705. mbedtls_x509_crt_init(&own_cert);
  15706. mbedtls_pk_init(&own_key);
  15707. mbedtls_x509_crt_init(&ca_chain);
  15708. // Load server certificate
  15709. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  15710. return false;
  15711. }
  15712. // Load server private key.
  15713. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  15714. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  15715. #if MBEDTLS_VERSION_MAJOR == 3
  15716. ,
  15717. mbedtls_ctr_drbg_random, nullptr
  15718. #endif
  15719. ) != 0) {
  15720. return false;
  15721. }
  15722. // Load CA chain for client verification
  15723. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  15724. return false;
  15725. }
  15726. initialized = true;
  15727. }
  15728. // Configure the SSL config
  15729. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  15730. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  15731. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  15732. // Set minimum TLS version using mbedTLS native API
  15733. #if MBEDTLS_VERSION_MAJOR >= 3
  15734. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  15735. #else
  15736. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  15737. MBEDTLS_SSL_MINOR_VERSION_3);
  15738. #endif
  15739. return true;
  15740. };
  15741. SSLServer svr(setup_callback);
  15742. ASSERT_TRUE(svr.is_valid());
  15743. ASSERT_TRUE(callback_invoked);
  15744. svr.Get("/test", [&](const Request &req, Response &res) {
  15745. res.set_content("test", "text/plain");
  15746. auto cert = req.peer_cert();
  15747. ASSERT_TRUE(static_cast<bool>(cert));
  15748. auto common_name = cert.subject_cn();
  15749. EXPECT_EQ("Common Name", common_name);
  15750. });
  15751. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15752. auto se = detail::scope_exit([&] {
  15753. svr.stop();
  15754. t.join();
  15755. ASSERT_FALSE(svr.is_running());
  15756. });
  15757. svr.wait_until_ready();
  15758. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15759. cli.enable_server_certificate_verification(false);
  15760. cli.set_connection_timeout(30);
  15761. auto res = cli.Get("/test");
  15762. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15763. ASSERT_EQ(StatusCode::OK_200, res->status);
  15764. }
  15765. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  15766. // context (owning mbedtls_ssl_config) before shutting down a still-open
  15767. // keep-alive SSL session, which reads through that config in
  15768. // mbedtls_ssl_close_notify.
  15769. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  15770. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15771. ASSERT_TRUE(svr.is_valid());
  15772. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  15773. res.set_content("test", "text/plain");
  15774. });
  15775. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15776. auto se = detail::scope_exit([&] {
  15777. svr.stop();
  15778. t.join();
  15779. ASSERT_FALSE(svr.is_running());
  15780. });
  15781. svr.wait_until_ready();
  15782. {
  15783. SSLClient cli(HOST, PORT);
  15784. cli.enable_server_certificate_verification(false);
  15785. cli.set_keep_alive(true);
  15786. auto res = cli.Get("/test");
  15787. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15788. ASSERT_EQ(StatusCode::OK_200, res->status);
  15789. // cli is destructed here with the keep-alive SSL session still open.
  15790. }
  15791. }
  15792. #endif
  15793. // WebSocket Tests
  15794. TEST(WebSocketTest, RSVBitsMustBeZero) {
  15795. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  15796. // defining the meaning of these bits has been negotiated.
  15797. auto make_frame = [](uint8_t first_byte) {
  15798. std::string frame;
  15799. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  15800. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  15801. frame += "Hello";
  15802. return frame;
  15803. };
  15804. // RSV1 set (0x40)
  15805. {
  15806. detail::BufferStream strm;
  15807. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  15808. ws::Opcode opcode;
  15809. std::string payload;
  15810. bool fin;
  15811. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15812. false, 1024));
  15813. }
  15814. // RSV2 set (0x20)
  15815. {
  15816. detail::BufferStream strm;
  15817. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  15818. ws::Opcode opcode;
  15819. std::string payload;
  15820. bool fin;
  15821. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15822. false, 1024));
  15823. }
  15824. // RSV3 set (0x10)
  15825. {
  15826. detail::BufferStream strm;
  15827. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  15828. ws::Opcode opcode;
  15829. std::string payload;
  15830. bool fin;
  15831. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15832. false, 1024));
  15833. }
  15834. // No RSV bits set - should succeed
  15835. {
  15836. detail::BufferStream strm;
  15837. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  15838. ws::Opcode opcode;
  15839. std::string payload;
  15840. bool fin;
  15841. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15842. false, 1024));
  15843. EXPECT_EQ(ws::Opcode::Text, opcode);
  15844. EXPECT_EQ("Hello", payload);
  15845. EXPECT_TRUE(fin);
  15846. }
  15847. }
  15848. TEST(WebSocketTest, ControlFrameValidation) {
  15849. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  15850. // payload length <= 125.
  15851. // Ping with FIN=0 - must be rejected
  15852. {
  15853. detail::BufferStream strm;
  15854. std::string frame;
  15855. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  15856. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  15857. strm.write(frame.data(), frame.size());
  15858. ws::Opcode opcode;
  15859. std::string payload;
  15860. bool fin;
  15861. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15862. false, 1024));
  15863. }
  15864. // Close with FIN=0 - must be rejected
  15865. {
  15866. detail::BufferStream strm;
  15867. std::string frame;
  15868. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  15869. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  15870. strm.write(frame.data(), frame.size());
  15871. ws::Opcode opcode;
  15872. std::string payload;
  15873. bool fin;
  15874. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15875. false, 1024));
  15876. }
  15877. // Ping with payload_len=126 (extended length) - must be rejected
  15878. {
  15879. detail::BufferStream strm;
  15880. std::string frame;
  15881. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  15882. frame += static_cast<char>(126); // payload_len=126 (>125)
  15883. frame += static_cast<char>(0x00); // extended length high byte
  15884. frame += static_cast<char>(126); // extended length low byte
  15885. frame += std::string(126, 'x');
  15886. strm.write(frame.data(), frame.size());
  15887. ws::Opcode opcode;
  15888. std::string payload;
  15889. bool fin;
  15890. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15891. false, 1024));
  15892. }
  15893. // Ping with FIN=1 and payload_len=125 - should succeed
  15894. {
  15895. detail::BufferStream strm;
  15896. std::string frame;
  15897. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  15898. frame += static_cast<char>(125); // payload_len=125
  15899. frame += std::string(125, 'x');
  15900. strm.write(frame.data(), frame.size());
  15901. ws::Opcode opcode;
  15902. std::string payload;
  15903. bool fin;
  15904. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15905. false, 1024));
  15906. EXPECT_EQ(ws::Opcode::Ping, opcode);
  15907. EXPECT_EQ(125u, payload.size());
  15908. EXPECT_TRUE(fin);
  15909. }
  15910. }
  15911. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  15912. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  15913. // length MUST be 0.
  15914. // MSB set - must be rejected
  15915. {
  15916. detail::BufferStream strm;
  15917. std::string frame;
  15918. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  15919. frame += static_cast<char>(127); // 64-bit extended length
  15920. frame += static_cast<char>(0x80); // MSB set (invalid)
  15921. frame += std::string(7, '\0'); // remaining 7 bytes of length
  15922. strm.write(frame.data(), frame.size());
  15923. ws::Opcode opcode;
  15924. std::string payload;
  15925. bool fin;
  15926. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15927. false, 1024));
  15928. }
  15929. // MSB clear - should pass length parsing (will be rejected by max_len,
  15930. // but that's a different check; use a small length to verify)
  15931. {
  15932. detail::BufferStream strm;
  15933. std::string frame;
  15934. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  15935. frame += static_cast<char>(127); // 64-bit extended length
  15936. frame += std::string(7, '\0'); // high bytes = 0
  15937. frame += static_cast<char>(0x03); // length = 3
  15938. frame += "abc";
  15939. strm.write(frame.data(), frame.size());
  15940. ws::Opcode opcode;
  15941. std::string payload;
  15942. bool fin;
  15943. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15944. false, 1024));
  15945. EXPECT_EQ(ws::Opcode::Text, opcode);
  15946. EXPECT_EQ("abc", payload);
  15947. }
  15948. }
  15949. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  15950. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  15951. // Valid UTF-8
  15952. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  15953. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  15954. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  15955. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  15956. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  15957. // Invalid UTF-8
  15958. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  15959. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  15960. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  15961. EXPECT_FALSE(
  15962. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  15963. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  15964. }
  15965. TEST(WebSocketTest, ConnectAndDisconnect) {
  15966. Server svr;
  15967. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  15968. std::string msg;
  15969. while (ws.read(msg)) {}
  15970. });
  15971. auto port = svr.bind_to_any_port(HOST);
  15972. std::thread t([&]() { svr.listen_after_bind(); });
  15973. svr.wait_until_ready();
  15974. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  15975. ASSERT_TRUE(client.connect());
  15976. EXPECT_TRUE(client.is_open());
  15977. client.close();
  15978. EXPECT_FALSE(client.is_open());
  15979. svr.stop();
  15980. t.join();
  15981. }
  15982. TEST(WebSocketTest, ValidURL) {
  15983. ws::WebSocketClient ws1("ws://localhost:8080/path");
  15984. EXPECT_TRUE(ws1.is_valid());
  15985. ws::WebSocketClient ws2("ws://example.com/path");
  15986. EXPECT_TRUE(ws2.is_valid());
  15987. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  15988. EXPECT_TRUE(ws3.is_valid());
  15989. #ifdef CPPHTTPLIB_SSL_ENABLED
  15990. ws::WebSocketClient wss1("wss://example.com/path");
  15991. EXPECT_TRUE(wss1.is_valid());
  15992. ws::WebSocketClient wss2("wss://example.com:443/path");
  15993. EXPECT_TRUE(wss2.is_valid());
  15994. #endif
  15995. }
  15996. TEST(WebSocketTest, InvalidURL) {
  15997. // No scheme
  15998. ws::WebSocketClient ws1("localhost:8080/path");
  15999. EXPECT_FALSE(ws1.is_valid());
  16000. // No path
  16001. ws::WebSocketClient ws2("ws://localhost:8080");
  16002. EXPECT_FALSE(ws2.is_valid());
  16003. // Empty string
  16004. ws::WebSocketClient ws3("");
  16005. EXPECT_FALSE(ws3.is_valid());
  16006. // Missing host
  16007. ws::WebSocketClient ws4("ws://:8080/path");
  16008. EXPECT_FALSE(ws4.is_valid());
  16009. // Port number overflow — should not crash
  16010. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  16011. EXPECT_FALSE(ws5.is_valid());
  16012. // Port out of range
  16013. ws::WebSocketClient ws6("ws://localhost:99999/path");
  16014. EXPECT_FALSE(ws6.is_valid());
  16015. }
  16016. TEST(WebSocketTest, UnsupportedScheme) {
  16017. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16018. ws::WebSocketClient ws1("http://localhost:8080/path");
  16019. EXPECT_FALSE(ws1.is_valid());
  16020. ws::WebSocketClient ws2("https://localhost:8080/path");
  16021. EXPECT_FALSE(ws2.is_valid());
  16022. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  16023. EXPECT_FALSE(ws3.is_valid());
  16024. #else
  16025. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  16026. std::invalid_argument);
  16027. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  16028. std::invalid_argument);
  16029. #endif
  16030. }
  16031. TEST(WebSocketTest, ConnectWhenInvalid) {
  16032. ws::WebSocketClient ws("not a valid url");
  16033. EXPECT_FALSE(ws.is_valid());
  16034. EXPECT_FALSE(ws.connect());
  16035. }
  16036. TEST(WebSocketTest, DefaultPort) {
  16037. ws::WebSocketClient ws1("ws://example.com/path");
  16038. EXPECT_TRUE(ws1.is_valid());
  16039. // ws:// defaults to port 80 (verified by successful parse)
  16040. #ifdef CPPHTTPLIB_SSL_ENABLED
  16041. ws::WebSocketClient ws2("wss://example.com/path");
  16042. EXPECT_TRUE(ws2.is_valid());
  16043. // wss:// defaults to port 443 (verified by successful parse)
  16044. #endif
  16045. }
  16046. TEST(WebSocketTest, IPv6LiteralAddress) {
  16047. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  16048. EXPECT_TRUE(ws1.is_valid());
  16049. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  16050. EXPECT_TRUE(ws2.is_valid());
  16051. }
  16052. TEST(WebSocketTest, ComplexPath) {
  16053. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  16054. EXPECT_TRUE(ws1.is_valid());
  16055. ws::WebSocketClient ws2("ws://localhost:8080/");
  16056. EXPECT_TRUE(ws2.is_valid());
  16057. }
  16058. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  16059. Server svr;
  16060. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  16061. std::string msg;
  16062. while (ws.read(msg)) {}
  16063. });
  16064. auto port = svr.bind_to_any_port(HOST);
  16065. std::thread t([&]() { svr.listen_after_bind(); });
  16066. svr.wait_until_ready();
  16067. auto another_host = "example.com";
  16068. auto wrong_ip = "192.0.2.1";
  16069. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  16070. client.set_hostname_addr_map({{another_host, wrong_ip}});
  16071. ASSERT_TRUE(client.connect());
  16072. EXPECT_TRUE(client.is_open());
  16073. client.close();
  16074. svr.stop();
  16075. t.join();
  16076. }
  16077. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  16078. Server svr;
  16079. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  16080. std::string msg;
  16081. while (ws.read(msg)) {}
  16082. });
  16083. auto port = svr.bind_to_any_port(HOST);
  16084. std::thread t([&]() { svr.listen_after_bind(); });
  16085. svr.wait_until_ready();
  16086. auto wrong_ip = "192.0.2.1";
  16087. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  16088. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  16089. client.set_connection_timeout(1);
  16090. client.set_read_timeout(1);
  16091. client.set_write_timeout(1);
  16092. EXPECT_FALSE(client.connect());
  16093. EXPECT_FALSE(client.is_open());
  16094. svr.stop();
  16095. t.join();
  16096. }
  16097. class WebSocketIntegrationTest : public ::testing::Test {
  16098. protected:
  16099. void SetUp() override {
  16100. server_ = httplib::detail::make_unique<Server>();
  16101. setup_server();
  16102. start_server();
  16103. }
  16104. void TearDown() override {
  16105. server_->stop();
  16106. if (server_thread_.joinable()) { server_thread_.join(); }
  16107. }
  16108. void setup_server() {
  16109. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  16110. std::string msg;
  16111. ws::ReadResult ret;
  16112. while ((ret = ws.read(msg))) {
  16113. if (ret == ws::Binary) {
  16114. ws.send(msg.data(), msg.size());
  16115. } else {
  16116. ws.send(msg);
  16117. }
  16118. }
  16119. });
  16120. server_->WebSocket("/ws-echo-string",
  16121. [](const Request &, ws::WebSocket &ws) {
  16122. std::string msg;
  16123. while (ws.read(msg)) {
  16124. ws.send("echo: " + msg);
  16125. }
  16126. });
  16127. server_->WebSocket(
  16128. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  16129. // Echo back request metadata
  16130. ws.send("path:" + req.path);
  16131. ws.send("header:" + req.get_header_value("X-Test-Header"));
  16132. std::string msg;
  16133. while (ws.read(msg)) {}
  16134. });
  16135. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  16136. std::string msg;
  16137. ws.read(msg); // wait for a message
  16138. ws.close();
  16139. });
  16140. server_->WebSocket("/ws-close-status",
  16141. [](const Request &, ws::WebSocket &ws) {
  16142. std::string msg;
  16143. ws.read(msg); // wait for a message
  16144. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  16145. });
  16146. server_->WebSocket(
  16147. "/ws-subprotocol",
  16148. [](const Request &, ws::WebSocket &ws) {
  16149. std::string msg;
  16150. while (ws.read(msg)) {
  16151. ws.send(msg);
  16152. }
  16153. },
  16154. [](const std::vector<std::string> &protocols) -> std::string {
  16155. for (const auto &p : protocols) {
  16156. if (p == "graphql-ws") { return p; }
  16157. }
  16158. return "";
  16159. });
  16160. }
  16161. void start_server() {
  16162. port_ = server_->bind_to_any_port(HOST);
  16163. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  16164. server_->wait_until_ready();
  16165. }
  16166. std::unique_ptr<Server> server_;
  16167. std::thread server_thread_;
  16168. int port_ = 0;
  16169. };
  16170. TEST_F(WebSocketIntegrationTest, TextEcho) {
  16171. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16172. "/ws-echo");
  16173. ASSERT_TRUE(client.connect());
  16174. ASSERT_TRUE(client.is_open());
  16175. ASSERT_TRUE(client.send("Hello WebSocket"));
  16176. std::string msg;
  16177. EXPECT_EQ(ws::Text, client.read(msg));
  16178. EXPECT_EQ("Hello WebSocket", msg);
  16179. client.close();
  16180. }
  16181. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  16182. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16183. "/ws-echo");
  16184. ASSERT_TRUE(client.connect());
  16185. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  16186. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  16187. std::string msg;
  16188. EXPECT_EQ(ws::Binary, client.read(msg));
  16189. EXPECT_EQ(binary_data, msg);
  16190. client.close();
  16191. }
  16192. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  16193. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16194. "/ws-echo");
  16195. ASSERT_TRUE(client.connect());
  16196. for (int i = 0; i < 10; i++) {
  16197. auto text = "message " + std::to_string(i);
  16198. ASSERT_TRUE(client.send(text));
  16199. std::string msg;
  16200. ASSERT_TRUE(client.read(msg));
  16201. EXPECT_EQ(text, msg);
  16202. }
  16203. client.close();
  16204. }
  16205. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  16206. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16207. "/ws-close");
  16208. ASSERT_TRUE(client.connect());
  16209. // Send a message to trigger the server to close
  16210. ASSERT_TRUE(client.send("trigger close"));
  16211. // The server will close, so read should return false
  16212. std::string msg;
  16213. EXPECT_FALSE(client.read(msg));
  16214. EXPECT_FALSE(client.is_open());
  16215. }
  16216. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  16217. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16218. "/ws-echo");
  16219. ASSERT_TRUE(client.connect());
  16220. // 128KB message
  16221. std::string large_data(128 * 1024, 'X');
  16222. ASSERT_TRUE(client.send(large_data));
  16223. std::string msg;
  16224. ASSERT_TRUE(client.read(msg));
  16225. EXPECT_EQ(large_data, msg);
  16226. client.close();
  16227. }
  16228. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  16229. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16230. "/ws-echo");
  16231. ASSERT_TRUE(client.connect());
  16232. const int num_threads = 4;
  16233. std::vector<std::thread> threads;
  16234. std::atomic<int> send_count{0};
  16235. for (int t = 0; t < num_threads; t++) {
  16236. threads.emplace_back([&client, &send_count, t]() {
  16237. for (int i = 0; i < 5; i++) {
  16238. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  16239. if (client.send(text)) { send_count++; }
  16240. }
  16241. });
  16242. }
  16243. for (auto &th : threads) {
  16244. th.join();
  16245. }
  16246. int received = 0;
  16247. std::string msg;
  16248. while (received < send_count.load()) {
  16249. if (!client.read(msg)) { break; }
  16250. received++;
  16251. }
  16252. EXPECT_EQ(send_count.load(), received);
  16253. client.close();
  16254. }
  16255. TEST_F(WebSocketIntegrationTest, ReadString) {
  16256. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16257. "/ws-echo-string");
  16258. ASSERT_TRUE(client.connect());
  16259. ASSERT_TRUE(client.send("hello"));
  16260. std::string msg;
  16261. ASSERT_TRUE(client.read(msg));
  16262. EXPECT_EQ("echo: hello", msg);
  16263. ASSERT_TRUE(client.send("world"));
  16264. ASSERT_TRUE(client.read(msg));
  16265. EXPECT_EQ("echo: world", msg);
  16266. client.close();
  16267. }
  16268. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  16269. Headers headers = {{"X-Test-Header", "test-value"}};
  16270. ws::WebSocketClient client(
  16271. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  16272. ASSERT_TRUE(client.connect());
  16273. std::string msg;
  16274. ASSERT_TRUE(client.read(msg));
  16275. EXPECT_EQ("path:/ws-request-info", msg);
  16276. ASSERT_TRUE(client.read(msg));
  16277. EXPECT_EQ("header:test-value", msg);
  16278. client.close();
  16279. }
  16280. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  16281. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16282. "/ws-echo");
  16283. client.set_read_timeout(1, 0); // 1 second
  16284. ASSERT_TRUE(client.connect());
  16285. // Don't send anything — server echo handler waits for a message,
  16286. // so read() should time out and return false.
  16287. std::string msg;
  16288. EXPECT_FALSE(client.read(msg));
  16289. }
  16290. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  16291. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16292. "/ws-echo");
  16293. client.set_read_timeout(5, 0);
  16294. ASSERT_TRUE(client.connect());
  16295. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  16296. // The server should reject it and close the connection.
  16297. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  16298. client.send(oversized);
  16299. // The server's read() should have failed due to payload limit,
  16300. // so our read() should return false (connection closed).
  16301. std::string msg;
  16302. EXPECT_FALSE(client.read(msg));
  16303. }
  16304. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  16305. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16306. "/ws-echo");
  16307. client.set_read_timeout(10, 0);
  16308. ASSERT_TRUE(client.connect());
  16309. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  16310. // This should succeed.
  16311. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  16312. ASSERT_TRUE(client.send(at_limit));
  16313. std::string msg;
  16314. ASSERT_TRUE(client.read(msg));
  16315. EXPECT_EQ(at_limit.size(), msg.size());
  16316. client.close();
  16317. }
  16318. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  16319. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16320. "/nonexistent");
  16321. EXPECT_FALSE(client.connect());
  16322. EXPECT_FALSE(client.is_open());
  16323. }
  16324. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  16325. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16326. "/ws-echo");
  16327. ASSERT_TRUE(client.connect());
  16328. ASSERT_TRUE(client.send(""));
  16329. std::string msg;
  16330. EXPECT_EQ(ws::Text, client.read(msg));
  16331. EXPECT_EQ("", msg);
  16332. client.close();
  16333. }
  16334. TEST_F(WebSocketIntegrationTest, Reconnect) {
  16335. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16336. "/ws-echo");
  16337. // First connection
  16338. ASSERT_TRUE(client.connect());
  16339. ASSERT_TRUE(client.send("first"));
  16340. std::string msg;
  16341. ASSERT_TRUE(client.read(msg));
  16342. EXPECT_EQ("first", msg);
  16343. client.close();
  16344. EXPECT_FALSE(client.is_open());
  16345. // Reconnect using the same client object
  16346. ASSERT_TRUE(client.connect());
  16347. ASSERT_TRUE(client.is_open());
  16348. ASSERT_TRUE(client.send("second"));
  16349. ASSERT_TRUE(client.read(msg));
  16350. EXPECT_EQ("second", msg);
  16351. client.close();
  16352. }
  16353. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  16354. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16355. "/ws-close-status");
  16356. ASSERT_TRUE(client.connect());
  16357. // Trigger the server to close with GoingAway status
  16358. ASSERT_TRUE(client.send("trigger"));
  16359. // read() should return false after receiving the close frame
  16360. std::string msg;
  16361. EXPECT_FALSE(client.read(msg));
  16362. EXPECT_FALSE(client.is_open());
  16363. }
  16364. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  16365. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16366. "/ws-echo");
  16367. ASSERT_TRUE(client.connect());
  16368. client.close(ws::CloseStatus::GoingAway, "client leaving");
  16369. EXPECT_FALSE(client.is_open());
  16370. }
  16371. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  16372. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  16373. ws::WebSocketClient client(
  16374. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  16375. ASSERT_TRUE(client.connect());
  16376. // Server should have selected graphql-ws
  16377. EXPECT_EQ("graphql-ws", client.subprotocol());
  16378. client.close();
  16379. }
  16380. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  16381. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  16382. ws::WebSocketClient client(
  16383. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  16384. ASSERT_TRUE(client.connect());
  16385. // Server should not have selected any subprotocol
  16386. EXPECT_TRUE(client.subprotocol().empty());
  16387. client.close();
  16388. }
  16389. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  16390. // Connect without requesting any subprotocol
  16391. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16392. "/ws-subprotocol");
  16393. ASSERT_TRUE(client.connect());
  16394. EXPECT_TRUE(client.subprotocol().empty());
  16395. client.close();
  16396. }
  16397. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  16398. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16399. "/ws-echo");
  16400. client.set_tcp_nodelay(true);
  16401. client.set_connection_timeout(3, 0);
  16402. bool socket_options_called = false;
  16403. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  16404. ASSERT_TRUE(client.connect());
  16405. ASSERT_TRUE(client.is_open());
  16406. EXPECT_TRUE(socket_options_called);
  16407. ASSERT_TRUE(client.send("hello"));
  16408. std::string msg;
  16409. auto result = client.read(msg);
  16410. EXPECT_EQ(result, ws::ReadResult::Text);
  16411. EXPECT_EQ(msg, "hello");
  16412. client.close();
  16413. }
  16414. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  16415. Server svr;
  16416. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  16417. if (!req.has_header("Authorization")) {
  16418. res.status = StatusCode::Unauthorized_401;
  16419. res.set_content("Unauthorized", "text/plain");
  16420. return Server::HandlerResponse::Handled;
  16421. }
  16422. return Server::HandlerResponse::Unhandled;
  16423. });
  16424. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  16425. std::string msg;
  16426. while (ws.read(msg)) {
  16427. ws.send(msg);
  16428. }
  16429. });
  16430. auto port = svr.bind_to_any_port("localhost");
  16431. std::thread t([&]() { svr.listen_after_bind(); });
  16432. svr.wait_until_ready();
  16433. // Without Authorization header - should be rejected before upgrade
  16434. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  16435. EXPECT_FALSE(client1.connect());
  16436. // With Authorization header - should succeed
  16437. Headers headers = {{"Authorization", "Bearer token123"}};
  16438. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  16439. headers);
  16440. ASSERT_TRUE(client2.connect());
  16441. ASSERT_TRUE(client2.send("hello"));
  16442. std::string msg;
  16443. ASSERT_TRUE(client2.read(msg));
  16444. EXPECT_EQ("hello", msg);
  16445. client2.close();
  16446. svr.stop();
  16447. t.join();
  16448. }
  16449. TEST(WebSocketTest, QueryStringInHandshake) {
  16450. Server svr;
  16451. std::mutex mtx;
  16452. std::string received_target;
  16453. std::string received_token;
  16454. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  16455. {
  16456. std::lock_guard<std::mutex> lock(mtx);
  16457. received_target = req.target;
  16458. if (req.has_param("token")) {
  16459. received_token = req.get_param_value("token");
  16460. }
  16461. }
  16462. std::string msg;
  16463. while (ws.read(msg)) {
  16464. ws.send(msg);
  16465. }
  16466. });
  16467. auto port = svr.bind_to_any_port("localhost");
  16468. std::thread t([&]() { svr.listen_after_bind(); });
  16469. svr.wait_until_ready();
  16470. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  16471. "/ws?token=ABC&session=123");
  16472. ASSERT_TRUE(client.connect());
  16473. // Round-trip ensures the handler has run and captured the request.
  16474. ASSERT_TRUE(client.send("hello"));
  16475. std::string msg;
  16476. ASSERT_TRUE(client.read(msg));
  16477. EXPECT_EQ("hello", msg);
  16478. client.close();
  16479. {
  16480. std::lock_guard<std::mutex> lock(mtx);
  16481. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  16482. EXPECT_EQ("ABC", received_token);
  16483. }
  16484. svr.stop();
  16485. t.join();
  16486. }
  16487. TEST(WebSocketTest, HostHeaderInHandshake) {
  16488. Server svr;
  16489. std::mutex mtx;
  16490. std::string received_host;
  16491. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  16492. {
  16493. std::lock_guard<std::mutex> lock(mtx);
  16494. received_host = req.get_header_value("Host");
  16495. }
  16496. std::string msg;
  16497. while (ws.read(msg)) {
  16498. ws.send(msg);
  16499. }
  16500. });
  16501. auto port = svr.bind_to_any_port("localhost");
  16502. std::thread t([&]() { svr.listen_after_bind(); });
  16503. svr.wait_until_ready();
  16504. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  16505. ASSERT_TRUE(client.connect());
  16506. // Round-trip ensures the handler has run and captured the request.
  16507. ASSERT_TRUE(client.send("hello"));
  16508. std::string msg;
  16509. ASSERT_TRUE(client.read(msg));
  16510. client.close();
  16511. {
  16512. std::lock_guard<std::mutex> lock(mtx);
  16513. // Non-default port must be present in the Host header. Default ports
  16514. // (80/443) are omitted; that logic is covered by
  16515. // MakeHostAndPortStringTest.
  16516. EXPECT_EQ("localhost:" + std::to_string(port), received_host);
  16517. }
  16518. svr.stop();
  16519. t.join();
  16520. }
  16521. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  16522. class WebSocketSSLIntegrationTest : public ::testing::Test {
  16523. protected:
  16524. void SetUp() override {
  16525. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  16526. SERVER_PRIVATE_KEY_FILE);
  16527. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  16528. std::string msg;
  16529. ws::ReadResult ret;
  16530. while ((ret = ws.read(msg))) {
  16531. if (ret == ws::Binary) {
  16532. ws.send(msg.data(), msg.size());
  16533. } else {
  16534. ws.send(msg);
  16535. }
  16536. }
  16537. });
  16538. port_ = server_->bind_to_any_port(HOST);
  16539. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  16540. server_->wait_until_ready();
  16541. }
  16542. void TearDown() override {
  16543. server_->stop();
  16544. if (server_thread_.joinable()) { server_thread_.join(); }
  16545. }
  16546. std::unique_ptr<SSLServer> server_;
  16547. std::thread server_thread_;
  16548. int port_ = 0;
  16549. };
  16550. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  16551. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  16552. "/ws-echo");
  16553. client.enable_server_certificate_verification(false);
  16554. ASSERT_TRUE(client.connect());
  16555. ASSERT_TRUE(client.is_open());
  16556. ASSERT_TRUE(client.send("Hello WSS"));
  16557. std::string msg;
  16558. EXPECT_EQ(ws::Text, client.read(msg));
  16559. EXPECT_EQ("Hello WSS", msg);
  16560. client.close();
  16561. }
  16562. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  16563. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  16564. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  16565. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  16566. // client (without calling close() first) is the only path that runs
  16567. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  16568. // bug exactly.
  16569. //
  16570. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  16571. // when linked against an instrumented libssl; run under Valgrind to catch it
  16572. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  16573. // suite (the freed session otherwise stalls on the close handshake) — this test
  16574. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  16575. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  16576. {
  16577. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  16578. "/ws-echo");
  16579. client.enable_server_certificate_verification(false);
  16580. client.set_read_timeout(2, 0);
  16581. client.set_write_timeout(2, 0);
  16582. ASSERT_TRUE(client.connect());
  16583. ASSERT_TRUE(client.is_open());
  16584. ASSERT_TRUE(client.send("still open"));
  16585. // Intentionally do NOT call client.close(): leaving scope runs
  16586. // shutdown_and_close() with the WebSocket still open, which must send the
  16587. // close frame while the TLS session is still alive.
  16588. }
  16589. }
  16590. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  16591. // shutdown_and_close() at the start of connect(), reproducing the same
  16592. // use-after-free within the test body rather than at scope exit. The second
  16593. // connect must succeed and echo, proving the close handshake ran over a live
  16594. // session. See the note above about memory-tool requirements.
  16595. TEST_F(WebSocketSSLIntegrationTest,
  16596. ReconnectWhileOpenSendsCloseOverLiveSession) {
  16597. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  16598. "/ws-echo");
  16599. client.enable_server_certificate_verification(false);
  16600. client.set_read_timeout(2, 0);
  16601. client.set_write_timeout(2, 0);
  16602. ASSERT_TRUE(client.connect());
  16603. ASSERT_TRUE(client.is_open());
  16604. ASSERT_TRUE(client.send("still open"));
  16605. // Reconnect without closing first: connect() calls shutdown_and_close() on
  16606. // the still-open connection, which must not touch a freed TLS session.
  16607. ASSERT_TRUE(client.connect());
  16608. ASSERT_TRUE(client.is_open());
  16609. ASSERT_TRUE(client.send("after reconnect"));
  16610. std::string msg;
  16611. EXPECT_EQ(ws::Text, client.read(msg));
  16612. EXPECT_EQ("after reconnect", msg);
  16613. client.close();
  16614. }
  16615. #endif
  16616. #ifdef CPPHTTPLIB_SSL_ENABLED
  16617. class WebSocketSSLCATest : public ::testing::Test {
  16618. protected:
  16619. void SetUp() override {
  16620. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  16621. SERVER_PRIVATE_KEY_FILE);
  16622. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  16623. std::string msg;
  16624. while (ws.read(msg)) {
  16625. ws.send(msg);
  16626. }
  16627. });
  16628. port_ = server_->bind_to_any_port("127.0.0.1");
  16629. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  16630. server_->wait_until_ready();
  16631. }
  16632. void TearDown() override {
  16633. server_->stop();
  16634. if (server_thread_.joinable()) { server_thread_.join(); }
  16635. }
  16636. std::string url() const {
  16637. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  16638. }
  16639. std::unique_ptr<SSLServer> server_;
  16640. std::thread server_thread_;
  16641. int port_ = 0;
  16642. };
  16643. // A custom CA loaded as PEM verifies the server with full certificate
  16644. // verification enabled
  16645. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  16646. ws::WebSocketClient client(url());
  16647. std::string cert;
  16648. read_file(SERVER_CERT2_FILE, cert);
  16649. client.load_ca_cert_store(cert.c_str(), cert.size());
  16650. ASSERT_TRUE(client.connect());
  16651. ASSERT_TRUE(client.send("hello"));
  16652. std::string msg;
  16653. EXPECT_EQ(ws::Text, client.read(msg));
  16654. EXPECT_EQ("hello", msg);
  16655. client.close();
  16656. }
  16657. // A custom CA that does not cover the server must fail verification (the
  16658. // custom CA is exclusive; system certs are not loaded alongside it)
  16659. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  16660. ws::WebSocketClient client(url());
  16661. std::string cert;
  16662. read_file(CLIENT_CA_CERT_FILE, cert);
  16663. client.load_ca_cert_store(cert.c_str(), cert.size());
  16664. ASSERT_FALSE(client.connect());
  16665. }
  16666. // Regression test: reconnecting with a native custom CA store used to reuse
  16667. // a store handle the previous TLS context had already freed (use-after-free
  16668. // under the OpenSSL backend). The context now lives as long as the client.
  16669. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  16670. ws::WebSocketClient client(url());
  16671. std::string cert;
  16672. read_file(SERVER_CERT2_FILE, cert);
  16673. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  16674. ASSERT_TRUE(client.connect());
  16675. client.close();
  16676. ASSERT_TRUE(client.connect());
  16677. ASSERT_TRUE(client.send("again"));
  16678. std::string msg;
  16679. EXPECT_EQ(ws::Text, client.read(msg));
  16680. EXPECT_EQ("again", msg);
  16681. client.close();
  16682. }
  16683. // Regression test: a certificate with a trusted chain but no identity match
  16684. // for the server IP must be rejected. The Mbed TLS backend used to skip
  16685. // verification entirely for IP hosts, so this connection succeeded there.
  16686. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  16687. // chain verification while the identity check must still fail.
  16688. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  16689. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16690. ASSERT_TRUE(svr.is_valid());
  16691. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  16692. std::string msg;
  16693. while (ws.read(msg)) {
  16694. ws.send(msg);
  16695. }
  16696. });
  16697. auto port = svr.bind_to_any_port("127.0.0.1");
  16698. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16699. auto se = detail::scope_exit([&] {
  16700. svr.stop();
  16701. t.join();
  16702. });
  16703. svr.wait_until_ready();
  16704. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  16705. "/echo");
  16706. std::string cert;
  16707. read_file(SERVER_CERT_FILE, cert);
  16708. client.load_ca_cert_store(cert.c_str(), cert.size());
  16709. ASSERT_FALSE(client.connect());
  16710. }
  16711. #endif
  16712. #if !defined(_WIN32)
  16713. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  16714. auto secret_dir = std::string("./symlink_test_secret");
  16715. auto served_dir = std::string("./symlink_test_served");
  16716. auto secret_file = secret_dir + "/secret.txt";
  16717. auto symlink_path = served_dir + "/escape";
  16718. // Setup: create directories and files
  16719. mkdir(secret_dir.c_str(), 0755);
  16720. mkdir(served_dir.c_str(), 0755);
  16721. {
  16722. std::ofstream ofs(secret_file);
  16723. ofs << "SECRET_DATA";
  16724. }
  16725. // Create symlink using absolute path so it resolves correctly
  16726. #ifdef PATH_MAX
  16727. char abs_secret[PATH_MAX];
  16728. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  16729. #else
  16730. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  16731. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  16732. ASSERT_NE(nullptr, abs_secret);
  16733. #endif
  16734. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  16735. auto se = detail::scope_exit([&] {
  16736. unlink(symlink_path.c_str());
  16737. unlink(secret_file.c_str());
  16738. rmdir(served_dir.c_str());
  16739. rmdir(secret_dir.c_str());
  16740. });
  16741. Server svr;
  16742. svr.set_mount_point("/", served_dir);
  16743. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  16744. auto se2 = detail::scope_exit([&] {
  16745. svr.stop();
  16746. listen_thread.join();
  16747. });
  16748. svr.wait_until_ready();
  16749. Client cli("localhost", PORT);
  16750. // Symlink pointing outside base dir should be blocked
  16751. auto res = cli.Get("/escape/secret.txt");
  16752. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16753. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  16754. }
  16755. #endif
  16756. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  16757. // A GET request with Content-Length to a static file handler must have its
  16758. // body drained before the keep-alive connection is reused. Otherwise the
  16759. // unread body bytes are interpreted as the next HTTP request.
  16760. //
  16761. // The body is sent AFTER receiving the first response (as in the original
  16762. // PoC) so that the stream_line_reader cannot buffer it together with the
  16763. // headers of the first request.
  16764. Server svr;
  16765. svr.set_mount_point("/", "./www");
  16766. std::atomic<int> smuggled_count(0);
  16767. svr.Get("/smuggled", [&](const Request &, Response &res) {
  16768. smuggled_count++;
  16769. res.set_content("oops", "text/plain");
  16770. });
  16771. auto port = svr.bind_to_any_port("localhost");
  16772. thread t = thread([&] { svr.listen_after_bind(); });
  16773. auto se = detail::scope_exit([&] {
  16774. svr.stop();
  16775. t.join();
  16776. });
  16777. svr.wait_until_ready();
  16778. auto error = Error::Success;
  16779. auto sock = detail::create_client_socket(
  16780. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  16781. /*connection_timeout_sec=*/2, 0,
  16782. /*read_timeout_sec=*/2, 0,
  16783. /*write_timeout_sec=*/2, 0, std::string(), error);
  16784. ASSERT_NE(INVALID_SOCKET, sock);
  16785. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  16786. // The "smuggled" request will be sent as the body of the outer GET
  16787. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  16788. "Host: localhost\r\n"
  16789. "Connection: close\r\n"
  16790. "\r\n";
  16791. // Step 1: Send only the outer request headers (no body yet)
  16792. std::string outer_headers = "GET /file HTTP/1.1\r\n"
  16793. "Host: localhost\r\n"
  16794. "Content-Length: " +
  16795. std::to_string(smuggled.size()) +
  16796. "\r\n"
  16797. "\r\n";
  16798. auto sent = send(sock, outer_headers.data(), outer_headers.size(), 0);
  16799. ASSERT_EQ(static_cast<ssize_t>(outer_headers.size()), sent);
  16800. // Step 2: Read the first response (server serves file without reading body)
  16801. std::string first_response;
  16802. char buf[4096];
  16803. for (;;) {
  16804. auto n = recv(sock, buf, sizeof(buf), 0);
  16805. if (n <= 0) break;
  16806. first_response.append(buf, static_cast<size_t>(n));
  16807. // Stop once we have a complete response (headers + body)
  16808. auto hdr_end = first_response.find("\r\n\r\n");
  16809. if (hdr_end != std::string::npos) {
  16810. // Check for Content-Length to know when the body is complete
  16811. auto cl_pos = first_response.find("Content-Length:");
  16812. if (cl_pos != std::string::npos) {
  16813. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  16814. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  16815. auto cl = std::stoul(
  16816. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  16817. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  16818. } else {
  16819. break; // No Content-Length, assume headers-only response
  16820. }
  16821. }
  16822. }
  16823. ASSERT_TRUE(first_response.find("HTTP/1.1 200") != std::string::npos);
  16824. // Step 3: Now send the body, which looks like a new HTTP request.
  16825. // On a vulnerable server the keep-alive loop reads this as a second request.
  16826. sent = send(sock, smuggled.data(), smuggled.size(), 0);
  16827. ASSERT_EQ(static_cast<ssize_t>(smuggled.size()), sent);
  16828. // Step 4: Try to read a second response (should NOT exist after fix)
  16829. std::string second_response;
  16830. for (;;) {
  16831. auto n = recv(sock, buf, sizeof(buf), 0);
  16832. if (n <= 0) break;
  16833. second_response.append(buf, static_cast<size_t>(n));
  16834. }
  16835. // The smuggled request must NOT have been processed
  16836. EXPECT_EQ(0, smuggled_count.load());
  16837. }
  16838. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  16839. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  16840. // must be rejected with 400 Bad Request.
  16841. Server svr;
  16842. svr.Post("/test", [&](const Request &, Response &res) {
  16843. res.set_content("ok", "text/plain");
  16844. });
  16845. thread t = thread([&] { svr.listen(HOST, PORT); });
  16846. auto se = detail::scope_exit([&] {
  16847. svr.stop();
  16848. t.join();
  16849. ASSERT_FALSE(svr.is_running());
  16850. });
  16851. svr.wait_until_ready();
  16852. // Exact "chunked"
  16853. {
  16854. auto req = "POST /test HTTP/1.1\r\n"
  16855. "Host: localhost\r\n"
  16856. "Content-Length: 5\r\n"
  16857. "Transfer-Encoding: chunked\r\n"
  16858. "Connection: close\r\n"
  16859. "\r\n"
  16860. "hello";
  16861. std::string response;
  16862. ASSERT_TRUE(send_request(1, req, &response));
  16863. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  16864. response.substr(0, response.find("\r\n")));
  16865. }
  16866. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  16867. {
  16868. auto req = "POST /test HTTP/1.1\r\n"
  16869. "Host: localhost\r\n"
  16870. "Content-Length: 5\r\n"
  16871. "Transfer-Encoding: gzip, chunked\r\n"
  16872. "Connection: close\r\n"
  16873. "\r\n"
  16874. "hello";
  16875. std::string response;
  16876. ASSERT_TRUE(send_request(1, req, &response));
  16877. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  16878. response.substr(0, response.find("\r\n")));
  16879. }
  16880. }
  16881. // Regression for issue #2450: a DELETE without Content-Length on a
  16882. // keep-alive connection must not let the post-response drain consume the
  16883. // next request's bytes.
  16884. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  16885. Server svr;
  16886. std::atomic<int> delete_count(0);
  16887. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  16888. delete_count++;
  16889. res.status = StatusCode::NoContent_204;
  16890. });
  16891. auto port = svr.bind_to_any_port(HOST);
  16892. thread t = thread([&] { svr.listen_after_bind(); });
  16893. auto se = detail::scope_exit([&] {
  16894. svr.stop();
  16895. t.join();
  16896. });
  16897. svr.wait_until_ready();
  16898. auto error = Error::Success;
  16899. auto sock = detail::create_client_socket(
  16900. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  16901. /*connection_timeout_sec=*/2, 0,
  16902. /*read_timeout_sec=*/2, 0,
  16903. /*write_timeout_sec=*/2, 0, std::string(), error);
  16904. ASSERT_NE(INVALID_SOCKET, sock);
  16905. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  16906. auto send_request_and_read_response = [&](const std::string &req,
  16907. std::string &out) -> bool {
  16908. auto sent = send(sock, req.data(), req.size(), 0);
  16909. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  16910. char buf[4096];
  16911. for (;;) {
  16912. auto n = recv(sock, buf, sizeof(buf), 0);
  16913. if (n <= 0) { return !out.empty(); }
  16914. out.append(buf, static_cast<size_t>(n));
  16915. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  16916. }
  16917. };
  16918. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  16919. "Host: localhost\r\n"
  16920. "\r\n";
  16921. std::string resp1;
  16922. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  16923. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  16924. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  16925. "Host: localhost\r\n"
  16926. "Connection: close\r\n"
  16927. "\r\n";
  16928. std::string resp2;
  16929. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  16930. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  16931. EXPECT_EQ(2, delete_count.load());
  16932. }
  16933. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  16934. Server svr;
  16935. svr.Post("/ingest", [&](const Request &, Response &res,
  16936. const ContentReader &content_reader) {
  16937. auto consumed = content_reader([](const char *, size_t) { return false; });
  16938. EXPECT_FALSE(consumed);
  16939. res.status = StatusCode::Conflict_409;
  16940. res.set_header("Connection", "close");
  16941. });
  16942. auto port = svr.bind_to_any_port(HOST);
  16943. thread t = thread([&] { svr.listen_after_bind(); });
  16944. auto se = detail::scope_exit([&] {
  16945. svr.stop();
  16946. t.join();
  16947. });
  16948. svr.wait_until_ready();
  16949. auto error = Error::Success;
  16950. auto sock = detail::create_client_socket(
  16951. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  16952. /*connection_timeout_sec=*/2, 0,
  16953. /*read_timeout_sec=*/1, 0,
  16954. /*write_timeout_sec=*/2, 0, std::string(), error);
  16955. ASSERT_NE(INVALID_SOCKET, sock);
  16956. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  16957. std::string request = "POST /ingest HTTP/1.1\r\n"
  16958. "Host: localhost\r\n"
  16959. "Transfer-Encoding: chunked\r\n"
  16960. "\r\n"
  16961. "4\r\n"
  16962. "data\r\n";
  16963. auto sent = send(sock, request.data(), request.size(), 0);
  16964. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  16965. std::string response;
  16966. ssize_t received = 0;
  16967. do {
  16968. char buf[4096];
  16969. received = recv(sock, buf, sizeof(buf), 0);
  16970. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  16971. } while (received > 0);
  16972. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  16973. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  16974. EXPECT_EQ(0, received);
  16975. }
  16976. namespace no_proxy_test {
  16977. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  16978. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  16979. // calling listen().
  16980. class ScopedServer {
  16981. public:
  16982. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  16983. ~ScopedServer() {
  16984. svr_.stop();
  16985. if (th_.joinable()) { th_.join(); }
  16986. }
  16987. Server &svr() { return svr_; }
  16988. int port() const { return port_; }
  16989. void listen() {
  16990. th_ = std::thread([this] { svr_.listen_after_bind(); });
  16991. svr_.wait_until_ready();
  16992. }
  16993. private:
  16994. Server svr_;
  16995. std::thread th_;
  16996. int port_ = 0;
  16997. };
  16998. class ProxyAndTargetServers {
  16999. public:
  17000. ProxyAndTargetServers() {
  17001. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  17002. proxy_hits_++;
  17003. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  17004. res.set_content("via-proxy", "text/plain");
  17005. });
  17006. target_.Get(".*", [this](const Request &req, Response &res) {
  17007. target_hits_++;
  17008. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  17009. res.set_content("direct", "text/plain");
  17010. });
  17011. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  17012. target_port_ = target_.bind_to_any_port("127.0.0.1");
  17013. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  17014. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  17015. proxy_mock_.wait_until_ready();
  17016. target_.wait_until_ready();
  17017. }
  17018. ~ProxyAndTargetServers() {
  17019. proxy_mock_.stop();
  17020. target_.stop();
  17021. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  17022. if (target_thread_.joinable()) { target_thread_.join(); }
  17023. }
  17024. Server &proxy_mock() { return proxy_mock_; }
  17025. Server &target() { return target_; }
  17026. int proxy_port() const { return proxy_port_; }
  17027. int target_port() const { return target_port_; }
  17028. int proxy_hits() const { return proxy_hits_.load(); }
  17029. int target_hits() const { return target_hits_.load(); }
  17030. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  17031. void reset_counters() {
  17032. proxy_hits_ = 0;
  17033. target_hits_ = 0;
  17034. last_had_proxy_authz_ = false;
  17035. }
  17036. private:
  17037. Server proxy_mock_;
  17038. Server target_;
  17039. std::thread proxy_thread_;
  17040. std::thread target_thread_;
  17041. int proxy_port_ = 0;
  17042. int target_port_ = 0;
  17043. std::atomic<int> proxy_hits_{0};
  17044. std::atomic<int> target_hits_{0};
  17045. std::atomic<bool> last_had_proxy_authz_{false};
  17046. };
  17047. inline std::unique_ptr<Client> make_client(const std::string &host,
  17048. ProxyAndTargetServers &s) {
  17049. auto cli = detail::make_unique<Client>(host, s.target_port());
  17050. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  17051. cli->set_proxy("127.0.0.1", s.proxy_port());
  17052. return cli;
  17053. }
  17054. } // namespace no_proxy_test
  17055. using no_proxy_test::make_client;
  17056. using no_proxy_test::ProxyAndTargetServers;
  17057. TEST(NoProxyTest, ExactHostnameBypasses) {
  17058. ProxyAndTargetServers s;
  17059. auto cli = make_client("example.com", s);
  17060. cli->set_no_proxy({"example.com"});
  17061. auto res = cli->Get("/");
  17062. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17063. EXPECT_EQ(0, s.proxy_hits());
  17064. EXPECT_EQ(1, s.target_hits());
  17065. }
  17066. TEST(NoProxyTest, SubdomainBypasses) {
  17067. ProxyAndTargetServers s;
  17068. auto cli = make_client("foo.example.com", s);
  17069. cli->set_no_proxy({"example.com"});
  17070. auto res = cli->Get("/");
  17071. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17072. EXPECT_EQ(0, s.proxy_hits());
  17073. EXPECT_EQ(1, s.target_hits());
  17074. }
  17075. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  17076. // Regression guard: "evilexample.com" must not be considered a subdomain
  17077. // of "example.com". Without the dot-boundary rule, a naive endsWith
  17078. // check would let traffic bypass the proxy and leak credentials direct
  17079. // to the attacker host.
  17080. ProxyAndTargetServers s;
  17081. auto cli = make_client("evilexample.com", s);
  17082. cli->set_no_proxy({"example.com"});
  17083. auto res = cli->Get("/");
  17084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17085. EXPECT_GE(s.proxy_hits(), 1);
  17086. EXPECT_EQ(0, s.target_hits());
  17087. }
  17088. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  17089. ProxyAndTargetServers s;
  17090. auto cli = make_client("example.com.evil.com", s);
  17091. cli->set_no_proxy({"example.com"});
  17092. auto res = cli->Get("/");
  17093. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17094. EXPECT_GE(s.proxy_hits(), 1);
  17095. EXPECT_EQ(0, s.target_hits());
  17096. }
  17097. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  17098. ProxyAndTargetServers s;
  17099. auto cli = make_client("example.com", s);
  17100. cli->set_no_proxy({".example.com"});
  17101. auto res = cli->Get("/");
  17102. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17103. EXPECT_EQ(0, s.proxy_hits());
  17104. EXPECT_EQ(1, s.target_hits());
  17105. }
  17106. TEST(NoProxyTest, CaseInsensitiveHostname) {
  17107. ProxyAndTargetServers s;
  17108. auto cli = make_client("Example.COM", s);
  17109. cli->set_no_proxy({"EXAMPLE.com"});
  17110. auto res = cli->Get("/");
  17111. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17112. EXPECT_EQ(0, s.proxy_hits());
  17113. EXPECT_EQ(1, s.target_hits());
  17114. }
  17115. TEST(NoProxyTest, TrailingDotIsNormalized) {
  17116. ProxyAndTargetServers s;
  17117. auto cli = make_client("example.com.", s);
  17118. cli->set_no_proxy({"example.com"});
  17119. auto res = cli->Get("/");
  17120. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17121. EXPECT_EQ(0, s.proxy_hits());
  17122. EXPECT_EQ(1, s.target_hits());
  17123. }
  17124. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  17125. // Trailing dots must be normalized on BOTH sides — host and entry.
  17126. // An implementation that only strips the host-side trailing dot would
  17127. // fail to match host "example.com" against entry "example.com." because
  17128. // a literal substring search would compare 11 chars against 12.
  17129. ProxyAndTargetServers s;
  17130. auto cli = make_client("example.com", s);
  17131. cli->set_no_proxy({"example.com."});
  17132. auto res = cli->Get("/");
  17133. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17134. EXPECT_EQ(0, s.proxy_hits());
  17135. EXPECT_EQ(1, s.target_hits());
  17136. }
  17137. TEST(NoProxyTest, WildcardBypassesEverything) {
  17138. ProxyAndTargetServers s;
  17139. auto cli = make_client("anything.invalid.test", s);
  17140. cli->set_no_proxy({"*"});
  17141. auto res = cli->Get("/");
  17142. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17143. EXPECT_EQ(0, s.proxy_hits());
  17144. EXPECT_EQ(1, s.target_hits());
  17145. }
  17146. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  17147. ProxyAndTargetServers s;
  17148. Client cli("127.0.0.1", s.target_port());
  17149. cli.set_proxy("127.0.0.1", s.proxy_port());
  17150. cli.set_no_proxy({"127.0.0.1"});
  17151. auto res = cli.Get("/");
  17152. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17153. EXPECT_EQ(0, s.proxy_hits());
  17154. EXPECT_EQ(1, s.target_hits());
  17155. }
  17156. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  17157. ProxyAndTargetServers s;
  17158. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  17159. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  17160. cli.set_proxy("127.0.0.1", s.proxy_port());
  17161. cli.set_no_proxy({"::1"});
  17162. auto res = cli.Get("/");
  17163. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17164. EXPECT_EQ(0, s.proxy_hits());
  17165. EXPECT_EQ(1, s.target_hits());
  17166. }
  17167. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  17168. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  17169. // must still be recognized as IPv6 for CIDR matching. Implementations
  17170. // that detect IPv6 only when the host begins with '[' would parse the
  17171. // host as a hostname and miss the match.
  17172. ProxyAndTargetServers s;
  17173. Client cli("fe80::1", s.target_port());
  17174. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  17175. cli.set_proxy("127.0.0.1", s.proxy_port());
  17176. cli.set_no_proxy({"fe80::/10"});
  17177. auto res = cli.Get("/");
  17178. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17179. EXPECT_EQ(0, s.proxy_hits());
  17180. EXPECT_EQ(1, s.target_hits());
  17181. }
  17182. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  17183. ProxyAndTargetServers s;
  17184. Client cli("::1", s.target_port());
  17185. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  17186. cli.set_proxy("127.0.0.1", s.proxy_port());
  17187. cli.set_no_proxy({"[::1]"});
  17188. auto res = cli.Get("/");
  17189. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17190. EXPECT_EQ(0, s.proxy_hits());
  17191. EXPECT_EQ(1, s.target_hits());
  17192. }
  17193. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  17194. ProxyAndTargetServers s;
  17195. Client cli("fe80::1", s.target_port());
  17196. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  17197. cli.set_proxy("127.0.0.1", s.proxy_port());
  17198. cli.set_no_proxy({"[fe80::]/10"});
  17199. auto res = cli.Get("/");
  17200. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17201. EXPECT_EQ(0, s.proxy_hits());
  17202. EXPECT_EQ(1, s.target_hits());
  17203. }
  17204. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  17205. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  17206. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  17207. // tricks via address-family conversion.
  17208. ProxyAndTargetServers s;
  17209. Client cli("::ffff:127.0.0.1", s.target_port());
  17210. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  17211. cli.set_proxy("127.0.0.1", s.proxy_port());
  17212. cli.set_no_proxy({"127.0.0.1"});
  17213. auto res = cli.Get("/");
  17214. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17215. EXPECT_GE(s.proxy_hits(), 1);
  17216. EXPECT_EQ(0, s.target_hits());
  17217. }
  17218. TEST(NoProxyTest, IPv4CidrMatch) {
  17219. ProxyAndTargetServers s;
  17220. Client cli("127.0.0.1", s.target_port());
  17221. cli.set_proxy("127.0.0.1", s.proxy_port());
  17222. cli.set_no_proxy({"127.0.0.0/8"});
  17223. auto res = cli.Get("/");
  17224. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17225. EXPECT_EQ(0, s.proxy_hits());
  17226. EXPECT_EQ(1, s.target_hits());
  17227. }
  17228. TEST(NoProxyTest, IPv4CidrNonMatch) {
  17229. ProxyAndTargetServers s;
  17230. Client cli("127.0.0.1", s.target_port());
  17231. cli.set_proxy("127.0.0.1", s.proxy_port());
  17232. cli.set_no_proxy({"10.0.0.0/8"});
  17233. auto res = cli.Get("/");
  17234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17235. EXPECT_GE(s.proxy_hits(), 1);
  17236. EXPECT_EQ(0, s.target_hits());
  17237. }
  17238. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  17239. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  17240. // IPv4 target matches.
  17241. ProxyAndTargetServers s;
  17242. Client cli("127.0.0.1", s.target_port());
  17243. cli.set_proxy("127.0.0.1", s.proxy_port());
  17244. cli.set_no_proxy({"0.0.0.0/0"});
  17245. auto res = cli.Get("/");
  17246. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17247. EXPECT_EQ(0, s.proxy_hits());
  17248. EXPECT_EQ(1, s.target_hits());
  17249. }
  17250. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  17251. ProxyAndTargetServers s;
  17252. Client cli("127.0.0.1", s.target_port());
  17253. cli.set_proxy("127.0.0.1", s.proxy_port());
  17254. cli.set_no_proxy({"127.0.0.1"});
  17255. auto res = cli.Get("/");
  17256. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17257. EXPECT_EQ(0, s.proxy_hits());
  17258. EXPECT_EQ(1, s.target_hits());
  17259. }
  17260. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  17261. ProxyAndTargetServers s;
  17262. Client cli("127.0.0.1", s.target_port());
  17263. cli.set_proxy("127.0.0.1", s.proxy_port());
  17264. cli.set_no_proxy({"127.0.0.0/33"});
  17265. auto res = cli.Get("/");
  17266. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17267. EXPECT_GE(s.proxy_hits(), 1);
  17268. EXPECT_EQ(0, s.target_hits());
  17269. }
  17270. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  17271. // Empty prefix after the slash must be rejected, not silently treated as /32.
  17272. ProxyAndTargetServers s;
  17273. Client cli("127.0.0.1", s.target_port());
  17274. cli.set_proxy("127.0.0.1", s.proxy_port());
  17275. cli.set_no_proxy({"127.0.0.1/"});
  17276. auto res = cli.Get("/");
  17277. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17278. EXPECT_GE(s.proxy_hits(), 1);
  17279. EXPECT_EQ(0, s.target_hits());
  17280. }
  17281. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  17282. ProxyAndTargetServers s;
  17283. auto cli = make_client("internal.corp", s);
  17284. cli->set_proxy_basic_auth("u", "p");
  17285. cli->set_no_proxy({"internal.corp"});
  17286. auto res = cli->Get("/");
  17287. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17288. EXPECT_EQ(1, s.target_hits());
  17289. EXPECT_EQ(0, s.proxy_hits());
  17290. EXPECT_FALSE(s.last_had_proxy_authz())
  17291. << "Proxy-Authorization must not be sent direct to the target";
  17292. }
  17293. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  17294. ProxyAndTargetServers s;
  17295. auto cli = make_client("public.example", s);
  17296. cli->set_proxy_basic_auth("u", "p");
  17297. cli->set_no_proxy({"internal.corp"}); // does not match
  17298. auto res = cli->Get("/");
  17299. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17300. EXPECT_GE(s.proxy_hits(), 1);
  17301. EXPECT_TRUE(s.last_had_proxy_authz());
  17302. }
  17303. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  17304. ProxyAndTargetServers s;
  17305. auto cli = make_client("anything.test", s);
  17306. auto res = cli->Get("/");
  17307. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17308. EXPECT_GE(s.proxy_hits(), 1);
  17309. EXPECT_EQ(0, s.target_hits());
  17310. }
  17311. TEST(NoProxyTest, PortSpecificEntryRejected) {
  17312. ProxyAndTargetServers s;
  17313. auto cli = make_client("example.com", s);
  17314. cli->set_no_proxy({"example.com:8080"});
  17315. auto res = cli->Get("/");
  17316. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17317. EXPECT_GE(s.proxy_hits(), 1);
  17318. EXPECT_EQ(0, s.target_hits());
  17319. }
  17320. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  17321. ProxyAndTargetServers s;
  17322. auto cli = make_client("anything.test", s);
  17323. cli->set_no_proxy({"", " ", "\t"});
  17324. auto res = cli->Get("/");
  17325. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17326. EXPECT_GE(s.proxy_hits(), 1);
  17327. EXPECT_EQ(0, s.target_hits());
  17328. }
  17329. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  17330. // An entry with leading/trailing whitespace must still match — env-style
  17331. // values are commonly pasted with stray spaces and an implementation
  17332. // that feeds the raw token directly to inet_pton would fail to match
  17333. // valid CIDRs because of the spaces.
  17334. ProxyAndTargetServers s;
  17335. Client cli("127.0.0.1", s.target_port());
  17336. cli.set_proxy("127.0.0.1", s.proxy_port());
  17337. cli.set_no_proxy({" 127.0.0.0/8 "});
  17338. auto res = cli.Get("/");
  17339. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17340. EXPECT_EQ(0, s.proxy_hits());
  17341. EXPECT_EQ(1, s.target_hits());
  17342. }
  17343. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  17344. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  17345. // go direct and must NOT carry Proxy-Authorization.
  17346. std::atomic<int> proxy_hits{0};
  17347. std::atomic<int> target_hits{0};
  17348. std::atomic<bool> target_saw_authz{false};
  17349. no_proxy_test::ScopedServer proxy_mock, target;
  17350. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  17351. proxy_hits++;
  17352. res.status = 302;
  17353. res.set_header("Location", "http://127.0.0.1:" +
  17354. std::to_string(target.port()) + "/landed");
  17355. });
  17356. target.svr().Get(".*", [&](const Request &req, Response &res) {
  17357. target_hits++;
  17358. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  17359. res.set_content("direct", "text/plain");
  17360. });
  17361. proxy_mock.listen();
  17362. target.listen();
  17363. Client cli("public.example", target.port());
  17364. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  17365. cli.set_proxy("127.0.0.1", proxy_mock.port());
  17366. cli.set_proxy_basic_auth("u", "p");
  17367. cli.set_no_proxy({"127.0.0.1"});
  17368. cli.set_follow_location(true);
  17369. auto res = cli.Get("/redir");
  17370. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17371. EXPECT_GE(proxy_hits.load(), 1);
  17372. EXPECT_GE(target_hits.load(), 1);
  17373. EXPECT_FALSE(target_saw_authz.load());
  17374. }
  17375. #ifdef CPPHTTPLIB_SSL_ENABLED
  17376. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  17377. // Direct origin replying 407 must not trigger the digest retry; otherwise
  17378. // proxy creds would be sent to the (possibly hostile) origin.
  17379. std::atomic<int> target_hits{0};
  17380. std::atomic<bool> target_saw_proxy_authz{false};
  17381. no_proxy_test::ScopedServer target;
  17382. target.svr().Get(".*", [&](const Request &req, Response &res) {
  17383. target_hits++;
  17384. if (req.has_header("Proxy-Authorization")) {
  17385. target_saw_proxy_authz = true;
  17386. }
  17387. res.status = StatusCode::ProxyAuthenticationRequired_407;
  17388. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  17389. "nonce=\"abc\", algorithm=MD5");
  17390. });
  17391. target.listen();
  17392. // The proxy address is set to the target's port: the bypass MUST kick in;
  17393. // if it doesn't, the test still routes "via proxy" to the same server and
  17394. // the Proxy-Authorization assertion below catches the leak.
  17395. Client cli("evil.example", target.port());
  17396. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  17397. cli.set_proxy("127.0.0.1", target.port());
  17398. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  17399. cli.set_no_proxy({"evil.example"});
  17400. auto res = cli.Get("/x");
  17401. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17402. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  17403. EXPECT_EQ(1, target_hits.load());
  17404. EXPECT_FALSE(target_saw_proxy_authz.load());
  17405. }
  17406. #endif
  17407. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  17408. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  17409. std::atomic<int> proxy_hits{0};
  17410. std::atomic<int> bypass_hits{0};
  17411. std::atomic<bool> proxy_saw_c_url{false};
  17412. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  17413. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  17414. proxy_hits++;
  17415. if (req.path.find("/start") != std::string::npos) {
  17416. res.status = 302;
  17417. res.set_header("Location", "http://127.0.0.1:" +
  17418. std::to_string(bypass_server.port()) +
  17419. "/middle");
  17420. return;
  17421. }
  17422. if (req.path.find("/end") != std::string::npos) {
  17423. proxy_saw_c_url = true;
  17424. res.set_content("c-via-proxy", "text/plain");
  17425. return;
  17426. }
  17427. res.set_content("unexpected", "text/plain");
  17428. });
  17429. // public.example's "advertised" port is arbitrary (the request never lands
  17430. // there — it goes through the proxy), but use a dynamic value to stay
  17431. // friendly with sharded parallel runs.
  17432. int public_port = bypass_server.port();
  17433. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  17434. bypass_hits++;
  17435. res.status = 302;
  17436. res.set_header("Location", "http://public.example:" +
  17437. std::to_string(public_port) + "/end");
  17438. });
  17439. proxy_mock.listen();
  17440. bypass_server.listen();
  17441. Client cli("public.example", public_port);
  17442. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  17443. cli.set_proxy("127.0.0.1", proxy_mock.port());
  17444. cli.set_no_proxy({"127.0.0.1"});
  17445. cli.set_follow_location(true);
  17446. auto res = cli.Get("/start");
  17447. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17448. EXPECT_EQ(StatusCode::OK_200, res->status);
  17449. EXPECT_EQ("c-via-proxy", res->body);
  17450. EXPECT_GE(proxy_hits.load(), 2);
  17451. EXPECT_GE(bypass_hits.load(), 1);
  17452. EXPECT_TRUE(proxy_saw_c_url.load());
  17453. }
  17454. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  17455. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  17456. // request reconnects to the correct endpoint.
  17457. std::atomic<int> proxy_hits{0};
  17458. std::atomic<int> target_hits{0};
  17459. no_proxy_test::ScopedServer proxy_mock, target;
  17460. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  17461. proxy_hits++;
  17462. res.set_content("via-proxy", "text/plain");
  17463. });
  17464. target.svr().Get(".*", [&](const Request &, Response &res) {
  17465. target_hits++;
  17466. res.set_content("direct", "text/plain");
  17467. });
  17468. proxy_mock.listen();
  17469. target.listen();
  17470. Client cli("public.example", target.port());
  17471. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  17472. cli.set_proxy("127.0.0.1", proxy_mock.port());
  17473. cli.set_keep_alive(true);
  17474. auto res1 = cli.Get("/a");
  17475. ASSERT_TRUE(res1);
  17476. EXPECT_EQ("via-proxy", res1->body);
  17477. EXPECT_EQ(1, proxy_hits.load());
  17478. EXPECT_EQ(0, target_hits.load());
  17479. cli.set_no_proxy({"public.example"});
  17480. auto res2 = cli.Get("/b");
  17481. ASSERT_TRUE(res2);
  17482. EXPECT_EQ("direct", res2->body);
  17483. EXPECT_EQ(1, proxy_hits.load());
  17484. EXPECT_EQ(1, target_hits.load());
  17485. }
  17486. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  17487. namespace proxy_tunnel_test {
  17488. // SSLServer counterpart to no_proxy_test::ScopedServer.
  17489. class ScopedSSLServer {
  17490. public:
  17491. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  17492. port_ = svr_.bind_to_any_port("127.0.0.1");
  17493. }
  17494. ~ScopedSSLServer() {
  17495. svr_.stop();
  17496. if (th_.joinable()) { th_.join(); }
  17497. }
  17498. SSLServer &svr() { return svr_; }
  17499. int port() const { return port_; }
  17500. void listen() {
  17501. th_ = std::thread([this] { svr_.listen_after_bind(); });
  17502. svr_.wait_until_ready();
  17503. }
  17504. private:
  17505. SSLServer svr_;
  17506. std::thread th_;
  17507. int port_ = 0;
  17508. };
  17509. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  17510. class ScopedConnectProxy {
  17511. public:
  17512. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  17513. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  17514. if (listen_fd_ < 0) { return; }
  17515. int yes = 1;
  17516. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  17517. sockaddr_in a{};
  17518. a.sin_family = AF_INET;
  17519. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  17520. a.sin_port = 0;
  17521. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  17522. return;
  17523. }
  17524. socklen_t alen = sizeof(a);
  17525. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  17526. 0) {
  17527. return;
  17528. }
  17529. port_ = ntohs(a.sin_port);
  17530. if (::listen(listen_fd_, 1) != 0) { return; }
  17531. th_ = std::thread([this] { run(); });
  17532. }
  17533. ~ScopedConnectProxy() {
  17534. stop_ = true;
  17535. if (listen_fd_ >= 0) {
  17536. ::shutdown(listen_fd_, SHUT_RDWR);
  17537. ::close(listen_fd_);
  17538. }
  17539. if (th_.joinable()) { th_.join(); }
  17540. }
  17541. int port() const { return port_; }
  17542. int connect_hits() const { return connect_hits_.load(); }
  17543. private:
  17544. void run() {
  17545. while (!stop_.load()) {
  17546. fd_set rfds;
  17547. FD_ZERO(&rfds);
  17548. FD_SET(listen_fd_, &rfds);
  17549. timeval tv{0, 100 * 1000};
  17550. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  17551. if (sel <= 0) { continue; }
  17552. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  17553. if (client_fd < 0) { continue; }
  17554. std::string req;
  17555. char buf[2048];
  17556. while (req.find("\r\n\r\n") == std::string::npos) {
  17557. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  17558. if (n <= 0) { break; }
  17559. req.append(buf, static_cast<size_t>(n));
  17560. }
  17561. if (req.compare(0, 7, "CONNECT") != 0) {
  17562. ::close(client_fd);
  17563. continue;
  17564. }
  17565. connect_hits_++;
  17566. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  17567. ::send(client_fd, ok, std::strlen(ok), 0);
  17568. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  17569. sockaddr_in o{};
  17570. o.sin_family = AF_INET;
  17571. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  17572. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  17573. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  17574. 0) {
  17575. ::close(client_fd);
  17576. ::close(origin_fd);
  17577. continue;
  17578. }
  17579. auto forward = [](int from, int to) {
  17580. char b[8192];
  17581. for (;;) {
  17582. ssize_t n = ::recv(from, b, sizeof(b), 0);
  17583. if (n <= 0) { break; }
  17584. ssize_t off = 0;
  17585. while (off < n) {
  17586. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  17587. if (s <= 0) {
  17588. off = n;
  17589. break;
  17590. }
  17591. off += s;
  17592. }
  17593. }
  17594. ::shutdown(to, SHUT_WR);
  17595. };
  17596. std::thread t1([&] { forward(client_fd, origin_fd); });
  17597. std::thread t2([&] { forward(origin_fd, client_fd); });
  17598. t1.join();
  17599. t2.join();
  17600. ::close(client_fd);
  17601. ::close(origin_fd);
  17602. }
  17603. }
  17604. int forward_port_ = -1;
  17605. int listen_fd_ = -1;
  17606. int port_ = 0;
  17607. std::thread th_;
  17608. std::atomic<bool> stop_{false};
  17609. std::atomic<int> connect_hits_{0};
  17610. };
  17611. } // namespace proxy_tunnel_test
  17612. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  17613. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  17614. // retry; otherwise proxy creds would be sent to the origin.
  17615. std::atomic<int> origin_hits{0};
  17616. std::atomic<bool> origin_saw_proxy_authz{false};
  17617. proxy_tunnel_test::ScopedSSLServer origin;
  17618. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  17619. origin_hits++;
  17620. if (req.has_header("Proxy-Authorization")) {
  17621. origin_saw_proxy_authz = true;
  17622. }
  17623. res.status = StatusCode::ProxyAuthenticationRequired_407;
  17624. res.set_header("Proxy-Authenticate",
  17625. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  17626. "algorithm=MD5");
  17627. });
  17628. origin.listen();
  17629. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  17630. ASSERT_NE(0, proxy.port());
  17631. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  17632. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  17633. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  17634. // and answer with its own status, making this test flaky.
  17635. SSLClient cli("127.0.0.1", origin.port());
  17636. cli.enable_server_certificate_verification(false);
  17637. cli.set_proxy("127.0.0.1", proxy.port());
  17638. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  17639. auto res = cli.Get("/x");
  17640. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17641. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  17642. EXPECT_EQ(1, origin_hits.load());
  17643. EXPECT_FALSE(origin_saw_proxy_authz.load());
  17644. EXPECT_EQ(1, proxy.connect_hits());
  17645. }
  17646. #endif