test.cc 743 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <cctype>
  17. #include <chrono>
  18. #include <clocale>
  19. #include <cstdio>
  20. #include <fstream>
  21. #include <future>
  22. #include <limits>
  23. #include <memory>
  24. #include <sstream>
  25. #include <stdexcept>
  26. #include <thread>
  27. #include <type_traits>
  28. #include <vector>
  29. #if __cplusplus >= 202002L
  30. inline std::string u8_to_string(const char8_t *s) {
  31. return std::string(reinterpret_cast<const char *>(s));
  32. }
  33. #define U8(x) u8_to_string(u8##x)
  34. #else
  35. #define U8(x) u8##x
  36. #endif
  37. #define SERVER_CERT_FILE "./cert.pem"
  38. #define SERVER_CERT2_FILE "./cert2.pem"
  39. #define SERVER_CERT_IP_CN_FILE "./cert_ip_cn.pem"
  40. #define SERVER_CERT_IPV6_FILE "./cert_ipv6.pem"
  41. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  42. #define CA_CERT_FILE "./ca-bundle.crt"
  43. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  44. #define CLIENT_CA_CERT_DIR "."
  45. #define CLIENT_CERT_FILE "./client.cert.pem"
  46. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  47. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  48. // Mbed TLS < 3.6 (e.g. Ubuntu's 2.28) has no PBES2-AES and needs the PBES1-3DES
  49. // key; 3.6+/4.x (4.x dropped DES) and OpenSSL/wolfSSL use the PBES2 AES key.
  50. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) && (MBEDTLS_VERSION_NUMBER < 0x03060000)
  51. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted_pbes1.key.pem"
  52. #else
  53. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  54. #endif
  55. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  56. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  57. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  58. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  59. #ifdef CPPHTTPLIB_SSL_ENABLED
  60. namespace httplib {
  61. namespace tls {
  62. // Declared here for the split build, where the TLS abstraction declarations
  63. // live below the split border; the definition is linked from httplib.cc.
  64. ca_store_t create_ca_store(const char *pem, size_t len);
  65. } // namespace tls
  66. } // namespace httplib
  67. #endif
  68. using namespace std;
  69. using namespace httplib;
  70. const char *HOST = "localhost";
  71. static int get_base_port() {
  72. const char *shard = getenv("GTEST_SHARD_INDEX");
  73. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  74. }
  75. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  76. // New standalone tests MUST use svr.bind_to_any_port() instead.
  77. const int PORT = get_base_port();
  78. const string LONG_QUERY_VALUE = string(25000, '@');
  79. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  80. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  81. const string TOO_LONG_QUERY_URL =
  82. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  83. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  84. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  85. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  86. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  87. return file.name == key;
  88. });
  89. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  90. return *it;
  91. #else
  92. if (it != items.end()) { return *it; }
  93. throw std::runtime_error("invalid multipart form data name error");
  94. #endif
  95. }
  96. static void read_file(const std::string &path, std::string &out) {
  97. std::ifstream fs(path, std::ios_base::binary);
  98. if (!fs) {
  99. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  100. return;
  101. #else
  102. throw std::runtime_error("File not found: " + path);
  103. #endif
  104. }
  105. fs.seekg(0, std::ios_base::end);
  106. auto size = fs.tellg();
  107. fs.seekg(0);
  108. out.resize(static_cast<size_t>(size));
  109. fs.read(&out[0], static_cast<std::streamsize>(size));
  110. }
  111. class UnixSocketTest : public ::testing::Test {
  112. protected:
  113. void TearDown() override { std::remove(pathname_.c_str()); }
  114. void client_GET(const std::string &addr) {
  115. httplib::Client cli{addr};
  116. cli.set_address_family(AF_UNIX);
  117. ASSERT_TRUE(cli.is_valid());
  118. const auto &result = cli.Get(pattern_);
  119. ASSERT_TRUE(result) << "error: " << result.error();
  120. const auto &resp = result.value();
  121. EXPECT_EQ(resp.status, StatusCode::OK_200);
  122. EXPECT_EQ(resp.body, content_);
  123. }
  124. static std::string make_sock_path() {
  125. const char *shard = getenv("GTEST_SHARD_INDEX");
  126. return shard ? std::string("./httplib-server-") + shard + ".sock"
  127. : "./httplib-server.sock";
  128. }
  129. const std::string pathname_{make_sock_path()};
  130. const std::string pattern_{"/hi"};
  131. const std::string content_{"Hello World!"};
  132. };
  133. TEST_F(UnixSocketTest, pathname) {
  134. httplib::Server svr;
  135. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  136. res.set_content(content_, "text/plain");
  137. });
  138. std::thread t{[&] {
  139. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  140. }};
  141. auto se = detail::scope_exit([&] {
  142. svr.stop();
  143. t.join();
  144. ASSERT_FALSE(svr.is_running());
  145. });
  146. svr.wait_until_ready();
  147. ASSERT_TRUE(svr.is_running());
  148. client_GET(pathname_);
  149. }
  150. #if defined(__linux__) || \
  151. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  152. TEST_F(UnixSocketTest, PeerPid) {
  153. httplib::Server svr;
  154. std::string remote_port_val;
  155. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  156. res.set_content(content_, "text/plain");
  157. remote_port_val = std::to_string(req.remote_port);
  158. });
  159. std::thread t{[&] {
  160. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  161. }};
  162. auto se = detail::scope_exit([&] {
  163. svr.stop();
  164. t.join();
  165. ASSERT_FALSE(svr.is_running());
  166. });
  167. svr.wait_until_ready();
  168. ASSERT_TRUE(svr.is_running());
  169. client_GET(pathname_);
  170. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  171. }
  172. #endif
  173. #ifdef __linux__
  174. TEST_F(UnixSocketTest, abstract) {
  175. constexpr char svr_path[]{"\x00httplib-server.sock"};
  176. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  177. httplib::Server svr;
  178. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  179. res.set_content(content_, "text/plain");
  180. });
  181. std::thread t{[&] {
  182. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  183. }};
  184. auto se = detail::scope_exit([&] {
  185. svr.stop();
  186. t.join();
  187. ASSERT_FALSE(svr.is_running());
  188. });
  189. svr.wait_until_ready();
  190. ASSERT_TRUE(svr.is_running());
  191. client_GET(abstract_addr);
  192. }
  193. #endif
  194. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  195. httplib::Server svr;
  196. std::string received_host_header;
  197. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  198. // Capture the Host header sent by the client
  199. auto host_iter = req.headers.find("Host");
  200. if (host_iter != req.headers.end()) {
  201. received_host_header = host_iter->second;
  202. }
  203. res.set_content(content_, "text/plain");
  204. });
  205. std::thread t{[&] {
  206. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  207. }};
  208. auto se = detail::scope_exit([&] {
  209. svr.stop();
  210. t.join();
  211. ASSERT_FALSE(svr.is_running());
  212. });
  213. svr.wait_until_ready();
  214. ASSERT_TRUE(svr.is_running());
  215. // Test that Host header is automatically set to "localhost" for Unix socket
  216. // connections
  217. httplib::Client cli{pathname_};
  218. cli.set_address_family(AF_UNIX);
  219. ASSERT_TRUE(cli.is_valid());
  220. const auto &result = cli.Get(pattern_);
  221. ASSERT_TRUE(result) << "error: " << result.error();
  222. const auto &resp = result.value();
  223. EXPECT_EQ(resp.status, StatusCode::OK_200);
  224. EXPECT_EQ(resp.body, content_);
  225. // Verify that Host header was automatically set to "localhost"
  226. EXPECT_EQ(received_host_header, "localhost");
  227. }
  228. #ifndef _WIN32
  229. TEST(SocketStream, wait_writable_UNIX) {
  230. int fds[2];
  231. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  232. const auto asSocketStream = [&](socket_t fd,
  233. std::function<bool(Stream &)> func) {
  234. return detail::process_client_socket(
  235. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  236. };
  237. asSocketStream(fds[0], [&](Stream &s0) {
  238. EXPECT_EQ(s0.socket(), fds[0]);
  239. EXPECT_TRUE(s0.wait_writable());
  240. EXPECT_TRUE(s0.is_peer_alive());
  241. EXPECT_EQ(0, close(fds[1]));
  242. EXPECT_FALSE(s0.is_peer_alive());
  243. return true;
  244. });
  245. EXPECT_EQ(0, close(fds[0]));
  246. }
  247. TEST(SocketStream, wait_writable_INET) {
  248. sockaddr_in addr;
  249. memset(&addr, 0, sizeof(addr));
  250. addr.sin_family = AF_INET;
  251. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  252. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  253. int disconnected_svr_sock = -1;
  254. std::thread svr{[&] {
  255. const int s = socket(AF_INET, SOCK_STREAM, 0);
  256. ASSERT_LE(0, s);
  257. // PORT + 1 is shared with the SSL redirect tests and with
  258. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  259. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  260. // because that happens on a worker thread the ASSERT does not stop the
  261. // test: it runs on and fails at the disconnected_svr_sock check instead.
  262. default_socket_options(s);
  263. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  264. ASSERT_EQ(0, listen(s, 1));
  265. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  266. ASSERT_EQ(0, close(s));
  267. }};
  268. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  269. std::thread cli{[&] {
  270. const int s = socket(AF_INET, SOCK_STREAM, 0);
  271. ASSERT_LE(0, s);
  272. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  273. ASSERT_EQ(0, close(s));
  274. }};
  275. cli.join();
  276. svr.join();
  277. ASSERT_NE(disconnected_svr_sock, -1);
  278. const auto asSocketStream = [&](socket_t fd,
  279. std::function<bool(Stream &)> func) {
  280. return detail::process_client_socket(
  281. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  282. };
  283. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  284. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  285. // wait_writable() returns true because select_write() only checks if the
  286. // send buffer has space. Peer disconnection is detected later by send().
  287. EXPECT_TRUE(ss.wait_writable());
  288. return true;
  289. });
  290. ASSERT_EQ(0, close(disconnected_svr_sock));
  291. }
  292. #endif // #ifndef _WIN32
  293. TEST(SetSocketOptTest, TcpNoDelay) {
  294. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  295. ASSERT_NE(sock, INVALID_SOCKET);
  296. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  297. int val = 0;
  298. socklen_t len = sizeof(val);
  299. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  300. reinterpret_cast<char *>(&val), &len));
  301. EXPECT_NE(val, 0);
  302. detail::close_socket(sock);
  303. }
  304. TEST(ClientTest, MoveConstructible) {
  305. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  306. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  307. }
  308. TEST(ClientTest, MoveAssignable) {
  309. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  310. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  311. }
  312. #ifdef _WIN32
  313. TEST(StartupTest, WSAStartup) {
  314. WSADATA wsaData;
  315. int ret = WSAStartup(0x0002, &wsaData);
  316. ASSERT_EQ(0, ret);
  317. }
  318. #endif
  319. TEST(DecodePathTest, PercentCharacter) {
  320. EXPECT_EQ(
  321. decode_path_component(
  322. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  323. U8("descrip=Gastos áéíóúñÑ 6"));
  324. }
  325. TEST(DecodePathTest, PercentCharacterNUL) {
  326. string expected;
  327. expected.push_back('x');
  328. expected.push_back('\0');
  329. expected.push_back('x');
  330. EXPECT_EQ(decode_path_component("x%00x"), expected);
  331. }
  332. TEST(DecodePathTest, UnicodeEncoding) {
  333. // %u0041 = 'A' (1-byte UTF-8)
  334. EXPECT_EQ("A", decode_path_component("%u0041"));
  335. // %u00E9 = 'é' (2-byte UTF-8)
  336. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  337. // %u3042 = 'あ' (3-byte UTF-8)
  338. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  339. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  340. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  341. // %uD800 = surrogate (invalid, silently dropped)
  342. EXPECT_EQ("", decode_path_component("%uD800"));
  343. }
  344. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  345. // A sign or whitespace inside the two-character escape window must not be
  346. // accepted as a valid percent-encoding; the sequence is passed through
  347. // literally, matching decode_uri_component / decode_path_component.
  348. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  349. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  350. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  351. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  352. // Well-formed escapes still decode.
  353. EXPECT_EQ("-", decode_query_component("%2D", false));
  354. EXPECT_EQ("A", decode_query_component("%41", false));
  355. }
  356. TEST(SanitizeFilenameTest, VariousPatterns) {
  357. // Path traversal
  358. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  359. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  360. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  361. // Normal and edge cases
  362. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  363. EXPECT_EQ("filename.txt",
  364. httplib::sanitize_filename("/path/to/filename.txt"));
  365. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  366. EXPECT_EQ("", httplib::sanitize_filename(".."));
  367. EXPECT_EQ("", httplib::sanitize_filename(""));
  368. // Null bytes stripped
  369. EXPECT_EQ("safe.txt",
  370. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  371. // Whitespace-only rejected
  372. EXPECT_EQ("", httplib::sanitize_filename(" "));
  373. }
  374. // Forward declaration (see the base64_encode note below): split builds move the
  375. // definition into httplib.cc, so re-declaring it here lets the test link.
  376. namespace httplib {
  377. namespace detail {
  378. bool is_chunked_transfer_encoding(const Headers &headers);
  379. } // namespace detail
  380. } // namespace httplib
  381. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  382. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  383. auto make = [](std::initializer_list<const char *> lines) {
  384. Headers h;
  385. for (auto te : lines) {
  386. if (te) { h.emplace("Transfer-Encoding", te); }
  387. }
  388. return h;
  389. };
  390. // Sole coding, matched case-insensitively.
  391. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  392. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  393. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  394. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  395. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  396. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  397. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  398. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  399. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  400. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  401. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  402. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  403. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  404. // were received, into one list. Headers preserves that order, so the answer
  405. // is decided by the last coding of the last line and the order the lines
  406. // arrived in is significant.
  407. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  408. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  409. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  410. // The split can fall anywhere in the list.
  411. EXPECT_TRUE(
  412. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  413. EXPECT_FALSE(
  414. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  415. // A trailing line naming no coding leaves the list ending in nothing, so it
  416. // must not inherit the chunked from the line before it.
  417. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  418. }
  419. // Forward declaration: in split builds split.py strips `inline` and moves the
  420. // definition into httplib.cc, so detail::base64_encode is not visible from the
  421. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  422. // in both header-only and split builds.
  423. namespace httplib {
  424. namespace detail {
  425. std::string base64_encode(const std::string &in);
  426. } // namespace detail
  427. } // namespace httplib
  428. TEST(Base64EncodeTest, KnownAnswers) {
  429. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  430. // where the accumulator's top bit is already set before the next shift.
  431. EXPECT_EQ("", detail::base64_encode(""));
  432. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  433. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  434. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  435. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  436. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  437. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  438. // High bytes keep the top bit set across several rounds.
  439. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  440. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  441. }
  442. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  443. string unescapedCharacters = "-_.!~*'()";
  444. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  445. }
  446. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  447. string reservedCharacters = ";,/?:@&=+$";
  448. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  449. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  450. }
  451. TEST(ClientQueryOrder, PreserveOrder) {
  452. // This test reproduces Issue #2259: client may reorder query parameters
  453. // when sending a GET request. The expected behavior is that the client
  454. // preserves the original query string order when the caller supplied it
  455. // as part of the path.
  456. Server svr;
  457. svr.Get("/", [&](const Request &req, Response &res) {
  458. // Echo back the raw target so the test can assert ordering
  459. res.set_content(req.target, "text/plain");
  460. });
  461. std::thread t{[&] { svr.listen(HOST, PORT); }};
  462. auto se = detail::scope_exit([&] {
  463. svr.stop();
  464. t.join();
  465. ASSERT_FALSE(svr.is_running());
  466. });
  467. svr.wait_until_ready();
  468. Client cli(HOST, PORT);
  469. ASSERT_TRUE(cli.is_valid());
  470. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  471. auto res = cli.Get(original);
  472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  473. // Expect the echoed target to exactly match the original path (order
  474. // preserved)
  475. EXPECT_EQ(res->body, original);
  476. }
  477. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  478. string chineseCharacters = U8("中国語");
  479. string russianCharacters = U8("дом");
  480. string brazilianCharacters = U8("óculos");
  481. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  482. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  483. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  484. "%D0%B4%D0%BE%D0%BC");
  485. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  486. }
  487. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  488. string unescapedCharacters = "-_.!~*'()";
  489. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  490. }
  491. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  492. string reservedCharacters = ";,/?:@&=+$";
  493. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  494. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  495. }
  496. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  497. string chineseCharacters = U8("中国語");
  498. string russianCharacters = U8("дом");
  499. string brazilianCharacters = U8("óculos");
  500. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  501. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  502. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  503. "%D0%B4%D0%BE%D0%BC");
  504. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  505. }
  506. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  507. // Issue #2082 use case: encoding path component with ampersand
  508. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  509. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  510. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  511. }
  512. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  513. string unescapedCharacters = "-_.!~*'()";
  514. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  515. }
  516. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  517. string reservedCharacters = ";,/?:@&=+$#";
  518. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  519. }
  520. TEST(EncodeUriTest, TestUTF8Characters) {
  521. string chineseCharacters = U8("中国語");
  522. string russianCharacters = U8("дом");
  523. string brazilianCharacters = U8("óculos");
  524. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  525. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  526. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  527. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  528. }
  529. TEST(EncodeUriTest, TestCompleteUri) {
  530. string uri =
  531. "https://example.com/path/to/resource?query=value&param=test#fragment";
  532. EXPECT_EQ(
  533. httplib::encode_uri(uri),
  534. "https://example.com/path/to/resource?query=value&param=test#fragment");
  535. }
  536. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  537. string uri =
  538. "https://example.com/path with spaces/file name.html?q=hello world";
  539. EXPECT_EQ(httplib::encode_uri(uri),
  540. "https://example.com/path%20with%20spaces/"
  541. "file%20name.html?q=hello%20world");
  542. }
  543. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  544. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  545. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  546. }
  547. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  548. string unescapedCharacters = "-_.!~*'()";
  549. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  550. }
  551. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  552. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  553. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  554. string encodedBrazilian = "%C3%B3culos";
  555. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  556. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  557. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  558. }
  559. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  560. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  561. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  562. "Piri Tommy Villiers - on & on");
  563. }
  564. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  565. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  566. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  567. }
  568. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  569. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  570. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  571. }
  572. TEST(DecodeUriTest, TestUTF8Characters) {
  573. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  574. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  575. string encodedBrazilian = "%C3%B3culos";
  576. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  577. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  578. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  579. }
  580. TEST(DecodeUriTest, TestCompleteUri) {
  581. string encodedUri = "https://example.com/path%20with%20spaces/"
  582. "file%20name.html?q=hello%20world";
  583. EXPECT_EQ(
  584. httplib::decode_uri(encodedUri),
  585. "https://example.com/path with spaces/file name.html?q=hello world");
  586. }
  587. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  588. string original =
  589. "https://example.com/path with spaces/file name.html?q=hello world";
  590. string encoded = httplib::encode_uri(original);
  591. string decoded = httplib::decode_uri(encoded);
  592. EXPECT_EQ(decoded, original);
  593. }
  594. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  595. // decode_uri is the inverse of encode_uri: an escaped reserved character
  596. // stays encoded so it is not promoted into a real delimiter, while
  597. // non-reserved escapes still decode (like JS decodeURI).
  598. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  599. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  600. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  601. "%3F%3A%40%26%3D%2B%24%2C%3B");
  602. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  603. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  604. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  605. "http://example.com/a%2Fb");
  606. // decode_uri_component still decodes the reserved character.
  607. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  608. }
  609. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  610. string original = "Piri Tommy Villiers - on & on";
  611. string encoded = httplib::encode_uri_component(original);
  612. string decoded = httplib::decode_uri_component(encoded);
  613. EXPECT_EQ(decoded, original);
  614. }
  615. TEST(TrimTests, TrimStringTests) {
  616. EXPECT_EQ("abc", detail::trim_copy("abc"));
  617. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  618. EXPECT_TRUE(detail::trim_copy("").empty());
  619. }
  620. TEST(AsciiTest, LocaleIndependentClassification) {
  621. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  622. // which consult the global C locale: std::isalnum(0xC5) can return true
  623. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  624. // helpers must classify every byte by the ASCII grammar alone.
  625. for (int i = 0; i < 256; i++) {
  626. auto c = static_cast<char>(i);
  627. auto is_digit = i >= '0' && i <= '9';
  628. auto is_upper = i >= 'A' && i <= 'Z';
  629. auto is_lower = i >= 'a' && i <= 'z';
  630. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  631. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  632. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  633. << "byte " << i;
  634. }
  635. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  636. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  637. // Non-ASCII bytes must be percent-encoded, never passed through as
  638. // alphanumeric.
  639. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  640. }
  641. TEST(FromCharsTest, Double) {
  642. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  643. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  644. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  645. auto parse = [](const std::string &s, double &v) {
  646. return detail::from_chars(s.data(), s.data() + s.size(), v);
  647. };
  648. double v = -1.0;
  649. // Representative quality values.
  650. EXPECT_EQ(parse("0", v).ec, std::errc{});
  651. EXPECT_DOUBLE_EQ(v, 0.0);
  652. EXPECT_EQ(parse("1", v).ec, std::errc{});
  653. EXPECT_DOUBLE_EQ(v, 1.0);
  654. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  655. EXPECT_DOUBLE_EQ(v, 0.8);
  656. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  657. EXPECT_DOUBLE_EQ(v, 0.001);
  658. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  659. EXPECT_DOUBLE_EQ(v, 1.0);
  660. // A missing integer or fractional part is tolerated.
  661. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  662. EXPECT_DOUBLE_EQ(v, 0.5);
  663. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  664. EXPECT_DOUBLE_EQ(v, 5.0);
  665. // Values outside [0, 1] still parse; the caller range-checks them.
  666. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  667. EXPECT_DOUBLE_EQ(v, 123.456);
  668. // Stops at the first byte that is not part of the number and reports where.
  669. std::string trailing = "0.9, text/html";
  670. auto r = parse(trailing, v);
  671. EXPECT_EQ(r.ec, std::errc{});
  672. EXPECT_DOUBLE_EQ(v, 0.9);
  673. EXPECT_EQ(*r.ptr, ',');
  674. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  675. // outright, and an 'e'/'E' simply ends the number.
  676. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  677. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  678. std::string exp_input = "1.5e3";
  679. r = parse(exp_input, v);
  680. EXPECT_EQ(r.ec, std::errc{});
  681. EXPECT_DOUBLE_EQ(v, 1.5);
  682. EXPECT_EQ(*r.ptr, 'e');
  683. // Invalid inputs.
  684. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  685. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  686. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  687. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  688. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  689. // Pathological but well-formed inputs must stay bounded (no overflow, no
  690. // out-of-bounds table access) and stay within [0, 1] for the caller.
  691. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  692. std::errc{});
  693. EXPECT_DOUBLE_EQ(v, 0.0);
  694. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  695. std::errc{});
  696. EXPECT_GE(v, 0.0);
  697. EXPECT_LE(v, 1.0);
  698. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  699. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  700. }
  701. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  702. // Simple case without quality values
  703. std::vector<std::string> result1;
  704. EXPECT_TRUE(detail::parse_accept_header(
  705. "text/html,application/json,text/plain", result1));
  706. EXPECT_EQ(result1.size(), 3U);
  707. EXPECT_EQ(result1[0], "text/html");
  708. EXPECT_EQ(result1[1], "application/json");
  709. EXPECT_EQ(result1[2], "text/plain");
  710. // With quality values
  711. std::vector<std::string> result2;
  712. EXPECT_TRUE(detail::parse_accept_header(
  713. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  714. EXPECT_EQ(result2.size(), 3U);
  715. EXPECT_EQ(result2[0], "application/json"); // highest q value
  716. EXPECT_EQ(result2[1], "text/html");
  717. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  718. }
  719. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  720. // Mixed with and without quality values
  721. std::vector<std::string> result;
  722. EXPECT_TRUE(detail::parse_accept_header(
  723. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  724. EXPECT_EQ(result.size(), 3U);
  725. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  726. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  727. EXPECT_EQ(result[2], "application/json"); // q=0.5
  728. }
  729. TEST(ParseAcceptHeaderTest, EdgeCases) {
  730. // Empty header
  731. std::vector<std::string> empty_result;
  732. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  733. EXPECT_TRUE(empty_result.empty());
  734. // Single type
  735. std::vector<std::string> single_result;
  736. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  737. EXPECT_EQ(single_result.size(), 1U);
  738. EXPECT_EQ(single_result[0], "application/json");
  739. // Wildcard types
  740. std::vector<std::string> wildcard_result;
  741. EXPECT_TRUE(detail::parse_accept_header(
  742. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  743. EXPECT_EQ(wildcard_result.size(), 3U);
  744. EXPECT_EQ(wildcard_result[0], "application/json");
  745. EXPECT_EQ(wildcard_result[1], "text/*");
  746. EXPECT_EQ(wildcard_result[2], "*/*");
  747. }
  748. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  749. // Common browser Accept header
  750. std::vector<std::string> browser_result;
  751. EXPECT_TRUE(
  752. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  753. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  754. browser_result));
  755. EXPECT_EQ(browser_result.size(), 6U);
  756. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  757. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  758. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  759. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  760. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  761. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  762. // API client header
  763. std::vector<std::string> api_result;
  764. EXPECT_TRUE(detail::parse_accept_header(
  765. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  766. api_result));
  767. EXPECT_EQ(api_result.size(), 3U);
  768. EXPECT_EQ(api_result[0], "application/json");
  769. EXPECT_EQ(api_result[1], "application/xml");
  770. EXPECT_EQ(api_result[2], "text/plain");
  771. }
  772. TEST(ParseAcceptHeaderTest, SpecialCases) {
  773. // Quality value with 3 decimal places
  774. std::vector<std::string> decimal_result;
  775. EXPECT_TRUE(detail::parse_accept_header(
  776. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  777. EXPECT_EQ(decimal_result.size(), 2U);
  778. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  779. EXPECT_EQ(decimal_result[1], "text/html");
  780. // Zero quality (should still be included but with lowest priority)
  781. std::vector<std::string> zero_q_result;
  782. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  783. zero_q_result));
  784. EXPECT_EQ(zero_q_result.size(), 2U);
  785. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  786. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  787. // No spaces around commas
  788. std::vector<std::string> no_space_result;
  789. EXPECT_TRUE(detail::parse_accept_header(
  790. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  791. no_space_result));
  792. EXPECT_EQ(no_space_result.size(), 3U);
  793. EXPECT_EQ(no_space_result[0], "text/html");
  794. EXPECT_EQ(no_space_result[1], "application/json");
  795. EXPECT_EQ(no_space_result[2], "text/plain");
  796. }
  797. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  798. // Quality values always use '.' as the decimal separator, so parsing must
  799. // not depend on the process locale. An embedding application may have
  800. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  801. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  802. std::string saved = cur ? cur : "C";
  803. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  804. "fr_FR.UTF-8"};
  805. bool switched = false;
  806. for (const auto loc : comma_locales) {
  807. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  808. std::localeconv()->decimal_point[0] == ',') {
  809. switched = true;
  810. break;
  811. }
  812. }
  813. if (!switched) {
  814. std::setlocale(LC_NUMERIC, saved.c_str());
  815. GTEST_SKIP() << "no comma-decimal locale available on this host";
  816. }
  817. // The higher-weighted type appears later in the list, so a correct parse
  818. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  819. // sensitive parse reads both weights as 0 and leaves the original order.
  820. std::vector<std::string> result;
  821. EXPECT_TRUE(detail::parse_accept_header(
  822. "application/json;q=0.1,text/html;q=0.9", result));
  823. ASSERT_EQ(result.size(), 2U);
  824. EXPECT_EQ(result[0], "text/html");
  825. EXPECT_EQ(result[1], "application/json");
  826. std::setlocale(LC_NUMERIC, saved.c_str());
  827. }
  828. TEST(ParseAcceptHeaderTest, InvalidCases) {
  829. std::vector<std::string> result;
  830. // Invalid quality value (> 1.0)
  831. EXPECT_FALSE(
  832. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  833. // Invalid quality value (< 0.0)
  834. EXPECT_FALSE(
  835. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  836. // Invalid quality value (not a number)
  837. EXPECT_FALSE(detail::parse_accept_header(
  838. "text/html;q=invalid,application/json", result));
  839. // Empty quality value
  840. EXPECT_FALSE(
  841. detail::parse_accept_header("text/html;q=,application/json", result));
  842. // Invalid media type format (no slash and not wildcard)
  843. EXPECT_FALSE(
  844. detail::parse_accept_header("invalidtype,application/json", result));
  845. // Empty media type
  846. result.clear();
  847. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  848. // Only commas
  849. result.clear();
  850. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  851. // Valid cases should still work
  852. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  853. EXPECT_EQ(result.size(), 1U);
  854. EXPECT_EQ(result[0], "*/*");
  855. EXPECT_TRUE(detail::parse_accept_header("*", result));
  856. EXPECT_EQ(result.size(), 1U);
  857. EXPECT_EQ(result[0], "*");
  858. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  859. EXPECT_EQ(result.size(), 1U);
  860. EXPECT_EQ(result[0], "text/*");
  861. }
  862. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  863. Server svr;
  864. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  865. EXPECT_EQ(req.accept_content_types.size(), 3U);
  866. EXPECT_EQ(req.accept_content_types[0], "application/json");
  867. EXPECT_EQ(req.accept_content_types[1], "text/html");
  868. EXPECT_EQ(req.accept_content_types[2], "*/*");
  869. res.set_content("ok", "text/plain");
  870. });
  871. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  872. EXPECT_TRUE(false);
  873. res.set_content("bad request", "text/plain");
  874. });
  875. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  876. auto se = detail::scope_exit([&] {
  877. svr.stop();
  878. listen_thread.join();
  879. ASSERT_FALSE(svr.is_running());
  880. });
  881. svr.wait_until_ready();
  882. Client cli("localhost", PORT);
  883. {
  884. auto res = cli.Get(
  885. "/accept_ok",
  886. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  887. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  888. EXPECT_EQ(StatusCode::OK_200, res->status);
  889. }
  890. {
  891. auto res = cli.Get("/accept_bad_request",
  892. Headers{{"Accept", "text/html;q=abc,application/json"}});
  893. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  894. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  895. }
  896. }
  897. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  898. Server svr;
  899. svr.Get("/", [](const Request & /*req*/, Response &res) {
  900. res.set_content("ok", "text/plain");
  901. });
  902. std::atomic<int> start_count{0};
  903. std::atomic<bool> running_when_called{false};
  904. svr.set_start_handler([&]() {
  905. running_when_called = svr.is_running();
  906. start_count++;
  907. });
  908. auto port = svr.bind_to_any_port(HOST);
  909. std::thread t([&]() { svr.listen_after_bind(); });
  910. auto se = detail::scope_exit([&] {
  911. svr.stop();
  912. t.join();
  913. ASSERT_FALSE(svr.is_running());
  914. });
  915. svr.wait_until_ready();
  916. // A successful request proves the accept loop is running, which the start
  917. // handler precedes; so by now the handler must have run exactly once.
  918. Client cli(HOST, port);
  919. cli.set_connection_timeout(std::chrono::seconds(5));
  920. auto res = cli.Get("/");
  921. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  922. EXPECT_EQ(StatusCode::OK_200, res->status);
  923. EXPECT_EQ(1, start_count.load());
  924. EXPECT_TRUE(running_when_called.load());
  925. }
  926. TEST(DivideTest, DivideStringTests) {
  927. auto divide = [](const std::string &str, char d) {
  928. std::string lhs;
  929. std::string rhs;
  930. detail::divide(str, d,
  931. [&](const char *lhs_data, std::size_t lhs_size,
  932. const char *rhs_data, std::size_t rhs_size) {
  933. lhs.assign(lhs_data, lhs_size);
  934. rhs.assign(rhs_data, rhs_size);
  935. });
  936. return std::make_pair(std::move(lhs), std::move(rhs));
  937. };
  938. {
  939. const auto res = divide("", '=');
  940. EXPECT_EQ(res.first, "");
  941. EXPECT_EQ(res.second, "");
  942. }
  943. {
  944. const auto res = divide("=", '=');
  945. EXPECT_EQ(res.first, "");
  946. EXPECT_EQ(res.second, "");
  947. }
  948. {
  949. const auto res = divide(" ", '=');
  950. EXPECT_EQ(res.first, " ");
  951. EXPECT_EQ(res.second, "");
  952. }
  953. {
  954. const auto res = divide("a", '=');
  955. EXPECT_EQ(res.first, "a");
  956. EXPECT_EQ(res.second, "");
  957. }
  958. {
  959. const auto res = divide("a=", '=');
  960. EXPECT_EQ(res.first, "a");
  961. EXPECT_EQ(res.second, "");
  962. }
  963. {
  964. const auto res = divide("=b", '=');
  965. EXPECT_EQ(res.first, "");
  966. EXPECT_EQ(res.second, "b");
  967. }
  968. {
  969. const auto res = divide("a=b", '=');
  970. EXPECT_EQ(res.first, "a");
  971. EXPECT_EQ(res.second, "b");
  972. }
  973. {
  974. const auto res = divide("a=b=", '=');
  975. EXPECT_EQ(res.first, "a");
  976. EXPECT_EQ(res.second, "b=");
  977. }
  978. {
  979. const auto res = divide("a=b=c", '=');
  980. EXPECT_EQ(res.first, "a");
  981. EXPECT_EQ(res.second, "b=c");
  982. }
  983. }
  984. TEST(SplitTest, ParseQueryString) {
  985. string s = "key1=val1&key2=val2&key3=val3";
  986. Params dic;
  987. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  988. [&](const char *b, const char *e) {
  989. string key, val;
  990. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  991. if (key.empty()) {
  992. key.assign(b2, e2);
  993. } else {
  994. val.assign(b2, e2);
  995. }
  996. });
  997. dic.emplace(key, val);
  998. });
  999. EXPECT_EQ("val1", dic.find("key1")->second);
  1000. EXPECT_EQ("val2", dic.find("key2")->second);
  1001. EXPECT_EQ("val3", dic.find("key3")->second);
  1002. }
  1003. TEST(SplitTest, ParseInvalidQueryTests) {
  1004. {
  1005. string s = " ";
  1006. Params dict;
  1007. detail::parse_query_text(s, dict);
  1008. EXPECT_TRUE(dict.empty());
  1009. }
  1010. {
  1011. string s = " = =";
  1012. Params dict;
  1013. detail::parse_query_text(s, dict);
  1014. EXPECT_TRUE(dict.empty());
  1015. }
  1016. }
  1017. TEST(ParseQueryTest, ParseQueryString) {
  1018. {
  1019. std::string s = "key1=val1&key2=val2&key3=val3";
  1020. Params dic;
  1021. detail::parse_query_text(s, dic);
  1022. EXPECT_EQ("val1", dic.find("key1")->second);
  1023. EXPECT_EQ("val2", dic.find("key2")->second);
  1024. EXPECT_EQ("val3", dic.find("key3")->second);
  1025. }
  1026. {
  1027. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1028. Params dic;
  1029. detail::parse_query_text(s, dic);
  1030. EXPECT_EQ("", dic.find("key1")->second);
  1031. EXPECT_EQ("val1", dic.find("key2")->second);
  1032. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1033. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1034. }
  1035. }
  1036. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1037. Params dic;
  1038. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1039. dic.emplace("key1", "val1");
  1040. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1041. dic.emplace("key2", "val2");
  1042. dic.emplace("key3", "val3");
  1043. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1044. }
  1045. // Joins every entry of a Headers or Params into "key=value " so a whole
  1046. // traversal can be compared in one assertion. Both are instantiations of the
  1047. // same insertion-ordered container, so one helper serves both.
  1048. template <typename Map> static std::string entries_to_string(const Map &m) {
  1049. std::string s;
  1050. for (const auto &entry : m) {
  1051. s += entry.first + "=" + entry.second + " ";
  1052. }
  1053. return s;
  1054. }
  1055. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1056. // Params used to be a std::multimap, which sorted by name and handed the
  1057. // caller's query back alphabetised. A client signing its query string could
  1058. // not reproduce the order it asked for.
  1059. Params dic;
  1060. dic.emplace("zulu", "1");
  1061. dic.emplace("alpha", "2");
  1062. dic.emplace("mike", "3");
  1063. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1064. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1065. }
  1066. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1067. Params dic;
  1068. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1069. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1070. }
  1071. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1072. Request req;
  1073. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1074. req.params);
  1075. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1076. EXPECT_EQ("first", req.get_param_value("tag"));
  1077. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1078. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1079. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1080. EXPECT_EQ("", req.get_param_value("tag", 3));
  1081. }
  1082. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1083. // Params shares its container with Headers, which matches field names
  1084. // case-insensitively. Parameter names must not pick that up.
  1085. Params dic;
  1086. dic.emplace("Key", "upper");
  1087. dic.emplace("key", "lower");
  1088. EXPECT_EQ(2U, dic.size());
  1089. EXPECT_EQ(1U, dic.count("Key"));
  1090. EXPECT_EQ(1U, dic.count("key"));
  1091. EXPECT_EQ("upper", dic.find("Key")->second);
  1092. EXPECT_EQ("lower", dic.find("key")->second);
  1093. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1094. }
  1095. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1096. Server svr;
  1097. std::string order;
  1098. svr.Get("/order", [&](const Request &req, Response &res) {
  1099. order = entries_to_string(req.params);
  1100. res.set_content("ok", "text/plain");
  1101. });
  1102. auto port = svr.bind_to_any_port(HOST);
  1103. thread t = thread([&] { svr.listen_after_bind(); });
  1104. auto se = detail::scope_exit([&] {
  1105. svr.stop();
  1106. t.join();
  1107. ASSERT_FALSE(svr.is_running());
  1108. });
  1109. svr.wait_until_ready();
  1110. Client cli(HOST, port);
  1111. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1112. ASSERT_TRUE(res);
  1113. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1114. }
  1115. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1116. Server svr;
  1117. std::string field_order, file_order;
  1118. svr.Post("/order", [&](const Request &req, Response &res) {
  1119. for (const auto &field : req.form.fields) {
  1120. field_order += field.first + "=" + field.second.content + " ";
  1121. }
  1122. for (const auto &file : req.form.files) {
  1123. file_order += file.first + "=" + file.second.filename + " ";
  1124. }
  1125. res.set_content("ok", "text/plain");
  1126. });
  1127. auto port = svr.bind_to_any_port(HOST);
  1128. thread t = thread([&] { svr.listen_after_bind(); });
  1129. auto se = detail::scope_exit([&] {
  1130. svr.stop();
  1131. t.join();
  1132. ASSERT_FALSE(svr.is_running());
  1133. });
  1134. svr.wait_until_ready();
  1135. UploadFormDataItems items = {
  1136. {"zulu", "1", "", ""},
  1137. {"alpha", "2", "", ""},
  1138. {"mike", "3", "", ""},
  1139. {"zebra", "z", "z.txt", "text/plain"},
  1140. {"apple", "a", "a.txt", "text/plain"},
  1141. };
  1142. Client cli(HOST, port);
  1143. auto res = cli.Post("/order", items);
  1144. ASSERT_TRUE(res);
  1145. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1146. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1147. }
  1148. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1149. Server svr;
  1150. std::vector<std::string> values;
  1151. std::string first, second, out_of_range, order;
  1152. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1153. values = req.form.get_fields("tag");
  1154. first = req.form.get_field("tag", 0);
  1155. second = req.form.get_field("tag", 1);
  1156. out_of_range = req.form.get_field("tag", 2);
  1157. for (const auto &field : req.form.fields) {
  1158. order += field.first + "=" + field.second.content + " ";
  1159. }
  1160. res.set_content("ok", "text/plain");
  1161. });
  1162. auto port = svr.bind_to_any_port(HOST);
  1163. thread t = thread([&] { svr.listen_after_bind(); });
  1164. auto se = detail::scope_exit([&] {
  1165. svr.stop();
  1166. t.join();
  1167. ASSERT_FALSE(svr.is_running());
  1168. });
  1169. svr.wait_until_ready();
  1170. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1171. // not adjacent in the container.
  1172. UploadFormDataItems items = {
  1173. {"tag", "first", "", ""},
  1174. {"other", "x", "", ""},
  1175. {"tag", "second", "", ""},
  1176. };
  1177. Client cli(HOST, port);
  1178. auto res = cli.Post("/repeated", items);
  1179. ASSERT_TRUE(res);
  1180. ASSERT_EQ(2U, values.size());
  1181. EXPECT_EQ("first", values[0]);
  1182. EXPECT_EQ("second", values[1]);
  1183. EXPECT_EQ("first", first);
  1184. EXPECT_EQ("second", second);
  1185. // std::multimap already kept entries sharing a name in insertion order, so
  1186. // everything above passes without this change too. The whole traversal is
  1187. // what tells the two apart: sorting by name would hoist "other" to the front
  1188. // and the two "tag" parts would end up adjacent.
  1189. EXPECT_EQ("tag=first other=x tag=second ", order);
  1190. // Advancing past the last entry of a name used to run off the container;
  1191. // the container's saturating increment makes it return the default instead.
  1192. EXPECT_EQ("", out_of_range);
  1193. }
  1194. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1195. // Server::read_content() keeps a FormFields::iterator alive across the
  1196. // content callbacks that fill the part it points at. The container is
  1197. // vector-backed, so a later emplace can reallocate and invalidate an older
  1198. // iterator; 64 parts grow the vector through seven reallocations, which
  1199. // checks that every part's content still lands in its own entry.
  1200. const size_t part_count = 64;
  1201. // One formula for both the parts sent and the values expected back, so the
  1202. // two cannot drift apart.
  1203. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1204. auto content_of = [](size_t i) {
  1205. return std::string(64, static_cast<char>('a' + (i % 26)));
  1206. };
  1207. Server svr;
  1208. std::vector<std::pair<std::string, std::string>> received;
  1209. svr.Post("/many", [&](const Request &req, Response &res) {
  1210. for (const auto &field : req.form.fields) {
  1211. received.emplace_back(field.first, field.second.content);
  1212. }
  1213. res.set_content("ok", "text/plain");
  1214. });
  1215. auto port = svr.bind_to_any_port(HOST);
  1216. thread t = thread([&] { svr.listen_after_bind(); });
  1217. auto se = detail::scope_exit([&] {
  1218. svr.stop();
  1219. t.join();
  1220. ASSERT_FALSE(svr.is_running());
  1221. });
  1222. svr.wait_until_ready();
  1223. UploadFormDataItems items;
  1224. for (size_t i = 0; i < part_count; i++) {
  1225. items.push_back({name_of(i), content_of(i), "", ""});
  1226. }
  1227. Client cli(HOST, port);
  1228. auto res = cli.Post("/many", items);
  1229. ASSERT_TRUE(res);
  1230. ASSERT_EQ(part_count, received.size());
  1231. for (size_t i = 0; i < part_count; i++) {
  1232. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1233. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1234. }
  1235. }
  1236. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1237. string content_type = "multipart/form-data; boundary=something";
  1238. string boundary;
  1239. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1240. EXPECT_TRUE(ret);
  1241. EXPECT_EQ(boundary, "something");
  1242. }
  1243. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1244. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1245. string boundary;
  1246. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1247. EXPECT_TRUE(ret);
  1248. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1249. }
  1250. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1251. string content_type =
  1252. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1253. string boundary;
  1254. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1255. EXPECT_TRUE(ret);
  1256. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1257. }
  1258. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1259. string content_type =
  1260. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1261. string boundary;
  1262. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1263. EXPECT_TRUE(ret);
  1264. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1265. }
  1266. TEST(GetHeaderValueTest, DefaultValue) {
  1267. Headers headers = {{"Dummy", "Dummy"}};
  1268. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1269. EXPECT_STREQ("text/plain", val);
  1270. }
  1271. TEST(GetHeaderValueTest, DefaultValueInt) {
  1272. Headers headers = {{"Dummy", "Dummy"}};
  1273. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1274. EXPECT_EQ(100ull, val);
  1275. }
  1276. TEST(GetHeaderValueTest, RegularValue) {
  1277. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1278. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1279. EXPECT_STREQ("text/html", val);
  1280. }
  1281. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1282. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1283. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1284. EXPECT_STREQ("text/html", val);
  1285. }
  1286. TEST(GetHeaderValueTest, SetContent) {
  1287. Response res;
  1288. res.set_content("html", "text/html");
  1289. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1290. res.set_content("text", "text/plain");
  1291. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1292. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1293. }
  1294. TEST(GetHeaderValueTest, RegularValueInt) {
  1295. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1296. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1297. EXPECT_EQ(100ull, val);
  1298. }
  1299. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1300. Headers headers = {{"Content-Length", "x"}};
  1301. auto is_invalid_value = false;
  1302. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1303. is_invalid_value);
  1304. EXPECT_EQ(0ull, val);
  1305. EXPECT_TRUE(is_invalid_value);
  1306. }
  1307. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1308. // An all-digit value that overflows size_t must be reported as invalid, not
  1309. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1310. // a large length to a small one on 32-bit builds, leaving the framing length
  1311. // wrong while is_invalid_value stayed false.
  1312. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1313. auto is_invalid_value = false;
  1314. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1315. is_invalid_value);
  1316. EXPECT_TRUE(is_invalid_value);
  1317. // A well-formed length is unaffected.
  1318. Headers ok = {{"Content-Length", "1234"}};
  1319. is_invalid_value = false;
  1320. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1321. is_invalid_value);
  1322. EXPECT_EQ(1234ull, val);
  1323. EXPECT_FALSE(is_invalid_value);
  1324. }
  1325. TEST(GetHeaderValueTest, Range) {
  1326. {
  1327. Headers headers = {make_range_header({{1, -1}})};
  1328. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1329. EXPECT_STREQ("bytes=1-", val);
  1330. }
  1331. {
  1332. Headers headers = {make_range_header({{-1, 1}})};
  1333. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1334. EXPECT_STREQ("bytes=-1", val);
  1335. }
  1336. {
  1337. Headers headers = {make_range_header({{1, 10}})};
  1338. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1339. EXPECT_STREQ("bytes=1-10", val);
  1340. }
  1341. {
  1342. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1343. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1344. EXPECT_STREQ("bytes=1-10, 100-", val);
  1345. }
  1346. {
  1347. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1348. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1349. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1350. }
  1351. {
  1352. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1353. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1354. EXPECT_STREQ("bytes=0-0, -1", val);
  1355. }
  1356. }
  1357. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1358. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1359. // to depend on the standard library (libstdc++ handed back duplicates in
  1360. // reverse insertion order, libc++ in insertion order).
  1361. Request req;
  1362. req.set_header("Accept-Encoding", "gzip");
  1363. req.set_header("Accept-Encoding", "deflate");
  1364. req.set_header("Accept-Encoding", "br");
  1365. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1366. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1367. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1368. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1369. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1370. }
  1371. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1372. Request req;
  1373. req.set_header("X-Test", "only");
  1374. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1375. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1376. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1377. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1378. }
  1379. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1380. Headers headers;
  1381. headers.emplace("Host", "example.com");
  1382. headers.emplace("Accept-Encoding", "gzip");
  1383. headers.emplace("User-Agent", "test");
  1384. headers.emplace("Accept-Encoding", "deflate");
  1385. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1386. "Accept-Encoding=deflate ",
  1387. entries_to_string(headers));
  1388. }
  1389. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1390. Headers headers = {{"Content-Type", "text/html"},
  1391. {"CONTENT-TYPE", "text/xml"}};
  1392. EXPECT_EQ(2U, headers.count("content-type"));
  1393. auto it = headers.find("content-type");
  1394. ASSERT_TRUE(it != headers.end());
  1395. EXPECT_EQ("text/html", it->second);
  1396. }
  1397. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1398. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1399. // drop only those fields and leave everything positioned between them.
  1400. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1401. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1402. auto rng = headers.equal_range("a");
  1403. headers.erase(rng.first, rng.second);
  1404. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1405. }
  1406. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1407. Headers headers = {
  1408. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1409. EXPECT_EQ(3U, headers.erase("A"));
  1410. EXPECT_EQ(0U, headers.count("A"));
  1411. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1412. }
  1413. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1414. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1415. headers.emplace_front("Host", "example.com");
  1416. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1417. entries_to_string(headers));
  1418. }
  1419. TEST(ParseHeaderValueTest, Range) {
  1420. {
  1421. Ranges ranges;
  1422. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1423. EXPECT_TRUE(ret);
  1424. EXPECT_EQ(1u, ranges.size());
  1425. EXPECT_EQ(1u, ranges[0].first);
  1426. EXPECT_EQ(-1, ranges[0].second);
  1427. }
  1428. {
  1429. Ranges ranges;
  1430. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1431. EXPECT_TRUE(ret);
  1432. EXPECT_EQ(1u, ranges.size());
  1433. EXPECT_EQ(-1, ranges[0].first);
  1434. EXPECT_EQ(1u, ranges[0].second);
  1435. }
  1436. {
  1437. Ranges ranges;
  1438. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1439. EXPECT_TRUE(ret);
  1440. EXPECT_EQ(1u, ranges.size());
  1441. EXPECT_EQ(1u, ranges[0].first);
  1442. EXPECT_EQ(10u, ranges[0].second);
  1443. }
  1444. {
  1445. Ranges ranges;
  1446. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1447. EXPECT_FALSE(ret);
  1448. }
  1449. {
  1450. Ranges ranges;
  1451. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1452. EXPECT_TRUE(ret);
  1453. EXPECT_EQ(2u, ranges.size());
  1454. EXPECT_EQ(1u, ranges[0].first);
  1455. EXPECT_EQ(10u, ranges[0].second);
  1456. EXPECT_EQ(100u, ranges[1].first);
  1457. EXPECT_EQ(-1, ranges[1].second);
  1458. }
  1459. {
  1460. Ranges ranges;
  1461. auto ret =
  1462. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1463. EXPECT_TRUE(ret);
  1464. EXPECT_EQ(3u, ranges.size());
  1465. EXPECT_EQ(1u, ranges[0].first);
  1466. EXPECT_EQ(10u, ranges[0].second);
  1467. EXPECT_EQ(100u, ranges[1].first);
  1468. EXPECT_EQ(200u, ranges[1].second);
  1469. EXPECT_EQ(300u, ranges[2].first);
  1470. EXPECT_EQ(400u, ranges[2].second);
  1471. }
  1472. {
  1473. Ranges ranges;
  1474. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1475. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1476. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1477. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1478. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1479. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1480. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1481. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1482. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1483. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1484. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1485. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1486. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1487. EXPECT_TRUE(ranges.empty());
  1488. }
  1489. }
  1490. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  1491. Request req;
  1492. req.set_header("Accept-Encoding", "gzip");
  1493. Response res;
  1494. res.set_header("Content-Type", "text/plain");
  1495. auto ret = detail::encoding_type(req, res);
  1496. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1497. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1498. #else
  1499. EXPECT_TRUE(ret == detail::EncodingType::None);
  1500. #endif
  1501. }
  1502. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1503. Request req;
  1504. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  1505. Response res;
  1506. res.set_header("Content-Type", "text/plain");
  1507. auto ret = detail::encoding_type(req, res);
  1508. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1509. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1510. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1511. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1512. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1513. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1514. #else
  1515. EXPECT_TRUE(ret == detail::EncodingType::None);
  1516. #endif
  1517. }
  1518. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  1519. Request req;
  1520. req.set_header("Accept-Encoding",
  1521. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  1522. Response res;
  1523. res.set_header("Content-Type", "text/plain");
  1524. auto ret = detail::encoding_type(req, res);
  1525. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1526. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1527. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1528. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1529. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1530. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1531. #else
  1532. EXPECT_TRUE(ret == detail::EncodingType::None);
  1533. #endif
  1534. }
  1535. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  1536. // All supported encodings rejected with q=0 should return None
  1537. Request req;
  1538. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  1539. Response res;
  1540. res.set_header("Content-Type", "text/plain");
  1541. auto ret = detail::encoding_type(req, res);
  1542. EXPECT_TRUE(ret == detail::EncodingType::None);
  1543. }
  1544. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1545. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1546. Request req;
  1547. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1548. Response res;
  1549. res.set_header("Content-Type", "text/plain");
  1550. auto ret = detail::encoding_type(req, res);
  1551. EXPECT_TRUE(ret == detail::EncodingType::None);
  1552. }
  1553. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1554. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1555. Request req;
  1556. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1557. Response res;
  1558. res.set_header("Content-Type", "text/plain");
  1559. auto ret = detail::encoding_type(req, res);
  1560. EXPECT_TRUE(ret == detail::EncodingType::None);
  1561. }
  1562. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1563. // RFC 7231: Accept-Encoding values are case-insensitive
  1564. Request req;
  1565. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1566. Response res;
  1567. res.set_header("Content-Type", "text/plain");
  1568. auto ret = detail::encoding_type(req, res);
  1569. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1570. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1571. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1572. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1573. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1574. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1575. #else
  1576. EXPECT_TRUE(ret == detail::EncodingType::None);
  1577. #endif
  1578. }
  1579. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1580. // q value should determine priority, not hardcoded order
  1581. Request req;
  1582. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  1583. Response res;
  1584. res.set_header("Content-Type", "text/plain");
  1585. auto ret = detail::encoding_type(req, res);
  1586. // gzip has highest q=1.0, so it should be selected even though
  1587. // br and zstd are also supported
  1588. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1589. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1590. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1591. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1592. #elif CPPHTTPLIB_BROTLI_SUPPORT
  1593. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1594. #else
  1595. EXPECT_TRUE(ret == detail::EncodingType::None);
  1596. #endif
  1597. }
  1598. TEST(BufferStreamTest, read) {
  1599. detail::BufferStream strm1;
  1600. Stream &strm = strm1;
  1601. EXPECT_EQ(5, strm.write("hello"));
  1602. char buf[512];
  1603. EXPECT_EQ(2, strm.read(buf, 2));
  1604. EXPECT_EQ('h', buf[0]);
  1605. EXPECT_EQ('e', buf[1]);
  1606. EXPECT_EQ(2, strm.read(buf, 2));
  1607. EXPECT_EQ('l', buf[0]);
  1608. EXPECT_EQ('l', buf[1]);
  1609. EXPECT_EQ(1, strm.read(buf, 1));
  1610. EXPECT_EQ('o', buf[0]);
  1611. EXPECT_EQ(0, strm.read(buf, 1));
  1612. }
  1613. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1614. auto host = "www.httpwatch.com";
  1615. auto ip = hosted_at(host);
  1616. EXPECT_EQ("23.96.13.243", ip);
  1617. std::vector<std::string> addrs;
  1618. hosted_at(host, addrs);
  1619. EXPECT_EQ(1u, addrs.size());
  1620. }
  1621. #if 0 // It depends on each test environment...
  1622. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1623. auto host = "www.youtube.com";
  1624. std::vector<std::string> addrs;
  1625. hosted_at(host, addrs);
  1626. EXPECT_EQ(20u, addrs.size());
  1627. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1628. EXPECT_TRUE(it != addrs.end());
  1629. }
  1630. #endif
  1631. class ChunkedEncodingTest : public ::testing::Test {
  1632. protected:
  1633. ChunkedEncodingTest()
  1634. : cli_(HOST, PORT)
  1635. #ifdef CPPHTTPLIB_SSL_ENABLED
  1636. ,
  1637. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1638. #endif
  1639. {
  1640. cli_.set_connection_timeout(2);
  1641. #ifdef CPPHTTPLIB_SSL_ENABLED
  1642. cli_.enable_server_certificate_verification(false);
  1643. #endif
  1644. }
  1645. virtual void SetUp() {
  1646. read_file("./image.jpg", image_data_);
  1647. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1648. res.set_content("Hello World!", "text/plain");
  1649. });
  1650. svr_.Get(
  1651. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1652. res.set_chunked_content_provider(
  1653. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1654. size_t remaining = image_data_.size() - offset;
  1655. if (remaining == 0) {
  1656. sink.done();
  1657. } else {
  1658. constexpr size_t CHUNK_SIZE = 1024;
  1659. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1660. sink.write(&image_data_[offset], send_size);
  1661. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1662. }
  1663. return true;
  1664. });
  1665. });
  1666. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1667. svr_.wait_until_ready();
  1668. }
  1669. virtual void TearDown() {
  1670. svr_.stop();
  1671. if (!request_threads_.empty()) {
  1672. std::this_thread::sleep_for(std::chrono::seconds(1));
  1673. for (auto &t : request_threads_) {
  1674. t.join();
  1675. }
  1676. }
  1677. t_.join();
  1678. }
  1679. #ifdef CPPHTTPLIB_SSL_ENABLED
  1680. SSLClient cli_;
  1681. SSLServer svr_;
  1682. #else
  1683. Client cli_;
  1684. Server svr_;
  1685. #endif
  1686. thread t_;
  1687. std::vector<thread> request_threads_;
  1688. std::string image_data_;
  1689. };
  1690. TEST_F(ChunkedEncodingTest, NormalGet) {
  1691. auto res = cli_.Get("/chunked");
  1692. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1693. std::string out;
  1694. read_file("./image.jpg", out);
  1695. EXPECT_EQ(StatusCode::OK_200, res->status);
  1696. EXPECT_EQ(out, res->body);
  1697. }
  1698. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1699. std::string body;
  1700. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1701. body.append(data, data_length);
  1702. return true;
  1703. });
  1704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1705. std::string out;
  1706. read_file("./image.jpg", out);
  1707. EXPECT_EQ(StatusCode::OK_200, res->status);
  1708. EXPECT_EQ(out, body);
  1709. }
  1710. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1711. std::string body;
  1712. auto res = cli_.Get(
  1713. "/chunked",
  1714. [&](const Response &response) {
  1715. EXPECT_EQ(StatusCode::OK_200, response.status);
  1716. return true;
  1717. },
  1718. [&](const char *data, size_t data_length) {
  1719. body.append(data, data_length);
  1720. return true;
  1721. });
  1722. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1723. std::string out;
  1724. read_file("./image.jpg", out);
  1725. EXPECT_EQ(StatusCode::OK_200, res->status);
  1726. EXPECT_EQ(out, body);
  1727. }
  1728. TEST(RangeTest, FromHTTPBin_Online) {
  1729. auto host = "httpbingo.org";
  1730. auto path = std::string{"/range/32"};
  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. cli.set_connection_timeout(5);
  1739. {
  1740. auto res = cli.Get(path);
  1741. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1742. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1743. EXPECT_EQ(StatusCode::OK_200, res->status);
  1744. }
  1745. {
  1746. Headers headers = {make_range_header({{1, -1}})};
  1747. auto res = cli.Get(path, headers);
  1748. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1749. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1750. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1751. }
  1752. {
  1753. Headers headers = {make_range_header({{1, 10}})};
  1754. auto res = cli.Get(path, headers);
  1755. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1756. EXPECT_EQ("bcdefghijk", res->body);
  1757. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1758. }
  1759. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  1760. // entire resource, while the original httpbin returned 200. Both are
  1761. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  1762. {
  1763. Headers headers = {make_range_header({{0, 31}})};
  1764. auto res = cli.Get(path, headers);
  1765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1766. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1767. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1768. res->status == StatusCode::PartialContent_206);
  1769. }
  1770. {
  1771. Headers headers = {make_range_header({{0, -1}})};
  1772. auto res = cli.Get(path, headers);
  1773. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1774. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1775. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1776. res->status == StatusCode::PartialContent_206);
  1777. }
  1778. // go-httpbin returns 206 with clamped range for over-range requests,
  1779. // while the original httpbin returned 416. Both behaviors are observed
  1780. // in real servers, so we only verify the request succeeds.
  1781. {
  1782. Headers headers = {make_range_header({{0, 32}})};
  1783. auto res = cli.Get(path, headers);
  1784. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1785. }
  1786. }
  1787. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1788. auto host = "unresolvableaddress.local";
  1789. auto path = std::string{"/"};
  1790. #ifdef CPPHTTPLIB_SSL_ENABLED
  1791. auto port = 443;
  1792. SSLClient cli(host, port);
  1793. #else
  1794. auto port = 80;
  1795. Client cli(host, port);
  1796. #endif
  1797. cli.set_connection_timeout(1);
  1798. {
  1799. auto res = cli.Get(path);
  1800. ASSERT_FALSE(res);
  1801. }
  1802. std::this_thread::sleep_for(std::chrono::seconds(8));
  1803. }
  1804. #if defined(__linux__) && defined(__GLIBC__) && \
  1805. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  1806. // Forward declaration: in split builds split.py strips `inline` and moves the
  1807. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  1808. // visible from the public httplib.h. Re-declaring it here lets the tests link
  1809. // against the symbol in both header-only and split builds.
  1810. namespace httplib {
  1811. namespace detail {
  1812. int getaddrinfo_with_timeout(const char *node, const char *service,
  1813. const struct addrinfo *hints,
  1814. struct addrinfo **res, time_t timeout_sec);
  1815. } // namespace detail
  1816. } // namespace httplib
  1817. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  1818. //
  1819. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  1820. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  1821. // gai_suspend() call hits the connection timeout the function calls
  1822. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  1823. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  1824. // still alive and still references the now-destroyed stack frame.
  1825. //
  1826. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  1827. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  1828. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  1829. // and runs them in a container.
  1830. namespace {
  1831. bool should_run_issue_2431_tests() {
  1832. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  1833. return v && *v && std::string(v) != "0";
  1834. }
  1835. std::string unique_unresolvable_host(int n) {
  1836. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  1837. // glibc still asks the configured nameserver — which is exactly the path
  1838. // we want to exercise. A unique label per call avoids the resolver cache.
  1839. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  1840. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  1841. std::to_string(n) + ".invalid";
  1842. }
  1843. } // namespace
  1844. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  1845. if (!should_run_issue_2431_tests()) {
  1846. GTEST_SKIP()
  1847. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1848. }
  1849. for (int i = 0; i < 8; ++i) {
  1850. struct addrinfo hints;
  1851. memset(&hints, 0, sizeof(hints));
  1852. hints.ai_family = AF_UNSPEC;
  1853. hints.ai_socktype = SOCK_STREAM;
  1854. auto host = unique_unresolvable_host(i);
  1855. struct addrinfo *result = nullptr;
  1856. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1857. &result, /*timeout_sec=*/1);
  1858. if (rc == 0 && result) { freeaddrinfo(result); }
  1859. }
  1860. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  1861. // stack region they still believe holds their gaicb.
  1862. std::this_thread::sleep_for(std::chrono::seconds(3));
  1863. }
  1864. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  1865. if (!should_run_issue_2431_tests()) {
  1866. GTEST_SKIP()
  1867. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1868. }
  1869. std::atomic<bool> stop{false};
  1870. std::vector<std::thread> threads;
  1871. for (int t = 0; t < 8; ++t) {
  1872. threads.emplace_back([t, &stop] {
  1873. int i = 0;
  1874. while (!stop.load(std::memory_order_relaxed)) {
  1875. struct addrinfo hints;
  1876. memset(&hints, 0, sizeof(hints));
  1877. hints.ai_family = AF_UNSPEC;
  1878. hints.ai_socktype = SOCK_STREAM;
  1879. auto host = unique_unresolvable_host(t * 100000 + i++);
  1880. struct addrinfo *result = nullptr;
  1881. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1882. &result, /*timeout_sec=*/1);
  1883. if (rc == 0 && result) { freeaddrinfo(result); }
  1884. }
  1885. });
  1886. }
  1887. std::this_thread::sleep_for(std::chrono::seconds(8));
  1888. stop.store(true, std::memory_order_relaxed);
  1889. for (auto &th : threads) {
  1890. th.join();
  1891. }
  1892. std::this_thread::sleep_for(std::chrono::seconds(3));
  1893. }
  1894. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  1895. if (!should_run_issue_2431_tests()) {
  1896. GTEST_SKIP()
  1897. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1898. }
  1899. std::atomic<bool> stop{false};
  1900. std::vector<std::thread> threads;
  1901. for (int t = 0; t < 8; ++t) {
  1902. threads.emplace_back([t, &stop] {
  1903. int i = 0;
  1904. while (!stop.load(std::memory_order_relaxed)) {
  1905. auto host = unique_unresolvable_host(t * 100000 + i++);
  1906. Client cli(host, 80);
  1907. cli.set_connection_timeout(1, 0);
  1908. cli.set_read_timeout(1, 0);
  1909. cli.set_write_timeout(1, 0);
  1910. (void)cli.Get("/");
  1911. }
  1912. });
  1913. }
  1914. std::this_thread::sleep_for(std::chrono::seconds(8));
  1915. stop.store(true, std::memory_order_relaxed);
  1916. for (auto &th : threads) {
  1917. th.join();
  1918. }
  1919. std::this_thread::sleep_for(std::chrono::seconds(3));
  1920. }
  1921. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  1922. TEST(ConnectionErrorTest, InvalidHost) {
  1923. auto host = "-abcde.com";
  1924. #ifdef CPPHTTPLIB_SSL_ENABLED
  1925. auto port = 443;
  1926. SSLClient cli(host, port);
  1927. #else
  1928. auto port = 80;
  1929. Client cli(host, port);
  1930. #endif
  1931. cli.set_connection_timeout(std::chrono::seconds(2));
  1932. auto res = cli.Get("/");
  1933. ASSERT_TRUE(!res);
  1934. EXPECT_EQ(Error::Connection, res.error());
  1935. }
  1936. TEST(ConnectionErrorTest, InvalidHost2) {
  1937. auto host = "httpcan.org/";
  1938. #ifdef CPPHTTPLIB_SSL_ENABLED
  1939. SSLClient cli(host);
  1940. #else
  1941. Client cli(host);
  1942. #endif
  1943. cli.set_connection_timeout(std::chrono::seconds(2));
  1944. auto res = cli.Get("/");
  1945. ASSERT_TRUE(!res);
  1946. EXPECT_EQ(Error::Connection, res.error());
  1947. }
  1948. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1949. auto host = "httpcan.org/";
  1950. #ifdef CPPHTTPLIB_SSL_ENABLED
  1951. SSLClient cli(host);
  1952. #else
  1953. Client cli(host);
  1954. #endif
  1955. cli.set_connection_timeout(std::chrono::seconds(2));
  1956. auto res = cli.Get("/");
  1957. ASSERT_TRUE(!res);
  1958. stringstream s;
  1959. s << "error code: " << res.error();
  1960. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1961. }
  1962. TEST(ConnectionErrorTest, InvalidPort) {
  1963. auto host = "localhost";
  1964. auto port = 44380;
  1965. #ifdef CPPHTTPLIB_SSL_ENABLED
  1966. SSLClient cli(host, port);
  1967. #else
  1968. Client cli(host, port);
  1969. #endif
  1970. cli.set_connection_timeout(std::chrono::seconds(2));
  1971. auto res = cli.Get("/");
  1972. ASSERT_TRUE(!res);
  1973. EXPECT_TRUE(Error::Connection == res.error() ||
  1974. Error::ConnectionTimeout == res.error());
  1975. }
  1976. TEST(ConnectionErrorTest, Timeout_Online) {
  1977. auto host = "google.com";
  1978. #ifdef CPPHTTPLIB_SSL_ENABLED
  1979. auto port = 44380;
  1980. SSLClient cli(host, port);
  1981. #else
  1982. auto port = 8080;
  1983. Client cli(host, port);
  1984. #endif
  1985. cli.set_connection_timeout(std::chrono::seconds(2));
  1986. // only probe one address type so that the error reason
  1987. // correlates to the timed-out IPv4, not the unsupported
  1988. // IPv6 connection attempt
  1989. cli.set_address_family(AF_INET);
  1990. auto res = cli.Get("/");
  1991. ASSERT_TRUE(!res);
  1992. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1993. }
  1994. TEST(CancelTest, NoCancel_Online) {
  1995. auto host = "httpbingo.org";
  1996. auto path = std::string{"/range/32"};
  1997. #ifdef CPPHTTPLIB_SSL_ENABLED
  1998. auto port = 443;
  1999. SSLClient cli(host, port);
  2000. #else
  2001. auto port = 80;
  2002. Client cli(host, port);
  2003. #endif
  2004. cli.set_connection_timeout(std::chrono::seconds(5));
  2005. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2006. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2007. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2008. EXPECT_EQ(StatusCode::OK_200, res->status);
  2009. }
  2010. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2011. // Use /bytes with a large payload so that the DownloadProgress callback
  2012. // (which only fires for Content-Length responses) is invoked before the
  2013. // entire body is received, giving cancellation a chance to fire.
  2014. auto host = "httpbingo.org";
  2015. auto path = std::string{"/bytes/524288"};
  2016. #ifdef CPPHTTPLIB_SSL_ENABLED
  2017. auto port = 443;
  2018. SSLClient cli(host, port);
  2019. #else
  2020. auto port = 80;
  2021. Client cli(host, port);
  2022. #endif
  2023. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2024. cli.set_connection_timeout(std::chrono::seconds(5));
  2025. ASSERT_TRUE(!res);
  2026. EXPECT_EQ(Error::Canceled, res.error());
  2027. }
  2028. TEST(CancelTest, WithCancelLargePayload_Online) {
  2029. auto host = "httpbingo.org";
  2030. auto path = std::string{"/bytes/524288"};
  2031. #ifdef CPPHTTPLIB_SSL_ENABLED
  2032. auto port = 443;
  2033. SSLClient cli(host, port);
  2034. #else
  2035. auto port = 80;
  2036. Client cli(host, port);
  2037. #endif
  2038. cli.set_connection_timeout(std::chrono::seconds(5));
  2039. uint32_t count = 0;
  2040. auto res =
  2041. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2042. ASSERT_TRUE(!res);
  2043. EXPECT_EQ(Error::Canceled, res.error());
  2044. }
  2045. TEST(CancelTest, NoCancelPost) {
  2046. Server svr;
  2047. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2048. res.set_content("Hello World!", "text/plain");
  2049. });
  2050. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2051. auto se = detail::scope_exit([&] {
  2052. svr.stop();
  2053. thread.join();
  2054. ASSERT_FALSE(svr.is_running());
  2055. });
  2056. svr.wait_until_ready();
  2057. Client cli(HOST, PORT);
  2058. cli.set_connection_timeout(std::chrono::seconds(5));
  2059. auto res =
  2060. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2061. "application/json", [](uint64_t, uint64_t) { return true; });
  2062. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2063. EXPECT_EQ("Hello World!", res->body);
  2064. EXPECT_EQ(StatusCode::OK_200, res->status);
  2065. }
  2066. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2067. Server svr;
  2068. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2069. res.set_content("Hello World!", "text/plain");
  2070. });
  2071. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2072. auto se = detail::scope_exit([&] {
  2073. svr.stop();
  2074. thread.join();
  2075. ASSERT_FALSE(svr.is_running());
  2076. });
  2077. svr.wait_until_ready();
  2078. Client cli(HOST, PORT);
  2079. cli.set_connection_timeout(std::chrono::seconds(5));
  2080. auto res =
  2081. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2082. "application/json", [](uint64_t, uint64_t) { return false; });
  2083. ASSERT_TRUE(!res);
  2084. EXPECT_EQ(Error::Canceled, res.error());
  2085. }
  2086. TEST(CancelTest, WithCancelLargePayloadPost) {
  2087. Server svr;
  2088. svr.set_payload_max_length(200 * 1024 * 1024);
  2089. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2090. res.set_content(LARGE_DATA, "text/plain");
  2091. });
  2092. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2093. auto se = detail::scope_exit([&] {
  2094. svr.stop();
  2095. thread.join();
  2096. ASSERT_FALSE(svr.is_running());
  2097. });
  2098. svr.wait_until_ready();
  2099. Client cli(HOST, PORT);
  2100. cli.set_payload_max_length(200 * 1024 * 1024);
  2101. cli.set_connection_timeout(std::chrono::seconds(5));
  2102. auto res =
  2103. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2104. "application/json", [](uint64_t, uint64_t) { return false; });
  2105. ASSERT_TRUE(!res);
  2106. EXPECT_EQ(Error::Canceled, res.error());
  2107. }
  2108. TEST(CancelTest, NoCancelPut) {
  2109. Server svr;
  2110. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2111. res.set_content("Hello World!", "text/plain");
  2112. });
  2113. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2114. auto se = detail::scope_exit([&] {
  2115. svr.stop();
  2116. thread.join();
  2117. ASSERT_FALSE(svr.is_running());
  2118. });
  2119. svr.wait_until_ready();
  2120. Client cli(HOST, PORT);
  2121. cli.set_connection_timeout(std::chrono::seconds(5));
  2122. auto res =
  2123. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2124. "application/json", [](uint64_t, uint64_t) { return true; });
  2125. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2126. EXPECT_EQ("Hello World!", res->body);
  2127. EXPECT_EQ(StatusCode::OK_200, res->status);
  2128. }
  2129. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2130. Server svr;
  2131. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2132. res.set_content("Hello World!", "text/plain");
  2133. });
  2134. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2135. auto se = detail::scope_exit([&] {
  2136. svr.stop();
  2137. thread.join();
  2138. ASSERT_FALSE(svr.is_running());
  2139. });
  2140. svr.wait_until_ready();
  2141. Client cli(HOST, PORT);
  2142. cli.set_connection_timeout(std::chrono::seconds(5));
  2143. auto res =
  2144. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2145. "application/json", [](uint64_t, uint64_t) { return false; });
  2146. ASSERT_TRUE(!res);
  2147. EXPECT_EQ(Error::Canceled, res.error());
  2148. }
  2149. TEST(CancelTest, WithCancelLargePayloadPut) {
  2150. Server svr;
  2151. svr.set_payload_max_length(200 * 1024 * 1024);
  2152. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2153. res.set_content(LARGE_DATA, "text/plain");
  2154. });
  2155. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2156. auto se = detail::scope_exit([&] {
  2157. svr.stop();
  2158. thread.join();
  2159. ASSERT_FALSE(svr.is_running());
  2160. });
  2161. svr.wait_until_ready();
  2162. Client cli(HOST, PORT);
  2163. cli.set_payload_max_length(200 * 1024 * 1024);
  2164. cli.set_connection_timeout(std::chrono::seconds(5));
  2165. auto res =
  2166. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2167. "application/json", [](uint64_t, uint64_t) { return false; });
  2168. ASSERT_TRUE(!res);
  2169. EXPECT_EQ(Error::Canceled, res.error());
  2170. }
  2171. TEST(CancelTest, NoCancelPatch) {
  2172. Server svr;
  2173. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2174. res.set_content("Hello World!", "text/plain");
  2175. });
  2176. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2177. auto se = detail::scope_exit([&] {
  2178. svr.stop();
  2179. thread.join();
  2180. ASSERT_FALSE(svr.is_running());
  2181. });
  2182. svr.wait_until_ready();
  2183. Client cli(HOST, PORT);
  2184. cli.set_connection_timeout(std::chrono::seconds(5));
  2185. auto res =
  2186. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2187. "application/json", [](uint64_t, uint64_t) { return true; });
  2188. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2189. EXPECT_EQ("Hello World!", res->body);
  2190. EXPECT_EQ(StatusCode::OK_200, res->status);
  2191. }
  2192. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2193. Server svr;
  2194. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2195. res.set_content("Hello World!", "text/plain");
  2196. });
  2197. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2198. auto se = detail::scope_exit([&] {
  2199. svr.stop();
  2200. thread.join();
  2201. ASSERT_FALSE(svr.is_running());
  2202. });
  2203. svr.wait_until_ready();
  2204. Client cli(HOST, PORT);
  2205. cli.set_connection_timeout(std::chrono::seconds(5));
  2206. auto res =
  2207. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2208. "application/json", [](uint64_t, uint64_t) { return false; });
  2209. ASSERT_TRUE(!res);
  2210. EXPECT_EQ(Error::Canceled, res.error());
  2211. }
  2212. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2213. Server svr;
  2214. svr.set_payload_max_length(200 * 1024 * 1024);
  2215. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2216. res.set_content(LARGE_DATA, "text/plain");
  2217. });
  2218. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2219. auto se = detail::scope_exit([&] {
  2220. svr.stop();
  2221. thread.join();
  2222. ASSERT_FALSE(svr.is_running());
  2223. });
  2224. svr.wait_until_ready();
  2225. Client cli(HOST, PORT);
  2226. cli.set_payload_max_length(200 * 1024 * 1024);
  2227. cli.set_connection_timeout(std::chrono::seconds(5));
  2228. auto res =
  2229. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2230. "application/json", [](uint64_t, uint64_t) { return false; });
  2231. ASSERT_TRUE(!res);
  2232. EXPECT_EQ(Error::Canceled, res.error());
  2233. }
  2234. TEST(CancelTest, NoCancelDelete) {
  2235. Server svr;
  2236. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2237. res.set_content("Hello World!", "text/plain");
  2238. });
  2239. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2240. auto se = detail::scope_exit([&] {
  2241. svr.stop();
  2242. thread.join();
  2243. ASSERT_FALSE(svr.is_running());
  2244. });
  2245. svr.wait_until_ready();
  2246. Client cli(HOST, PORT);
  2247. cli.set_connection_timeout(std::chrono::seconds(5));
  2248. auto res =
  2249. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2250. "application/json", [](uint64_t, uint64_t) { return true; });
  2251. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2252. EXPECT_EQ("Hello World!", res->body);
  2253. EXPECT_EQ(StatusCode::OK_200, res->status);
  2254. }
  2255. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2256. Server svr;
  2257. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2258. res.set_content("Hello World!", "text/plain");
  2259. });
  2260. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2261. auto se = detail::scope_exit([&] {
  2262. svr.stop();
  2263. thread.join();
  2264. ASSERT_FALSE(svr.is_running());
  2265. });
  2266. svr.wait_until_ready();
  2267. Client cli(HOST, PORT);
  2268. cli.set_connection_timeout(std::chrono::seconds(5));
  2269. auto res =
  2270. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2271. "application/json", [](uint64_t, uint64_t) { return false; });
  2272. ASSERT_TRUE(!res);
  2273. EXPECT_EQ(Error::Canceled, res.error());
  2274. }
  2275. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2276. Server svr;
  2277. svr.set_payload_max_length(200 * 1024 * 1024);
  2278. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2279. res.set_content(LARGE_DATA, "text/plain");
  2280. });
  2281. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2282. auto se = detail::scope_exit([&] {
  2283. svr.stop();
  2284. thread.join();
  2285. ASSERT_FALSE(svr.is_running());
  2286. });
  2287. svr.wait_until_ready();
  2288. Client cli(HOST, PORT);
  2289. cli.set_payload_max_length(200 * 1024 * 1024);
  2290. cli.set_connection_timeout(std::chrono::seconds(5));
  2291. auto res =
  2292. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2293. "application/json", [](uint64_t, uint64_t) { return false; });
  2294. ASSERT_TRUE(!res);
  2295. EXPECT_EQ(Error::Canceled, res.error());
  2296. }
  2297. static std::string remove_whitespace(const std::string &input) {
  2298. std::string output;
  2299. output.reserve(input.size());
  2300. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2301. [](unsigned char c) { return !std::isspace(c); });
  2302. return output;
  2303. }
  2304. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2305. auto host = "httpbingo.org";
  2306. auto path = std::string{"/basic-auth/hello/world"};
  2307. #ifdef CPPHTTPLIB_SSL_ENABLED
  2308. auto port = 443;
  2309. SSLClient cli(host, port);
  2310. #else
  2311. auto port = 80;
  2312. Client cli(host, port);
  2313. #endif
  2314. {
  2315. auto res = cli.Get(path);
  2316. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2317. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2318. }
  2319. {
  2320. auto res = cli.Get(
  2321. path, Headers{make_basic_authentication_header("hello", "world")});
  2322. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2323. auto body = remove_whitespace(res->body);
  2324. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2325. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2326. EXPECT_EQ(StatusCode::OK_200, res->status);
  2327. }
  2328. {
  2329. cli.set_basic_auth("hello", "world");
  2330. auto res = cli.Get(path);
  2331. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2332. auto body = remove_whitespace(res->body);
  2333. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2334. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2335. EXPECT_EQ(StatusCode::OK_200, res->status);
  2336. }
  2337. {
  2338. cli.set_basic_auth("hello", "bad");
  2339. auto res = cli.Get(path);
  2340. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2341. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2342. }
  2343. {
  2344. cli.set_basic_auth("bad", "world");
  2345. auto res = cli.Get(path);
  2346. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2347. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2348. }
  2349. }
  2350. #ifdef CPPHTTPLIB_SSL_ENABLED
  2351. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2352. auto host = "httpbingo.org";
  2353. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2354. auto paths = std::vector<std::string>{
  2355. "/digest-auth/auth/hello/world/MD5",
  2356. "/digest-auth/auth/hello/world/SHA-256",
  2357. };
  2358. auto port = 443;
  2359. SSLClient cli(host, port);
  2360. {
  2361. auto res = cli.Get(unauth_path);
  2362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2363. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2364. }
  2365. {
  2366. cli.set_digest_auth("hello", "world");
  2367. for (const auto &path : paths) {
  2368. auto res = cli.Get(path.c_str());
  2369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2370. auto body = remove_whitespace(res->body);
  2371. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2372. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2373. EXPECT_EQ(StatusCode::OK_200, res->status);
  2374. }
  2375. cli.set_digest_auth("hello", "bad");
  2376. for (const auto &path : paths) {
  2377. auto res = cli.Get(path.c_str());
  2378. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2379. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2380. }
  2381. }
  2382. }
  2383. #endif
  2384. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  2385. auto host = "google.com";
  2386. auto another_host = "example.com";
  2387. auto wrong_ip = "0.0.0.0";
  2388. #ifdef CPPHTTPLIB_SSL_ENABLED
  2389. SSLClient cli(host);
  2390. #else
  2391. Client cli(host);
  2392. #endif
  2393. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  2394. auto res = cli.Get("/");
  2395. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2396. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  2397. }
  2398. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  2399. auto host = "google.com";
  2400. auto wrong_ip = "0.0.0.0";
  2401. #ifdef CPPHTTPLIB_SSL_ENABLED
  2402. SSLClient cli(host);
  2403. #else
  2404. Client cli(host);
  2405. #endif
  2406. cli.set_hostname_addr_map({{host, wrong_ip}});
  2407. auto res = cli.Get("/");
  2408. ASSERT_TRUE(!res);
  2409. EXPECT_EQ(Error::Connection, res.error());
  2410. }
  2411. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  2412. // A mapped value that is not an IP literal must be resolved. "localhost"
  2413. // resolves from the hosts file, so this test needs no external DNS.
  2414. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  2415. auto host = "target.invalid";
  2416. Server svr;
  2417. std::string received_host;
  2418. svr.Get("/hi", [&](const Request &req, Response &res) {
  2419. received_host = req.get_header_value("Host");
  2420. res.set_content("Hello World!", "text/plain");
  2421. });
  2422. auto port = svr.bind_to_any_port(HOST);
  2423. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2424. auto se = detail::scope_exit([&] {
  2425. svr.stop();
  2426. thread.join();
  2427. ASSERT_FALSE(svr.is_running());
  2428. });
  2429. svr.wait_until_ready();
  2430. Client cli(host, port);
  2431. cli.set_hostname_addr_map({{host, HOST}});
  2432. auto res = cli.Get("/hi");
  2433. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2434. EXPECT_EQ(StatusCode::OK_200, res->status);
  2435. // The mapping only redirects the connection; the identity stays host_.
  2436. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  2437. }
  2438. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  2439. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  2440. auto host = "target.invalid";
  2441. Server svr;
  2442. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2443. res.set_content("Hello World!", "text/plain");
  2444. });
  2445. auto port = svr.bind_to_any_port("127.0.0.1");
  2446. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2447. auto se = detail::scope_exit([&] {
  2448. svr.stop();
  2449. thread.join();
  2450. ASSERT_FALSE(svr.is_running());
  2451. });
  2452. svr.wait_until_ready();
  2453. Client cli(host, port);
  2454. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  2455. auto res = cli.Get("/hi");
  2456. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2457. EXPECT_EQ(StatusCode::OK_200, res->status);
  2458. }
  2459. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  2460. // An empty mapped value must leave host_ as the connection target. Without
  2461. // that guard the empty value would become the host argument, getaddrinfo
  2462. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  2463. // loopback - silently connecting somewhere the caller never asked for.
  2464. // The server listens on loopback, so such a fallback would succeed and is
  2465. // therefore observable as a failure of this test.
  2466. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  2467. Server svr;
  2468. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2469. res.set_content("Hello World!", "text/plain");
  2470. });
  2471. auto port = svr.bind_to_any_port(HOST);
  2472. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2473. auto se = detail::scope_exit([&] {
  2474. svr.stop();
  2475. thread.join();
  2476. ASSERT_FALSE(svr.is_running());
  2477. });
  2478. svr.wait_until_ready();
  2479. Client cli(blackhole, port);
  2480. cli.set_hostname_addr_map({{blackhole, ""}});
  2481. cli.set_connection_timeout(1);
  2482. auto res = cli.Get("/hi");
  2483. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  2484. }
  2485. TEST(AbsoluteRedirectTest, Redirect_Online) {
  2486. auto host = "httpbingo.org";
  2487. auto path = std::string{"/absolute-redirect/3"};
  2488. #ifdef CPPHTTPLIB_SSL_ENABLED
  2489. SSLClient cli(host);
  2490. #else
  2491. Client cli(host);
  2492. #endif
  2493. cli.set_follow_location(true);
  2494. auto res = cli.Get(path);
  2495. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2496. EXPECT_EQ(StatusCode::OK_200, res->status);
  2497. }
  2498. TEST(RedirectTest, Redirect_Online) {
  2499. auto host = "httpbingo.org";
  2500. auto path = std::string{"/redirect/3"};
  2501. #ifdef CPPHTTPLIB_SSL_ENABLED
  2502. SSLClient cli(host);
  2503. #else
  2504. Client cli(host);
  2505. #endif
  2506. cli.set_follow_location(true);
  2507. auto res = cli.Get(path);
  2508. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2509. EXPECT_EQ(StatusCode::OK_200, res->status);
  2510. }
  2511. TEST(RelativeRedirectTest, Redirect_Online) {
  2512. auto host = "httpbingo.org";
  2513. auto path = std::string{"/relative-redirect/3"};
  2514. #ifdef CPPHTTPLIB_SSL_ENABLED
  2515. SSLClient cli(host);
  2516. #else
  2517. Client cli(host);
  2518. #endif
  2519. cli.set_follow_location(true);
  2520. auto res = cli.Get(path);
  2521. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2522. EXPECT_EQ(StatusCode::OK_200, res->status);
  2523. }
  2524. TEST(TooManyRedirectTest, Redirect_Online) {
  2525. auto host = "httpbingo.org";
  2526. auto path = std::string{"/redirect/21"};
  2527. #ifdef CPPHTTPLIB_SSL_ENABLED
  2528. SSLClient cli(host);
  2529. #else
  2530. Client cli(host);
  2531. #endif
  2532. cli.set_follow_location(true);
  2533. auto res = cli.Get(path);
  2534. ASSERT_TRUE(!res);
  2535. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  2536. }
  2537. #ifdef CPPHTTPLIB_SSL_ENABLED
  2538. TEST(YahooRedirectTest, Redirect_Online) {
  2539. Client cli("yahoo.com");
  2540. auto res = cli.Get("/");
  2541. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2542. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  2543. cli.set_follow_location(true);
  2544. res = cli.Get("/");
  2545. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2546. EXPECT_EQ(StatusCode::OK_200, res->status);
  2547. EXPECT_EQ("https://www.yahoo.com/", res->location);
  2548. }
  2549. // Previously "nghttp2.org" "/httpbin/redirect-to"
  2550. #define REDIR_HOST "httpbingo.org"
  2551. #define REDIR_PATH "/redirect-to"
  2552. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  2553. SSLClient cli(REDIR_HOST);
  2554. cli.set_follow_location(true);
  2555. auto res =
  2556. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  2557. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2558. EXPECT_EQ(StatusCode::OK_200, res->status);
  2559. }
  2560. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  2561. SSLClient cli(REDIR_HOST);
  2562. cli.set_follow_location(true);
  2563. Params params;
  2564. params.emplace("url", "http://example.com");
  2565. params.emplace("status_code", "302");
  2566. auto res = cli.Get(REDIR_PATH, params, Headers{});
  2567. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2568. EXPECT_EQ(StatusCode::OK_200, res->status);
  2569. }
  2570. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  2571. SSLClient cli(REDIR_HOST);
  2572. cli.set_follow_location(true);
  2573. Params params;
  2574. params.emplace("url", "http://example.com");
  2575. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  2576. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2577. EXPECT_EQ(StatusCode::OK_200, res->status);
  2578. }
  2579. TEST(UrlWithSpace, Redirect_Online) {
  2580. SSLClient cli("edge.forgecdn.net");
  2581. cli.set_follow_location(true);
  2582. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  2583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2584. EXPECT_EQ(StatusCode::OK_200, res->status);
  2585. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  2586. }
  2587. #endif
  2588. #if !defined(_WIN32) && !defined(_WIN64)
  2589. TEST(ReceiveSignals, Signal) {
  2590. auto setupSignalHandlers = []() {
  2591. struct sigaction act;
  2592. sigemptyset(&act.sa_mask);
  2593. act.sa_flags = SA_SIGINFO;
  2594. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  2595. switch (sig) {
  2596. case SIGINT:
  2597. default: break;
  2598. }
  2599. };
  2600. ::sigaction(SIGINT, &act, nullptr);
  2601. };
  2602. Server svr;
  2603. int port = 0;
  2604. auto thread = std::thread([&]() {
  2605. setupSignalHandlers();
  2606. port = svr.bind_to_any_port(HOST);
  2607. svr.listen_after_bind();
  2608. });
  2609. auto se = detail::scope_exit([&] {
  2610. svr.stop();
  2611. thread.join();
  2612. ASSERT_FALSE(svr.is_running());
  2613. });
  2614. svr.wait_until_ready();
  2615. ASSERT_TRUE(svr.is_running());
  2616. pthread_kill(thread.native_handle(), SIGINT);
  2617. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  2618. ASSERT_TRUE(svr.is_running());
  2619. }
  2620. #endif
  2621. TEST(RedirectToDifferentPort, Redirect) {
  2622. Server svr1;
  2623. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  2624. res.set_content("Hello World!", "text/plain");
  2625. });
  2626. int svr1_port = 0;
  2627. auto thread1 = std::thread([&]() {
  2628. svr1_port = svr1.bind_to_any_port(HOST);
  2629. svr1.listen_after_bind();
  2630. });
  2631. Server svr2;
  2632. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  2633. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  2634. });
  2635. int svr2_port = 0;
  2636. auto thread2 = std::thread([&]() {
  2637. svr2_port = svr2.bind_to_any_port(HOST);
  2638. svr2.listen_after_bind();
  2639. });
  2640. auto se = detail::scope_exit([&] {
  2641. svr2.stop();
  2642. thread2.join();
  2643. svr1.stop();
  2644. thread1.join();
  2645. ASSERT_FALSE(svr2.is_running());
  2646. ASSERT_FALSE(svr1.is_running());
  2647. });
  2648. svr1.wait_until_ready();
  2649. svr2.wait_until_ready();
  2650. Client cli("localhost", svr2_port);
  2651. cli.set_follow_location(true);
  2652. auto res = cli.Get("/2");
  2653. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2654. EXPECT_EQ(StatusCode::OK_200, res->status);
  2655. EXPECT_EQ("Hello World!", res->body);
  2656. }
  2657. static void
  2658. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  2659. Server svr1;
  2660. std::string captured_authorization;
  2661. svr1.Get("/target", [&](const Request &req, Response &res) {
  2662. captured_authorization = req.get_header_value("Authorization");
  2663. res.set_content("OK", "text/plain");
  2664. });
  2665. int svr1_port = 0;
  2666. auto thread1 = std::thread([&]() {
  2667. svr1_port = svr1.bind_to_any_port(HOST);
  2668. svr1.listen_after_bind();
  2669. });
  2670. Server svr2;
  2671. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2672. res.set_redirect(
  2673. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  2674. });
  2675. int svr2_port = 0;
  2676. auto thread2 = std::thread([&]() {
  2677. svr2_port = svr2.bind_to_any_port(HOST);
  2678. svr2.listen_after_bind();
  2679. });
  2680. auto se = detail::scope_exit([&] {
  2681. svr2.stop();
  2682. thread2.join();
  2683. svr1.stop();
  2684. thread1.join();
  2685. ASSERT_FALSE(svr2.is_running());
  2686. ASSERT_FALSE(svr1.is_running());
  2687. });
  2688. svr1.wait_until_ready();
  2689. svr2.wait_until_ready();
  2690. Client cli("localhost", svr2_port);
  2691. cli.set_follow_location(true);
  2692. set_auth(cli);
  2693. auto res = cli.Get("/redir");
  2694. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2695. EXPECT_EQ(StatusCode::OK_200, res->status);
  2696. // RFC 9110: credentials MUST NOT be forwarded to a different host
  2697. EXPECT_TRUE(captured_authorization.empty());
  2698. }
  2699. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  2700. TestDoNotForwardCredentialsOnRedirect(
  2701. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  2702. }
  2703. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  2704. TestDoNotForwardCredentialsOnRedirect(
  2705. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  2706. }
  2707. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  2708. Server svr1;
  2709. std::string captured_cookie;
  2710. bool target_hit = false;
  2711. svr1.Get("/target", [&](const Request &req, Response &res) {
  2712. captured_cookie = req.get_header_value("Cookie");
  2713. target_hit = true;
  2714. res.set_content("OK", "text/plain");
  2715. });
  2716. int svr1_port = 0;
  2717. auto thread1 = std::thread([&]() {
  2718. svr1_port = svr1.bind_to_any_port(HOST);
  2719. svr1.listen_after_bind();
  2720. });
  2721. Server svr2;
  2722. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2723. res.set_redirect(
  2724. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  2725. });
  2726. int svr2_port = 0;
  2727. auto thread2 = std::thread([&]() {
  2728. svr2_port = svr2.bind_to_any_port(HOST);
  2729. svr2.listen_after_bind();
  2730. });
  2731. auto se = detail::scope_exit([&] {
  2732. svr2.stop();
  2733. thread2.join();
  2734. svr1.stop();
  2735. thread1.join();
  2736. ASSERT_FALSE(svr2.is_running());
  2737. ASSERT_FALSE(svr1.is_running());
  2738. });
  2739. svr1.wait_until_ready();
  2740. svr2.wait_until_ready();
  2741. Client cli("localhost", svr2_port);
  2742. cli.set_follow_location(true);
  2743. Headers headers = {{"Cookie", "session_id=SECRET; auth=PRIVATE"}};
  2744. auto res = cli.Get("/redir", headers);
  2745. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2746. EXPECT_EQ(StatusCode::OK_200, res->status);
  2747. EXPECT_TRUE(target_hit);
  2748. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  2749. EXPECT_TRUE(captured_cookie.empty());
  2750. }
  2751. TEST(RedirectToSamePort, ForwardCookie) {
  2752. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  2753. // header so that ordinary session flows keep working.
  2754. Server svr;
  2755. std::string captured_cookie;
  2756. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2757. res.set_redirect("/target", 302);
  2758. });
  2759. svr.Get("/target", [&](const Request &req, Response &res) {
  2760. captured_cookie = req.get_header_value("Cookie");
  2761. res.set_content("OK", "text/plain");
  2762. });
  2763. auto port = svr.bind_to_any_port(HOST);
  2764. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2765. auto se = detail::scope_exit([&] {
  2766. svr.stop();
  2767. thread.join();
  2768. ASSERT_FALSE(svr.is_running());
  2769. });
  2770. svr.wait_until_ready();
  2771. Client cli(HOST, port);
  2772. cli.set_follow_location(true);
  2773. Headers headers = {{"Cookie", "session_id=SECRET"}};
  2774. auto res = cli.Get("/redir", headers);
  2775. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2776. EXPECT_EQ(StatusCode::OK_200, res->status);
  2777. EXPECT_EQ("session_id=SECRET", captured_cookie);
  2778. }
  2779. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  2780. Server svr;
  2781. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2782. // Port number that overflows int — should not crash
  2783. res.set_redirect("http://localhost:99999999999999999999/target");
  2784. });
  2785. auto port = svr.bind_to_any_port(HOST);
  2786. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  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. Client cli(HOST, port);
  2794. cli.set_follow_location(true);
  2795. auto res = cli.Get("/redir");
  2796. // Should fail gracefully, not crash (no valid response due to bad port)
  2797. EXPECT_FALSE(res);
  2798. }
  2799. TEST(RedirectFromPageWithContent, Redirect) {
  2800. Server svr;
  2801. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2802. res.set_content("___", "text/plain");
  2803. res.set_redirect("/2");
  2804. });
  2805. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  2806. res.set_content("Hello World!", "text/plain");
  2807. });
  2808. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  2809. auto se = detail::scope_exit([&] {
  2810. svr.stop();
  2811. th.join();
  2812. ASSERT_FALSE(svr.is_running());
  2813. });
  2814. svr.wait_until_ready();
  2815. {
  2816. Client cli("localhost", PORT);
  2817. cli.set_follow_location(true);
  2818. std::string body;
  2819. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2820. body.append(data, data_length);
  2821. return true;
  2822. });
  2823. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2824. EXPECT_EQ(StatusCode::OK_200, res->status);
  2825. EXPECT_EQ("Hello World!", body);
  2826. }
  2827. {
  2828. Client cli("localhost", PORT);
  2829. std::string body;
  2830. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2831. body.append(data, data_length);
  2832. return true;
  2833. });
  2834. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2835. EXPECT_EQ(StatusCode::Found_302, res->status);
  2836. EXPECT_EQ("___", body);
  2837. }
  2838. }
  2839. TEST(RedirectFromPageWithContentIP6, Redirect) {
  2840. Server svr;
  2841. auto port_str = std::to_string(PORT);
  2842. auto redirect_url = "http://[::1]:" + port_str + "/2";
  2843. auto expected_host = "[::1]:" + port_str;
  2844. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2845. res.set_content("___", "text/plain");
  2846. // res.set_redirect("/2");
  2847. res.set_redirect(redirect_url);
  2848. });
  2849. svr.Get("/2", [&](const Request &req, Response &res) {
  2850. auto host_header = req.headers.find("Host");
  2851. ASSERT_TRUE(host_header != req.headers.end());
  2852. EXPECT_EQ(expected_host, host_header->second);
  2853. res.set_content("Hello World!", "text/plain");
  2854. });
  2855. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  2856. auto se = detail::scope_exit([&] {
  2857. svr.stop();
  2858. th.join();
  2859. ASSERT_FALSE(svr.is_running());
  2860. });
  2861. // When IPV6 support isn't available svr.listen("::1", PORT) never
  2862. // actually starts anything, so the condition !svr.is_running() will
  2863. // always remain true, and the loop never stops.
  2864. // This basically counts how many milliseconds have passed since the
  2865. // call to svr.listen(), and if after 5 seconds nothing started yet
  2866. // aborts the test.
  2867. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  2868. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2869. ASSERT_LT(milliseconds, 5000U);
  2870. }
  2871. {
  2872. Client cli("::1", PORT);
  2873. cli.set_follow_location(true);
  2874. std::string body;
  2875. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2876. body.append(data, data_length);
  2877. return true;
  2878. });
  2879. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2880. EXPECT_EQ(StatusCode::OK_200, res->status);
  2881. EXPECT_EQ("Hello World!", body);
  2882. }
  2883. {
  2884. Client cli("::1", PORT);
  2885. std::string body;
  2886. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2887. body.append(data, data_length);
  2888. return true;
  2889. });
  2890. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2891. EXPECT_EQ(StatusCode::Found_302, res->status);
  2892. EXPECT_EQ("___", body);
  2893. }
  2894. }
  2895. TEST(PathUrlEncodeTest, PathUrlEncode) {
  2896. Server svr;
  2897. svr.Get("/foo", [](const Request &req, Response &res) {
  2898. auto a = req.params.find("a");
  2899. if (a != req.params.end()) {
  2900. res.set_content((*a).second, "text/plain");
  2901. res.status = StatusCode::OK_200;
  2902. } else {
  2903. res.status = StatusCode::BadRequest_400;
  2904. }
  2905. });
  2906. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2907. auto se = detail::scope_exit([&] {
  2908. svr.stop();
  2909. thread.join();
  2910. ASSERT_FALSE(svr.is_running());
  2911. });
  2912. svr.wait_until_ready();
  2913. {
  2914. Client cli(HOST, PORT);
  2915. cli.set_path_encode(false);
  2916. auto res = cli.Get("/foo?a=explicitly+encoded");
  2917. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2918. EXPECT_EQ(StatusCode::OK_200, res->status);
  2919. // This expects it back with a space, as the `+` won't have been
  2920. // url-encoded, and server-side the params get decoded turning `+`
  2921. // into spaces.
  2922. EXPECT_EQ("explicitly encoded", res->body);
  2923. }
  2924. }
  2925. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  2926. // When path encoding is disabled the client must transmit the supplied
  2927. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  2928. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  2929. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  2930. // than a space (0x20). Assert on the raw wire target to catch this.
  2931. Server svr;
  2932. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  2933. svr.Get("/foo", [&](const Request &req, Response &res) {
  2934. EXPECT_EQ(expected_target, req.target);
  2935. res.status = StatusCode::OK_200;
  2936. });
  2937. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2938. auto se = detail::scope_exit([&] {
  2939. svr.stop();
  2940. thread.join();
  2941. ASSERT_FALSE(svr.is_running());
  2942. });
  2943. svr.wait_until_ready();
  2944. {
  2945. Client cli(HOST, PORT);
  2946. cli.set_path_encode(false);
  2947. auto res = cli.Get(expected_target.c_str());
  2948. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2949. EXPECT_EQ(StatusCode::OK_200, res->status);
  2950. }
  2951. }
  2952. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  2953. // `open_stream()` used to skip the path encoding that the buffered send
  2954. // path applies, so the same `path` produced different bytes in the request
  2955. // line depending on which API was used. Assert the two agree.
  2956. Server svr;
  2957. std::string target;
  2958. svr.Get(".*", [&](const Request &req, Response &res) {
  2959. target = req.target;
  2960. res.status = StatusCode::OK_200;
  2961. });
  2962. auto port = svr.bind_to_any_port(HOST);
  2963. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2964. auto se = detail::scope_exit([&] {
  2965. svr.stop();
  2966. thread.join();
  2967. ASSERT_FALSE(svr.is_running());
  2968. });
  2969. svr.wait_until_ready();
  2970. struct {
  2971. const char *path;
  2972. const char *expected;
  2973. } cases[] = {
  2974. {"/a b?x=1", "/a%20b?x=1"},
  2975. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  2976. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  2977. };
  2978. for (const auto &c : cases) {
  2979. Client cli(HOST, port);
  2980. target.clear();
  2981. auto res = cli.Get(c.path);
  2982. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2983. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  2984. auto buffered_target = target;
  2985. target.clear();
  2986. auto handle = cli.open_stream("GET", c.path);
  2987. EXPECT_TRUE(handle.is_valid())
  2988. << "streaming path: " << c.path << ", " << to_string(handle.error);
  2989. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  2990. }
  2991. }
  2992. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  2993. // The `set_path_encode(false)` contract — transmit the supplied target
  2994. // verbatim — must hold for the streaming API too.
  2995. Server svr;
  2996. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  2997. std::string target;
  2998. svr.Get("/foo", [&](const Request &req, Response &res) {
  2999. target = req.target;
  3000. res.status = StatusCode::OK_200;
  3001. });
  3002. auto port = svr.bind_to_any_port(HOST);
  3003. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3004. auto se = detail::scope_exit([&] {
  3005. svr.stop();
  3006. thread.join();
  3007. ASSERT_FALSE(svr.is_running());
  3008. });
  3009. svr.wait_until_ready();
  3010. {
  3011. Client cli(HOST, port);
  3012. cli.set_path_encode(false);
  3013. auto handle = cli.open_stream("GET", expected_target);
  3014. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3015. EXPECT_EQ(expected_target, target);
  3016. }
  3017. }
  3018. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3019. // With path encoding enabled a CR/LF in the target is percent-encoded
  3020. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3021. // write_request_line still backstops `set_path_encode(false)`, which is
  3022. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3023. Server svr;
  3024. // Captured before routing: the decoded path contains a newline, which a
  3025. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3026. std::string target;
  3027. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3028. target = req.target;
  3029. res.status = StatusCode::OK_200;
  3030. return Server::HandlerResponse::Handled;
  3031. });
  3032. auto port = svr.bind_to_any_port(HOST);
  3033. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3034. auto se = detail::scope_exit([&] {
  3035. svr.stop();
  3036. thread.join();
  3037. ASSERT_FALSE(svr.is_running());
  3038. });
  3039. svr.wait_until_ready();
  3040. {
  3041. Client cli(HOST, port);
  3042. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3043. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3044. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3045. }
  3046. }
  3047. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3048. // Nothing may reach the wire: a raw CR/LF target would split the request
  3049. // line and inject headers.
  3050. Server svr;
  3051. // Pre-routing so that "not called" means nothing reached the server at all,
  3052. // rather than merely failing to match a handler pattern.
  3053. auto handler_called = false;
  3054. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3055. handler_called = true;
  3056. res.status = StatusCode::OK_200;
  3057. return Server::HandlerResponse::Handled;
  3058. });
  3059. auto port = svr.bind_to_any_port(HOST);
  3060. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3061. auto se = detail::scope_exit([&] {
  3062. svr.stop();
  3063. thread.join();
  3064. ASSERT_FALSE(svr.is_running());
  3065. });
  3066. svr.wait_until_ready();
  3067. {
  3068. Client cli(HOST, port);
  3069. cli.set_path_encode(false);
  3070. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3071. EXPECT_FALSE(handle.is_valid());
  3072. EXPECT_EQ(Error::Write, handle.error);
  3073. EXPECT_FALSE(handler_called);
  3074. }
  3075. }
  3076. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3077. // Which of the two branches runs is decided by whether the query component
  3078. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3079. // an empty query and must still fall back to building one from
  3080. // `req.params`, while a non-empty query must win over `req.params`.
  3081. Server svr;
  3082. std::string target;
  3083. svr.Get("/foo", [&](const Request &req, Response &res) {
  3084. target = req.target;
  3085. res.status = StatusCode::OK_200;
  3086. });
  3087. auto port = svr.bind_to_any_port(HOST);
  3088. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3089. auto se = detail::scope_exit([&] {
  3090. svr.stop();
  3091. thread.join();
  3092. ASSERT_FALSE(svr.is_running());
  3093. });
  3094. svr.wait_until_ready();
  3095. {
  3096. // Trailing `?` -> empty query component -> `req.params` is used.
  3097. Client cli(HOST, port);
  3098. Request req;
  3099. req.method = "GET";
  3100. req.path = "/foo?";
  3101. req.params.emplace("a", "1");
  3102. target.clear();
  3103. auto res = cli.send(req);
  3104. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3105. EXPECT_EQ("/foo?a=1", target);
  3106. }
  3107. {
  3108. // Non-empty query in `req.path` -> `req.params` is not appended.
  3109. Client cli(HOST, port);
  3110. Request req;
  3111. req.method = "GET";
  3112. req.path = "/foo?b=2";
  3113. req.params.emplace("a", "1");
  3114. target.clear();
  3115. auto res = cli.send(req);
  3116. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3117. EXPECT_EQ("/foo?b=2", target);
  3118. }
  3119. }
  3120. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3121. Server svr;
  3122. svr.Get("/", [](const Request &req, Response &) {
  3123. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3124. });
  3125. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3126. auto se = detail::scope_exit([&] {
  3127. svr.stop();
  3128. thread.join();
  3129. ASSERT_FALSE(svr.is_running());
  3130. });
  3131. svr.wait_until_ready();
  3132. {
  3133. Client cli(HOST, PORT);
  3134. cli.set_path_encode(false);
  3135. auto res = cli.Get("/?something=%0A");
  3136. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3137. EXPECT_EQ(StatusCode::OK_200, res->status);
  3138. }
  3139. }
  3140. TEST(BindServerTest, BindDualStack) {
  3141. Server svr;
  3142. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3143. res.set_content("Hello World!", "text/plain");
  3144. });
  3145. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3146. auto se = detail::scope_exit([&] {
  3147. svr.stop();
  3148. thread.join();
  3149. ASSERT_FALSE(svr.is_running());
  3150. });
  3151. svr.wait_until_ready();
  3152. {
  3153. Client cli("127.0.0.1", PORT);
  3154. auto res = cli.Get("/1");
  3155. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3156. EXPECT_EQ(StatusCode::OK_200, res->status);
  3157. EXPECT_EQ("Hello World!", res->body);
  3158. }
  3159. {
  3160. Client cli("::1", PORT);
  3161. auto res = cli.Get("/1");
  3162. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3163. EXPECT_EQ(StatusCode::OK_200, res->status);
  3164. EXPECT_EQ("Hello World!", res->body);
  3165. }
  3166. }
  3167. TEST(BindServerTest, BindAndListenSeparately) {
  3168. Server svr;
  3169. int port = svr.bind_to_any_port("0.0.0.0");
  3170. ASSERT_TRUE(svr.is_valid());
  3171. ASSERT_TRUE(port > 0);
  3172. svr.stop();
  3173. }
  3174. // Reports whether anything is still listening on a loopback port. A plain
  3175. // connect() is used instead of a Client request because a socket left bound by
  3176. // mistake accepts the connection into its backlog and never answers, which
  3177. // would hang the test instead of failing it.
  3178. static bool is_loopback_port_accepting(int port) {
  3179. sockaddr_in addr{};
  3180. addr.sin_family = AF_INET;
  3181. addr.sin_port = htons(static_cast<uint16_t>(port));
  3182. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3183. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3184. EXPECT_NE(sock, INVALID_SOCKET);
  3185. if (sock == INVALID_SOCKET) { return false; }
  3186. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3187. static_cast<socklen_t>(sizeof(addr)));
  3188. detail::close_socket(sock);
  3189. return ret == 0;
  3190. }
  3191. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3192. Server svr;
  3193. auto port = svr.bind_to_any_port("127.0.0.1");
  3194. ASSERT_TRUE(port > 0);
  3195. svr.stop();
  3196. // bind_to_any_port() already called listen(2), so until stop() closed the
  3197. // descriptor the port kept accepting connections into the backlog. ASSERT
  3198. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3199. // below blocks forever in the accept loop.
  3200. ASSERT_FALSE(is_loopback_port_accepting(port));
  3201. // Nothing is left to accept on, so listen_after_bind() must report failure
  3202. // instead of returning success without ever serving.
  3203. EXPECT_FALSE(svr.listen_after_bind());
  3204. // The failed listen marks the server decommissioned, so a waiter returns
  3205. // instead of spinning forever.
  3206. svr.wait_until_ready();
  3207. }
  3208. #ifdef CPPHTTPLIB_SSL_ENABLED
  3209. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3210. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3211. CLIENT_CA_CERT_DIR);
  3212. int port = svr.bind_to_any_port("0.0.0.0");
  3213. ASSERT_TRUE(svr.is_valid());
  3214. ASSERT_TRUE(port > 0);
  3215. svr.stop();
  3216. }
  3217. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  3218. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  3219. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  3220. int port = svr.bind_to_any_port("0.0.0.0");
  3221. ASSERT_TRUE(svr.is_valid());
  3222. ASSERT_TRUE(port > 0);
  3223. svr.stop();
  3224. }
  3225. TEST(BindServerTest, UpdateCertsPem) {
  3226. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3227. int port = svr.bind_to_any_port("0.0.0.0");
  3228. ASSERT_TRUE(svr.is_valid());
  3229. ASSERT_TRUE(port > 0);
  3230. // Read PEM files
  3231. std::string cert_pem, key_pem, ca_pem;
  3232. read_file(SERVER_CERT_FILE, cert_pem);
  3233. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3234. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3235. // Update server certificates using PEM API
  3236. ASSERT_TRUE(
  3237. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3238. ASSERT_TRUE(svr.is_valid());
  3239. svr.stop();
  3240. }
  3241. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  3242. // Start server with client CA (enables client auth)
  3243. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3244. ASSERT_TRUE(svr.is_valid());
  3245. bool handler_called = false;
  3246. svr.Get("/test", [&](const Request &req, Response &res) {
  3247. handler_called = true;
  3248. // Verify client certificate is present
  3249. auto cert = req.peer_cert();
  3250. EXPECT_TRUE(static_cast<bool>(cert));
  3251. res.set_content("ok", "text/plain");
  3252. });
  3253. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3254. auto se = detail::scope_exit([&] {
  3255. svr.stop();
  3256. t.join();
  3257. ASSERT_FALSE(svr.is_running());
  3258. });
  3259. svr.wait_until_ready();
  3260. // Read PEM files
  3261. std::string cert_pem, key_pem, ca_pem;
  3262. read_file(SERVER_CERT_FILE, cert_pem);
  3263. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3264. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3265. // Update server certificates and client CA using PEM API while server running
  3266. ASSERT_TRUE(
  3267. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3268. // Connect with client certificate
  3269. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3270. cli.enable_server_certificate_verification(false);
  3271. cli.set_connection_timeout(30);
  3272. auto res = cli.Get("/test");
  3273. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3274. ASSERT_EQ(StatusCode::OK_200, res->status);
  3275. ASSERT_TRUE(handler_called);
  3276. EXPECT_EQ("ok", res->body);
  3277. }
  3278. #endif
  3279. TEST(ErrorHandlerTest, ContentLength) {
  3280. Server svr;
  3281. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3282. res.status = StatusCode::OK_200;
  3283. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3284. "text/html"); // <= Content-Length still 13
  3285. });
  3286. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3287. res.set_content("Hello World!\n", "text/plain");
  3288. res.status = 524;
  3289. });
  3290. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3291. auto se = detail::scope_exit([&] {
  3292. svr.stop();
  3293. thread.join();
  3294. ASSERT_FALSE(svr.is_running());
  3295. });
  3296. svr.wait_until_ready();
  3297. {
  3298. Client cli(HOST, PORT);
  3299. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3301. EXPECT_EQ(StatusCode::OK_200, res->status);
  3302. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3303. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3304. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3305. }
  3306. }
  3307. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3308. TEST(ExceptionTest, WithoutExceptionHandler) {
  3309. Server svr;
  3310. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  3311. throw std::runtime_error("exception...");
  3312. });
  3313. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  3314. throw std::runtime_error("exception\r\n...");
  3315. });
  3316. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3317. auto se = detail::scope_exit([&] {
  3318. svr.stop();
  3319. listen_thread.join();
  3320. ASSERT_FALSE(svr.is_running());
  3321. });
  3322. svr.wait_until_ready();
  3323. Client cli("localhost", PORT);
  3324. {
  3325. auto res = cli.Get("/exception");
  3326. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3327. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3328. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3329. }
  3330. {
  3331. auto res = cli.Get("/unknown");
  3332. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3333. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3334. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3335. }
  3336. }
  3337. TEST(ExceptionTest, WithExceptionHandler) {
  3338. Server svr;
  3339. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  3340. std::exception_ptr ep) {
  3341. EXPECT_FALSE(ep == nullptr);
  3342. try {
  3343. std::rethrow_exception(ep);
  3344. } catch (std::exception &e) {
  3345. EXPECT_EQ("abc", std::string(e.what()));
  3346. } catch (...) {}
  3347. res.status = StatusCode::InternalServerError_500;
  3348. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3349. "text/html"); // <= Content-Length still 13 at this point
  3350. });
  3351. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3352. res.set_content("Hello World!\n", "text/plain");
  3353. throw std::runtime_error("abc");
  3354. });
  3355. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3356. auto se = detail::scope_exit([&] {
  3357. svr.stop();
  3358. thread.join();
  3359. ASSERT_FALSE(svr.is_running());
  3360. });
  3361. svr.wait_until_ready();
  3362. for (size_t i = 0; i < 10; i++) {
  3363. Client cli(HOST, PORT);
  3364. for (size_t j = 0; j < 100; j++) {
  3365. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3366. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3367. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3368. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3369. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3370. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3371. }
  3372. cli.set_keep_alive(true);
  3373. for (size_t j = 0; j < 100; j++) {
  3374. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3375. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3376. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3377. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3378. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3379. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3380. }
  3381. }
  3382. }
  3383. TEST(ExceptionTest, AndErrorHandler) {
  3384. Server svr;
  3385. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3386. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  3387. });
  3388. svr.set_exception_handler(
  3389. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  3390. EXPECT_FALSE(ep == nullptr);
  3391. try {
  3392. std::rethrow_exception(ep);
  3393. } catch (std::exception &e) {
  3394. res.set_content(e.what(), "text/html");
  3395. } catch (...) {}
  3396. res.status = StatusCode::InternalServerError_500;
  3397. });
  3398. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  3399. throw std::runtime_error("EXCEPTION");
  3400. });
  3401. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  3402. res.set_content("ERROR", "text/html");
  3403. res.status = StatusCode::InternalServerError_500;
  3404. });
  3405. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3406. auto se = detail::scope_exit([&] {
  3407. svr.stop();
  3408. thread.join();
  3409. ASSERT_FALSE(svr.is_running());
  3410. });
  3411. svr.wait_until_ready();
  3412. Client cli(HOST, PORT);
  3413. {
  3414. auto res = cli.Get("/exception");
  3415. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3416. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3417. EXPECT_EQ("EXCEPTION", res->body);
  3418. }
  3419. {
  3420. auto res = cli.Get("/error");
  3421. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3422. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3423. EXPECT_EQ("ERROR", res->body);
  3424. }
  3425. {
  3426. auto res = cli.Get("/invalid");
  3427. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3428. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3429. EXPECT_EQ("NOT_FOUND", res->body);
  3430. }
  3431. }
  3432. #endif
  3433. TEST(NoContentTest, ContentLength) {
  3434. Server svr;
  3435. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3436. res.status = StatusCode::NoContent_204;
  3437. });
  3438. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3439. auto se = detail::scope_exit([&] {
  3440. svr.stop();
  3441. thread.join();
  3442. ASSERT_FALSE(svr.is_running());
  3443. });
  3444. svr.wait_until_ready();
  3445. {
  3446. Client cli(HOST, PORT);
  3447. auto res = cli.Get("/hi");
  3448. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3449. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  3450. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3451. }
  3452. }
  3453. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  3454. #ifdef CPPHTTPLIB_SSL_ENABLED
  3455. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  3456. ASSERT_TRUE(svr.is_valid());
  3457. #else
  3458. Server svr;
  3459. #endif
  3460. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  3461. if (req.path == "/routing_handler") {
  3462. res.set_header("PRE_ROUTING", "on");
  3463. res.set_content("Routing Handler", "text/plain");
  3464. return httplib::Server::HandlerResponse::Handled;
  3465. }
  3466. return httplib::Server::HandlerResponse::Unhandled;
  3467. });
  3468. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3469. res.set_content("Error", "text/html");
  3470. });
  3471. svr.set_post_routing_handler([](const Request &req, Response &res) {
  3472. if (req.path == "/routing_handler") {
  3473. res.set_header("POST_ROUTING", "on");
  3474. }
  3475. });
  3476. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3477. res.set_content("Hello World!\n", "text/plain");
  3478. });
  3479. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3480. auto se = detail::scope_exit([&] {
  3481. svr.stop();
  3482. thread.join();
  3483. ASSERT_FALSE(svr.is_running());
  3484. });
  3485. svr.wait_until_ready();
  3486. {
  3487. #ifdef CPPHTTPLIB_SSL_ENABLED
  3488. SSLClient cli(HOST, PORT);
  3489. cli.enable_server_certificate_verification(false);
  3490. #else
  3491. Client cli(HOST, PORT);
  3492. #endif
  3493. auto res = cli.Get("/routing_handler");
  3494. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3495. EXPECT_EQ(StatusCode::OK_200, res->status);
  3496. EXPECT_EQ("Routing Handler", res->body);
  3497. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  3498. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  3499. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  3500. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  3501. }
  3502. {
  3503. #ifdef CPPHTTPLIB_SSL_ENABLED
  3504. SSLClient cli(HOST, PORT);
  3505. cli.enable_server_certificate_verification(false);
  3506. #else
  3507. Client cli(HOST, PORT);
  3508. #endif
  3509. auto res = cli.Get("/hi");
  3510. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3511. EXPECT_EQ(StatusCode::OK_200, res->status);
  3512. EXPECT_EQ("Hello World!\n", res->body);
  3513. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  3514. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  3515. }
  3516. {
  3517. #ifdef CPPHTTPLIB_SSL_ENABLED
  3518. SSLClient cli(HOST, PORT);
  3519. cli.enable_server_certificate_verification(false);
  3520. #else
  3521. Client cli(HOST, PORT);
  3522. #endif
  3523. auto res = cli.Get("/aaa");
  3524. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3525. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3526. EXPECT_EQ("Error", res->body);
  3527. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  3528. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  3529. }
  3530. }
  3531. TEST(RequestHandlerTest, PreRequestHandler) {
  3532. auto route_path = "/user/:user";
  3533. Server svr;
  3534. svr.Get("/hi", [](const Request &, Response &res) {
  3535. res.set_content("hi", "text/plain");
  3536. });
  3537. svr.Get(route_path, [](const Request &req, Response &res) {
  3538. res.set_content(req.path_params.at("user"), "text/plain");
  3539. });
  3540. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  3541. if (req.matched_route == route_path) {
  3542. auto user = req.path_params.at("user");
  3543. if (user != "john") {
  3544. res.status = StatusCode::Forbidden_403;
  3545. res.set_content("error", "text/html");
  3546. return Server::HandlerResponse::Handled;
  3547. }
  3548. }
  3549. return Server::HandlerResponse::Unhandled;
  3550. });
  3551. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3552. auto se = detail::scope_exit([&] {
  3553. svr.stop();
  3554. thread.join();
  3555. ASSERT_FALSE(svr.is_running());
  3556. });
  3557. svr.wait_until_ready();
  3558. Client cli(HOST, PORT);
  3559. {
  3560. auto res = cli.Get("/hi");
  3561. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3562. EXPECT_EQ(StatusCode::OK_200, res->status);
  3563. EXPECT_EQ("hi", res->body);
  3564. }
  3565. {
  3566. auto res = cli.Get("/user/john");
  3567. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3568. EXPECT_EQ(StatusCode::OK_200, res->status);
  3569. EXPECT_EQ("john", res->body);
  3570. }
  3571. {
  3572. auto res = cli.Get("/user/invalid-user");
  3573. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3574. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  3575. EXPECT_EQ("error", res->body);
  3576. }
  3577. }
  3578. // The pre-request handler must run before the request body is read, so a
  3579. // rejected request never forces the server to buffer a (potentially large)
  3580. // body. Here the posted body is larger than the payload limit: if the body
  3581. // were read first the server would answer 413, but because the pre-request
  3582. // handler runs first it answers 403 and the body is never read.
  3583. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  3584. Server svr;
  3585. svr.set_payload_max_length(8);
  3586. auto handler_ran = false;
  3587. svr.Post("/reject", [&](const Request &req, Response &res) {
  3588. handler_ran = true;
  3589. res.set_content(req.body, "text/plain");
  3590. });
  3591. svr.Post("/accept", [](const Request &req, Response &res) {
  3592. res.set_content(req.body, "text/plain");
  3593. });
  3594. svr.set_pre_request_handler([](const Request &req, Response &res) {
  3595. if (req.matched_route == "/reject") {
  3596. res.status = StatusCode::Forbidden_403;
  3597. res.set_content("denied", "text/plain");
  3598. return Server::HandlerResponse::Handled;
  3599. }
  3600. return Server::HandlerResponse::Unhandled;
  3601. });
  3602. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3603. auto se = detail::scope_exit([&] {
  3604. svr.stop();
  3605. thread.join();
  3606. ASSERT_FALSE(svr.is_running());
  3607. });
  3608. svr.wait_until_ready();
  3609. Client cli(HOST, PORT);
  3610. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  3611. // rejects with 403 before the body is read, so 413 is never reached.
  3612. {
  3613. auto res = cli.Post("/reject", "0123456789", "text/plain");
  3614. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3615. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  3616. EXPECT_EQ("denied", res->body);
  3617. EXPECT_FALSE(handler_ran);
  3618. }
  3619. // An approved route still reads the body and enforces the payload limit.
  3620. {
  3621. auto res = cli.Post("/accept", "0123456789", "text/plain");
  3622. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3623. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  3624. }
  3625. }
  3626. TEST(UserDataTest, BasicOperations) {
  3627. httplib::UserData ud;
  3628. // Initially empty
  3629. EXPECT_FALSE(ud.has("key"));
  3630. EXPECT_EQ(nullptr, ud.get<int>("key"));
  3631. // set and get
  3632. ud.set("key", 42);
  3633. EXPECT_TRUE(ud.has("key"));
  3634. auto *p = ud.get<int>("key");
  3635. ASSERT_NE(nullptr, p);
  3636. EXPECT_EQ(42, *p);
  3637. // Type mismatch → nullptr
  3638. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  3639. // Overwrite with different type
  3640. ud.set("key", std::string("hello"));
  3641. EXPECT_EQ(nullptr, ud.get<int>("key"));
  3642. auto *s = ud.get<std::string>("key");
  3643. ASSERT_NE(nullptr, s);
  3644. EXPECT_EQ("hello", *s);
  3645. // erase
  3646. ud.erase("key");
  3647. EXPECT_FALSE(ud.has("key"));
  3648. // clear
  3649. ud.set("a", 1);
  3650. ud.set("b", 2);
  3651. ud.clear();
  3652. EXPECT_FALSE(ud.has("a"));
  3653. EXPECT_FALSE(ud.has("b"));
  3654. }
  3655. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  3656. struct AuthCtx {
  3657. std::string user_id;
  3658. };
  3659. Server svr;
  3660. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  3661. res.user_data.set("auth", AuthCtx{"alice"});
  3662. return Server::HandlerResponse::Unhandled;
  3663. });
  3664. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  3665. auto *ctx = res.user_data.get<AuthCtx>("auth");
  3666. ASSERT_NE(nullptr, ctx);
  3667. res.set_content("Hello " + ctx->user_id, "text/plain");
  3668. });
  3669. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3670. auto se = detail::scope_exit([&] {
  3671. svr.stop();
  3672. thread.join();
  3673. ASSERT_FALSE(svr.is_running());
  3674. });
  3675. svr.wait_until_ready();
  3676. Client cli(HOST, PORT);
  3677. auto res = cli.Get("/me");
  3678. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3679. EXPECT_EQ(StatusCode::OK_200, res->status);
  3680. EXPECT_EQ("Hello alice", res->body);
  3681. }
  3682. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  3683. struct RoleCtx {
  3684. std::string role;
  3685. };
  3686. Server svr;
  3687. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  3688. res.user_data.set("role", RoleCtx{"admin"});
  3689. return Server::HandlerResponse::Unhandled;
  3690. });
  3691. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  3692. auto *ctx = res.user_data.get<RoleCtx>("role");
  3693. ASSERT_NE(nullptr, ctx);
  3694. res.set_content(ctx->role, "text/plain");
  3695. });
  3696. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3697. auto se = detail::scope_exit([&] {
  3698. svr.stop();
  3699. thread.join();
  3700. ASSERT_FALSE(svr.is_running());
  3701. });
  3702. svr.wait_until_ready();
  3703. Client cli(HOST, PORT);
  3704. auto res = cli.Get("/role");
  3705. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3706. EXPECT_EQ(StatusCode::OK_200, res->status);
  3707. EXPECT_EQ("admin", res->body);
  3708. }
  3709. TEST(InvalidFormatTest, StatusCode) {
  3710. Server svr;
  3711. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3712. res.set_content("Hello World!\n", "text/plain");
  3713. res.status = 9999; // Status should be a three-digit code...
  3714. });
  3715. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3716. auto se = detail::scope_exit([&] {
  3717. svr.stop();
  3718. thread.join();
  3719. ASSERT_FALSE(svr.is_running());
  3720. });
  3721. svr.wait_until_ready();
  3722. {
  3723. Client cli(HOST, PORT);
  3724. auto res = cli.Get("/hi");
  3725. ASSERT_FALSE(res);
  3726. }
  3727. }
  3728. TEST(URLFragmentTest, WithFragment) {
  3729. Server svr;
  3730. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  3731. EXPECT_TRUE(req.target == "/hi");
  3732. });
  3733. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3734. auto se = detail::scope_exit([&] {
  3735. svr.stop();
  3736. thread.join();
  3737. ASSERT_FALSE(svr.is_running());
  3738. });
  3739. svr.wait_until_ready();
  3740. {
  3741. Client cli(HOST, PORT);
  3742. auto res = cli.Get("/hi#key1=val1=key2=val2");
  3743. EXPECT_TRUE(res);
  3744. EXPECT_EQ(StatusCode::OK_200, res->status);
  3745. res = cli.Get("/hi%23key1=val1=key2=val2");
  3746. EXPECT_TRUE(res);
  3747. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3748. }
  3749. }
  3750. TEST(HeaderWriter, SetHeaderWriter) {
  3751. Server svr;
  3752. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  3753. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  3754. return detail::write_headers(strm, hdrs);
  3755. });
  3756. svr.Get("/hi", [](const Request &req, Response &res) {
  3757. auto it = req.headers.find("CustomClientHeader");
  3758. EXPECT_TRUE(it != req.headers.end());
  3759. EXPECT_EQ(it->second, "CustomClientValue");
  3760. res.set_content("Hello World!\n", "text/plain");
  3761. });
  3762. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3763. auto se = detail::scope_exit([&] {
  3764. svr.stop();
  3765. thread.join();
  3766. ASSERT_FALSE(svr.is_running());
  3767. });
  3768. svr.wait_until_ready();
  3769. {
  3770. Client cli(HOST, PORT);
  3771. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  3772. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  3773. return detail::write_headers(strm, hdrs);
  3774. });
  3775. auto res = cli.Get("/hi");
  3776. EXPECT_TRUE(res);
  3777. EXPECT_EQ(StatusCode::OK_200, res->status);
  3778. auto it = res->headers.find("CustomServerHeader");
  3779. EXPECT_TRUE(it != res->headers.end());
  3780. EXPECT_EQ(it->second, "CustomServerValue");
  3781. }
  3782. }
  3783. class ServerTest : public ::testing::Test {
  3784. protected:
  3785. ServerTest()
  3786. : cli_(HOST, PORT)
  3787. #ifdef CPPHTTPLIB_SSL_ENABLED
  3788. ,
  3789. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  3790. #endif
  3791. {
  3792. #ifdef CPPHTTPLIB_SSL_ENABLED
  3793. cli_.enable_server_certificate_verification(false);
  3794. #endif
  3795. // Allow LARGE_DATA (100MB) responses
  3796. cli_.set_payload_max_length(200 * 1024 * 1024);
  3797. }
  3798. virtual void SetUp() {
  3799. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  3800. svr_.set_payload_max_length(200 * 1024 * 1024);
  3801. svr_.set_mount_point("/", "./www");
  3802. svr_.set_mount_point("/mount", "./www2");
  3803. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  3804. svr_.Get("/hi",
  3805. [&](const Request & /*req*/, Response &res) {
  3806. res.set_content("Hello World!", "text/plain");
  3807. })
  3808. .Get("/file_content",
  3809. [&](const Request & /*req*/, Response &res) {
  3810. res.set_file_content("./www/dir/test.html");
  3811. })
  3812. .Get("/file_content_with_content_type",
  3813. [&](const Request & /*req*/, Response &res) {
  3814. res.set_file_content("./www/file", "text/plain");
  3815. })
  3816. .Get("/invalid_file_content",
  3817. [&](const Request & /*req*/, Response &res) {
  3818. res.set_file_content("./www/dir/invalid_file_path");
  3819. })
  3820. .Get("/http_response_splitting",
  3821. [&](const Request & /*req*/, Response &res) {
  3822. res.set_header("a", "1\r\nSet-Cookie: a=1");
  3823. EXPECT_EQ(0U, res.headers.size());
  3824. EXPECT_FALSE(res.has_header("a"));
  3825. res.set_header("a", "1\nSet-Cookie: a=1");
  3826. EXPECT_EQ(0U, res.headers.size());
  3827. EXPECT_FALSE(res.has_header("a"));
  3828. res.set_header("a", "1\rSet-Cookie: a=1");
  3829. EXPECT_EQ(0U, res.headers.size());
  3830. EXPECT_FALSE(res.has_header("a"));
  3831. res.set_header("a\r\nb", "0");
  3832. EXPECT_EQ(0U, res.headers.size());
  3833. EXPECT_FALSE(res.has_header("a"));
  3834. res.set_header("a\rb", "0");
  3835. EXPECT_EQ(0U, res.headers.size());
  3836. EXPECT_FALSE(res.has_header("a"));
  3837. res.set_header("a\nb", "0");
  3838. EXPECT_EQ(0U, res.headers.size());
  3839. EXPECT_FALSE(res.has_header("a"));
  3840. res.set_redirect("1\r\nSet-Cookie: a=1");
  3841. EXPECT_EQ(0U, res.headers.size());
  3842. EXPECT_FALSE(res.has_header("Location"));
  3843. })
  3844. .Get("/slow",
  3845. [&](const Request & /*req*/, Response &res) {
  3846. std::this_thread::sleep_for(std::chrono::seconds(4));
  3847. res.set_content("slow", "text/plain");
  3848. })
  3849. #if 0
  3850. .Post("/slowpost",
  3851. [&](const Request & /*req*/, Response &res) {
  3852. std::this_thread::sleep_for(std::chrono::seconds(2));
  3853. res.set_content("slow", "text/plain");
  3854. })
  3855. #endif
  3856. .Get("/remote_addr",
  3857. [&](const Request &req, Response &res) {
  3858. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  3859. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  3860. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3861. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  3862. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  3863. #endif
  3864. res.set_content(req.remote_addr, "text/plain");
  3865. })
  3866. .Get("/local_addr",
  3867. [&](const Request &req, Response &res) {
  3868. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  3869. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  3870. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3871. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  3872. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  3873. #endif
  3874. auto local_addr = req.local_addr;
  3875. auto local_port = std::to_string(req.local_port);
  3876. res.set_content(local_addr.append(":").append(local_port),
  3877. "text/plain");
  3878. })
  3879. .Get("/endwith%",
  3880. [&](const Request & /*req*/, Response &res) {
  3881. res.set_content("Hello World!", "text/plain");
  3882. })
  3883. .Get("/a\\+\\+b",
  3884. [&](const Request &req, Response &res) {
  3885. ASSERT_TRUE(req.has_param("a +b"));
  3886. auto val = req.get_param_value("a +b");
  3887. res.set_content(val, "text/plain");
  3888. })
  3889. .Get("/", [&](const Request & /*req*/,
  3890. Response &res) { res.set_redirect("/hi"); })
  3891. .Post("/1",
  3892. [](const Request & /*req*/, Response &res) {
  3893. res.set_redirect("/2", StatusCode::SeeOther_303);
  3894. })
  3895. .Get("/2",
  3896. [](const Request & /*req*/, Response &res) {
  3897. res.set_content("redirected.", "text/plain");
  3898. res.status = StatusCode::OK_200;
  3899. })
  3900. .Post("/person",
  3901. [&](const Request &req, Response &res) {
  3902. if (req.has_param("name") && req.has_param("note")) {
  3903. persons_[req.get_param_value("name")] =
  3904. req.get_param_value("note");
  3905. } else {
  3906. res.status = StatusCode::BadRequest_400;
  3907. }
  3908. })
  3909. .Put("/person",
  3910. [&](const Request &req, Response &res) {
  3911. if (req.has_param("name") && req.has_param("note")) {
  3912. persons_[req.get_param_value("name")] =
  3913. req.get_param_value("note");
  3914. } else {
  3915. res.status = StatusCode::BadRequest_400;
  3916. }
  3917. })
  3918. .Get("/person/(.*)",
  3919. [&](const Request &req, Response &res) {
  3920. string name = req.matches[1];
  3921. if (persons_.find(name) != persons_.end()) {
  3922. auto note = persons_[name];
  3923. res.set_content(note, "text/plain");
  3924. } else {
  3925. res.status = StatusCode::NotFound_404;
  3926. }
  3927. })
  3928. .Delete("/person",
  3929. [&](const Request &req, Response &res) {
  3930. if (req.has_param("name")) {
  3931. string name = req.get_param_value("name");
  3932. if (persons_.find(name) != persons_.end()) {
  3933. persons_.erase(name);
  3934. res.set_content("DELETED", "text/plain");
  3935. } else {
  3936. res.status = StatusCode::NotFound_404;
  3937. }
  3938. } else {
  3939. res.status = StatusCode::BadRequest_400;
  3940. }
  3941. })
  3942. .Post("/x-www-form-urlencoded-json",
  3943. [&](const Request &req, Response &res) {
  3944. auto json = req.get_param_value("json");
  3945. ASSERT_EQ(JSON_DATA, json);
  3946. res.set_content(json, "appliation/json");
  3947. res.status = StatusCode::OK_200;
  3948. })
  3949. .Get("/streamed-chunked",
  3950. [&](const Request & /*req*/, Response &res) {
  3951. res.set_chunked_content_provider(
  3952. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  3953. sink.os << "123";
  3954. sink.os << "456";
  3955. sink.os << "789";
  3956. sink.done();
  3957. return true;
  3958. });
  3959. })
  3960. .Get("/streamed-chunked-with-prohibited-trailer",
  3961. [&](const Request & /*req*/, Response &res) {
  3962. auto i = new int(0);
  3963. // Declare both a prohibited trailer (Content-Length) and an
  3964. // allowed one
  3965. res.set_header("Trailer", "Content-Length, X-Allowed");
  3966. res.set_chunked_content_provider(
  3967. "text/plain",
  3968. [i](size_t /*offset*/, DataSink &sink) {
  3969. switch (*i) {
  3970. case 0: sink.os << "123"; break;
  3971. case 1: sink.os << "456"; break;
  3972. case 2: sink.os << "789"; break;
  3973. case 3: {
  3974. sink.done_with_trailer(
  3975. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  3976. } break;
  3977. }
  3978. (*i)++;
  3979. return true;
  3980. },
  3981. [i](bool success) {
  3982. EXPECT_TRUE(success);
  3983. delete i;
  3984. });
  3985. })
  3986. .Get("/streamed-chunked2",
  3987. [&](const Request & /*req*/, Response &res) {
  3988. auto i = new int(0);
  3989. res.set_chunked_content_provider(
  3990. "text/plain",
  3991. [i](size_t /*offset*/, DataSink &sink) {
  3992. switch (*i) {
  3993. case 0: sink.os << "123"; break;
  3994. case 1: sink.os << "456"; break;
  3995. case 2: sink.os << "789"; break;
  3996. case 3: sink.done(); break;
  3997. }
  3998. (*i)++;
  3999. return true;
  4000. },
  4001. [i](bool success) {
  4002. EXPECT_TRUE(success);
  4003. delete i;
  4004. });
  4005. })
  4006. .Get("/streamed-chunked-with-trailer",
  4007. [&](const Request & /*req*/, Response &res) {
  4008. auto i = new int(0);
  4009. res.set_header("Trailer", "Dummy1, Dummy2");
  4010. res.set_chunked_content_provider(
  4011. "text/plain",
  4012. [i](size_t /*offset*/, DataSink &sink) {
  4013. switch (*i) {
  4014. case 0: sink.os << "123"; break;
  4015. case 1: sink.os << "456"; break;
  4016. case 2: sink.os << "789"; break;
  4017. case 3: {
  4018. sink.done_with_trailer(
  4019. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  4020. } break;
  4021. }
  4022. (*i)++;
  4023. return true;
  4024. },
  4025. [i](bool success) {
  4026. EXPECT_TRUE(success);
  4027. delete i;
  4028. });
  4029. })
  4030. .Get("/streamed",
  4031. [&](const Request & /*req*/, Response &res) {
  4032. res.set_content_provider(
  4033. 6, "text/plain",
  4034. [](size_t offset, size_t /*length*/, DataSink &sink) {
  4035. sink.os << (offset < 3 ? "a" : "b");
  4036. return true;
  4037. });
  4038. })
  4039. .Get("/streamed-without-length",
  4040. [&](const Request & /*req*/, Response &res) {
  4041. auto data = new std::string("abcdefg");
  4042. res.set_content_provider(
  4043. "text/plain",
  4044. [data](size_t offset, DataSink &sink) {
  4045. if (offset < data->size()) {
  4046. sink.os << data->substr(offset);
  4047. }
  4048. sink.done();
  4049. return true;
  4050. },
  4051. [data](bool success) {
  4052. EXPECT_TRUE(success);
  4053. delete data;
  4054. });
  4055. })
  4056. .Get("/streamed-with-range",
  4057. [&](const Request &req, Response &res) {
  4058. auto data = new std::string("abcdefg");
  4059. // An explicit status keeps the server from picking the 206 it
  4060. // would otherwise choose for a ranged request, so the response
  4061. // is not a partial representation.
  4062. auto status = req.get_param_value("status");
  4063. if (status == "200") {
  4064. res.status = StatusCode::OK_200;
  4065. } else if (status == "403") {
  4066. res.status = StatusCode::Forbidden_403;
  4067. }
  4068. res.set_content_provider(
  4069. data->size(), "text/plain",
  4070. [data](size_t offset, size_t length, DataSink &sink) {
  4071. size_t DATA_CHUNK_SIZE = 4;
  4072. const auto &d = *data;
  4073. auto out_len =
  4074. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  4075. auto ret =
  4076. sink.write(&d[static_cast<size_t>(offset)], out_len);
  4077. EXPECT_TRUE(ret);
  4078. return true;
  4079. },
  4080. [data, &req](bool success) {
  4081. EXPECT_EQ(success, !req.has_param("error"));
  4082. delete data;
  4083. });
  4084. })
  4085. .Get("/streamed-cancel",
  4086. [&](const Request & /*req*/, Response &res) {
  4087. res.set_content_provider(
  4088. size_t(-1), "text/plain",
  4089. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4090. sink.os << "data_chunk";
  4091. return true;
  4092. });
  4093. })
  4094. .Get("/regex-with-delimiter",
  4095. [&](const Request &req, Response & /*res*/) {
  4096. ASSERT_TRUE(req.has_param("key"));
  4097. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  4098. })
  4099. .Get("/with-range",
  4100. [&](const Request & /*req*/, Response &res) {
  4101. res.set_content("abcdefg", "text/plain");
  4102. })
  4103. .Get("/test-start-time",
  4104. [&](const Request &req, Response & /*res*/) {
  4105. EXPECT_NE(req.start_time_,
  4106. std::chrono::steady_clock::time_point::min());
  4107. })
  4108. .Get("/with-range-customized-response",
  4109. [&](const Request & /*req*/, Response &res) {
  4110. res.status = StatusCode::BadRequest_400;
  4111. res.set_content(JSON_DATA, "application/json");
  4112. })
  4113. .Post("/chunked",
  4114. [&](const Request &req, Response & /*res*/) {
  4115. EXPECT_EQ(req.body, "dechunked post body");
  4116. })
  4117. .Post("/large-chunked",
  4118. [&](const Request &req, Response & /*res*/) {
  4119. std::string expected(6 * 30 * 1024u, 'a');
  4120. EXPECT_EQ(req.body, expected);
  4121. })
  4122. .Post("/multipart",
  4123. [&](const Request &req, Response & /*res*/) {
  4124. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  4125. req.form.get_field_count("text2") +
  4126. req.form.get_field_count("file3") +
  4127. req.form.get_field_count("file4"));
  4128. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  4129. req.form.get_file_count("file2"));
  4130. ASSERT_TRUE(!req.form.has_file("???"));
  4131. ASSERT_TRUE(!req.form.has_field("???"));
  4132. ASSERT_TRUE(req.body.empty());
  4133. {
  4134. const auto &text = req.form.get_field("text1");
  4135. EXPECT_EQ("text default", text);
  4136. }
  4137. {
  4138. const auto &text = req.form.get_field("text2");
  4139. EXPECT_EQ("aωb", text);
  4140. }
  4141. {
  4142. const auto &file = req.form.get_file("file1");
  4143. EXPECT_EQ("hello.txt", file.filename);
  4144. EXPECT_EQ("text/plain", file.content_type);
  4145. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  4146. }
  4147. {
  4148. const auto &file = req.form.get_file("file2");
  4149. EXPECT_EQ("world.json", file.filename);
  4150. EXPECT_EQ("application/json", file.content_type);
  4151. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  4152. }
  4153. {
  4154. const auto &text = req.form.get_field("file3");
  4155. EXPECT_EQ(0u, text.size());
  4156. }
  4157. {
  4158. const auto &text = req.form.get_field("file4");
  4159. EXPECT_EQ(0u, text.size());
  4160. }
  4161. })
  4162. .Post("/multipart/multi_file_values",
  4163. [&](const Request &req, Response & /*res*/) {
  4164. EXPECT_EQ(3u, req.form.get_field_count("text") +
  4165. req.form.get_field_count("multi_text1"));
  4166. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  4167. ASSERT_TRUE(!req.form.has_file("???"));
  4168. ASSERT_TRUE(!req.form.has_field("???"));
  4169. ASSERT_TRUE(req.body.empty());
  4170. {
  4171. const auto &text = req.form.get_field("text");
  4172. EXPECT_EQ("default text", text);
  4173. }
  4174. {
  4175. const auto &text1_values = req.form.get_fields("multi_text1");
  4176. EXPECT_EQ(2u, text1_values.size());
  4177. EXPECT_EQ("aaaaa", text1_values[0]);
  4178. EXPECT_EQ("bbbbb", text1_values[1]);
  4179. }
  4180. {
  4181. const auto &file1_values = req.form.get_files("multi_file1");
  4182. EXPECT_EQ(2u, file1_values.size());
  4183. auto file1 = file1_values[0];
  4184. EXPECT_EQ(file1.filename, "hello.txt");
  4185. EXPECT_EQ(file1.content_type, "text/plain");
  4186. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  4187. auto file2 = file1_values[1];
  4188. EXPECT_EQ(file2.filename, "world.json");
  4189. EXPECT_EQ(file2.content_type, "application/json");
  4190. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  4191. }
  4192. })
  4193. .Post("/empty",
  4194. [&](const Request &req, Response &res) {
  4195. EXPECT_EQ(req.body, "");
  4196. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  4197. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4198. res.set_content("empty", "text/plain");
  4199. })
  4200. .Post("/empty-no-content-type",
  4201. [&](const Request &req, Response &res) {
  4202. EXPECT_EQ(req.body, "");
  4203. EXPECT_FALSE(req.has_header("Content-Type"));
  4204. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4205. res.set_content("empty-no-content-type", "text/plain");
  4206. })
  4207. .Post("/path-only",
  4208. [&](const Request &req, Response &res) {
  4209. EXPECT_EQ(req.body, "");
  4210. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4211. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4212. res.set_content("path-only", "text/plain");
  4213. })
  4214. .Post("/path-headers-only",
  4215. [&](const Request &req, Response &res) {
  4216. EXPECT_EQ(req.body, "");
  4217. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4218. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4219. EXPECT_EQ("world", req.get_header_value("hello"));
  4220. EXPECT_EQ("world2", req.get_header_value("hello2"));
  4221. res.set_content("path-headers-only", "text/plain");
  4222. })
  4223. .Post("/post-large",
  4224. [&](const Request &req, Response &res) {
  4225. EXPECT_EQ(req.body, LARGE_DATA);
  4226. res.set_content(req.body, "text/plain");
  4227. })
  4228. .Post("/post-loopback",
  4229. [&](const Request &, Response &res,
  4230. ContentReader const &content_reader) {
  4231. std::string body;
  4232. content_reader([&](const char *data, size_t data_length) {
  4233. body.append(data, data_length);
  4234. return true;
  4235. });
  4236. res.set_content(body, "text/plain");
  4237. })
  4238. .Put("/put-loopback",
  4239. [&](const Request &, Response &res,
  4240. ContentReader const &content_reader) {
  4241. std::string body;
  4242. content_reader([&](const char *data, size_t data_length) {
  4243. body.append(data, data_length);
  4244. return true;
  4245. });
  4246. res.set_content(body, "text/plain");
  4247. })
  4248. .Patch("/patch-loopback",
  4249. [&](const Request &, Response &res,
  4250. ContentReader const &content_reader) {
  4251. std::string body;
  4252. content_reader([&](const char *data, size_t data_length) {
  4253. body.append(data, data_length);
  4254. return true;
  4255. });
  4256. res.set_content(body, "text/plain");
  4257. })
  4258. .Put("/empty-no-content-type",
  4259. [&](const Request &req, Response &res) {
  4260. EXPECT_EQ(req.body, "");
  4261. EXPECT_FALSE(req.has_header("Content-Type"));
  4262. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4263. res.set_content("empty-no-content-type", "text/plain");
  4264. })
  4265. .Put("/put",
  4266. [&](const Request &req, Response &res) {
  4267. EXPECT_EQ(req.body, "PUT");
  4268. res.set_content(req.body, "text/plain");
  4269. })
  4270. .Put("/put-large",
  4271. [&](const Request &req, Response &res) {
  4272. EXPECT_EQ(req.body, LARGE_DATA);
  4273. res.set_content(req.body, "text/plain");
  4274. })
  4275. .Patch("/patch",
  4276. [&](const Request &req, Response &res) {
  4277. EXPECT_EQ(req.body, "PATCH");
  4278. res.set_content(req.body, "text/plain");
  4279. })
  4280. .Delete("/delete",
  4281. [&](const Request & /*req*/, Response &res) {
  4282. res.set_content("DELETE", "text/plain");
  4283. })
  4284. .Delete("/delete-body",
  4285. [&](const Request &req, Response &res) {
  4286. EXPECT_EQ(req.body, "content");
  4287. res.set_content(req.body, "text/plain");
  4288. })
  4289. .Options(R"(\*)",
  4290. [&](const Request & /*req*/, Response &res) {
  4291. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  4292. })
  4293. .Get("/request-target",
  4294. [&](const Request &req, Response & /*res*/) {
  4295. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  4296. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  4297. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  4298. })
  4299. .Get("/long-query-value",
  4300. [&](const Request &req, Response & /*res*/) {
  4301. EXPECT_EQ(LONG_QUERY_URL, req.target);
  4302. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  4303. })
  4304. .Get("/too-long-query-value",
  4305. [&](const Request &req, Response & /*res*/) {
  4306. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  4307. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  4308. })
  4309. .Get("/array-param",
  4310. [&](const Request &req, Response & /*res*/) {
  4311. EXPECT_EQ(3u, req.get_param_value_count("array"));
  4312. EXPECT_EQ("value1", req.get_param_value("array", 0));
  4313. EXPECT_EQ("value2", req.get_param_value("array", 1));
  4314. EXPECT_EQ("value3", req.get_param_value("array", 2));
  4315. })
  4316. .Get("/array-param-values",
  4317. [&](const Request &req, Response & /*res*/) {
  4318. auto values = req.get_param_values("array");
  4319. EXPECT_EQ(3u, values.size());
  4320. EXPECT_EQ("value1", values[0]);
  4321. EXPECT_EQ("value2", values[1]);
  4322. EXPECT_EQ("value3", values[2]);
  4323. auto empty = req.get_param_values("nonexistent");
  4324. EXPECT_TRUE(empty.empty());
  4325. })
  4326. .Post("/validate-no-multiple-headers",
  4327. [&](const Request &req, Response & /*res*/) {
  4328. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  4329. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  4330. })
  4331. .Post("/content_receiver",
  4332. [&](const Request &req, Response &res,
  4333. const ContentReader &content_reader) {
  4334. if (req.is_multipart_form_data()) {
  4335. std::vector<FormData> items;
  4336. content_reader(
  4337. [&](const FormData &file) {
  4338. items.push_back(file);
  4339. return true;
  4340. },
  4341. [&](const char *data, size_t data_length) {
  4342. items.back().content.append(data, data_length);
  4343. return true;
  4344. });
  4345. EXPECT_EQ(5u, items.size());
  4346. {
  4347. const auto &file = get_file_value(items, "text1");
  4348. EXPECT_TRUE(file.filename.empty());
  4349. EXPECT_EQ("text default", file.content);
  4350. }
  4351. {
  4352. const auto &file = get_file_value(items, "text2");
  4353. EXPECT_TRUE(file.filename.empty());
  4354. EXPECT_EQ("aωb", file.content);
  4355. }
  4356. {
  4357. const auto &file = get_file_value(items, "file1");
  4358. EXPECT_EQ("hello.txt", file.filename);
  4359. EXPECT_EQ("text/plain", file.content_type);
  4360. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  4361. }
  4362. {
  4363. const auto &file = get_file_value(items, "file2");
  4364. EXPECT_EQ("world.json", file.filename);
  4365. EXPECT_EQ("application/json", file.content_type);
  4366. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  4367. }
  4368. {
  4369. const auto &file = get_file_value(items, "file3");
  4370. EXPECT_TRUE(file.filename.empty());
  4371. EXPECT_EQ("application/octet-stream", file.content_type);
  4372. EXPECT_EQ(0u, file.content.size());
  4373. }
  4374. } else {
  4375. std::string body;
  4376. content_reader([&](const char *data, size_t data_length) {
  4377. EXPECT_EQ(7U, data_length);
  4378. body.append(data, data_length);
  4379. return true;
  4380. });
  4381. EXPECT_EQ(body, "content");
  4382. res.set_content(body, "text/plain");
  4383. }
  4384. })
  4385. .Put("/content_receiver",
  4386. [&](const Request & /*req*/, Response &res,
  4387. const ContentReader &content_reader) {
  4388. std::string body;
  4389. content_reader([&](const char *data, size_t data_length) {
  4390. body.append(data, data_length);
  4391. return true;
  4392. });
  4393. EXPECT_EQ(body, "content");
  4394. res.set_content(body, "text/plain");
  4395. })
  4396. .Patch("/content_receiver",
  4397. [&](const Request & /*req*/, Response &res,
  4398. const ContentReader &content_reader) {
  4399. std::string body;
  4400. content_reader([&](const char *data, size_t data_length) {
  4401. body.append(data, data_length);
  4402. return true;
  4403. });
  4404. EXPECT_EQ(body, "content");
  4405. res.set_content(body, "text/plain");
  4406. })
  4407. .Post("/query-string-and-body",
  4408. [&](const Request &req, Response & /*res*/) {
  4409. ASSERT_TRUE(req.has_param("key"));
  4410. EXPECT_EQ(req.get_param_value("key"), "value");
  4411. EXPECT_EQ(req.body, "content");
  4412. })
  4413. .Get("/last-request",
  4414. [&](const Request &req, Response & /*res*/) {
  4415. EXPECT_EQ("close", req.get_header_value("Connection"));
  4416. })
  4417. .Get(R"(/redirect/(\d+))",
  4418. [&](const Request &req, Response &res) {
  4419. auto num = std::stoi(req.matches[1]) + 1;
  4420. std::string url = "/redirect/" + std::to_string(num);
  4421. res.set_redirect(url);
  4422. })
  4423. .Post("/binary",
  4424. [&](const Request &req, Response &res) {
  4425. EXPECT_EQ(4U, req.body.size());
  4426. EXPECT_EQ("application/octet-stream",
  4427. req.get_header_value("Content-Type"));
  4428. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4429. res.set_content(req.body, "application/octet-stream");
  4430. })
  4431. .Put("/binary",
  4432. [&](const Request &req, Response &res) {
  4433. EXPECT_EQ(4U, req.body.size());
  4434. EXPECT_EQ("application/octet-stream",
  4435. req.get_header_value("Content-Type"));
  4436. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4437. res.set_content(req.body, "application/octet-stream");
  4438. })
  4439. .Patch("/binary",
  4440. [&](const Request &req, Response &res) {
  4441. EXPECT_EQ(4U, req.body.size());
  4442. EXPECT_EQ("application/octet-stream",
  4443. req.get_header_value("Content-Type"));
  4444. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4445. res.set_content(req.body, "application/octet-stream");
  4446. })
  4447. .Delete("/binary",
  4448. [&](const Request &req, Response &res) {
  4449. EXPECT_EQ(4U, req.body.size());
  4450. EXPECT_EQ("application/octet-stream",
  4451. req.get_header_value("Content-Type"));
  4452. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4453. res.set_content(req.body, "application/octet-stream");
  4454. })
  4455. .Get("/issue1772",
  4456. [&](const Request & /*req*/, Response &res) {
  4457. res.status = 401;
  4458. res.set_header("WWW-Authenticate", "Basic realm=123456");
  4459. })
  4460. .Delete("/issue609",
  4461. [](const httplib::Request &, httplib::Response &res,
  4462. const httplib::ContentReader &) {
  4463. res.set_content("ok", "text/plain");
  4464. })
  4465. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  4466. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  4467. .Get("/compress",
  4468. [&](const Request & /*req*/, Response &res) {
  4469. res.set_content(
  4470. "12345678901234567890123456789012345678901234567890123456789"
  4471. "01234567890123456789012345678901234567890",
  4472. "text/plain");
  4473. })
  4474. .Get("/compress-with-charset",
  4475. [&](const Request & /*req*/, Response &res) {
  4476. res.set_content(
  4477. "12345678901234567890123456789012345678901234567890123456789"
  4478. "01234567890123456789012345678901234567890",
  4479. "application/json; charset=utf-8");
  4480. })
  4481. .Get("/nocompress",
  4482. [&](const Request & /*req*/, Response &res) {
  4483. res.set_content(
  4484. "12345678901234567890123456789012345678901234567890123456789"
  4485. "01234567890123456789012345678901234567890",
  4486. "application/octet-stream");
  4487. })
  4488. .Post("/compress-multipart",
  4489. [&](const Request &req, Response & /*res*/) {
  4490. EXPECT_EQ(2u, req.form.fields.size());
  4491. ASSERT_TRUE(!req.form.has_field("???"));
  4492. {
  4493. const auto &text = req.form.get_field("key1");
  4494. EXPECT_EQ("test", text);
  4495. }
  4496. {
  4497. const auto &text = req.form.get_field("key2");
  4498. EXPECT_EQ("--abcdefg123", text);
  4499. }
  4500. })
  4501. #endif
  4502. ;
  4503. persons_["john"] = "programmer";
  4504. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  4505. svr_.wait_until_ready();
  4506. }
  4507. virtual void TearDown() {
  4508. svr_.stop();
  4509. if (!request_threads_.empty()) {
  4510. std::this_thread::sleep_for(std::chrono::seconds(1));
  4511. for (auto &t : request_threads_) {
  4512. t.join();
  4513. }
  4514. }
  4515. t_.join();
  4516. }
  4517. map<string, string> persons_;
  4518. #ifdef CPPHTTPLIB_SSL_ENABLED
  4519. SSLClient cli_;
  4520. SSLServer svr_;
  4521. #else
  4522. Client cli_;
  4523. Server svr_;
  4524. #endif
  4525. thread t_;
  4526. std::vector<thread> request_threads_;
  4527. };
  4528. TEST_F(ServerTest, GetMethod200) {
  4529. auto res = cli_.Get("/hi");
  4530. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4531. EXPECT_EQ("HTTP/1.1", res->version);
  4532. EXPECT_EQ(StatusCode::OK_200, res->status);
  4533. EXPECT_EQ("OK", res->reason);
  4534. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4535. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  4536. EXPECT_EQ("Hello World!", res->body);
  4537. }
  4538. TEST_F(ServerTest, GetEmptyFile) {
  4539. auto res = cli_.Get("/empty_file");
  4540. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4541. EXPECT_EQ(StatusCode::OK_200, res->status);
  4542. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  4543. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  4544. EXPECT_EQ("", res->body);
  4545. }
  4546. TEST_F(ServerTest, GetFileContent) {
  4547. auto res = cli_.Get("/file_content");
  4548. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4549. EXPECT_EQ(StatusCode::OK_200, res->status);
  4550. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4551. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  4552. EXPECT_EQ("test.html", res->body);
  4553. }
  4554. TEST_F(ServerTest, GetFileContentWithRange) {
  4555. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  4556. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4557. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4558. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4559. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  4560. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  4561. EXPECT_EQ("est", res->body);
  4562. }
  4563. TEST_F(ServerTest, GetFileContentWithContentType) {
  4564. auto res = cli_.Get("/file_content_with_content_type");
  4565. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4566. EXPECT_EQ(StatusCode::OK_200, res->status);
  4567. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4568. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  4569. EXPECT_EQ("file\n", res->body);
  4570. }
  4571. TEST_F(ServerTest, GetInvalidFileContent) {
  4572. auto res = cli_.Get("/invalid_file_content");
  4573. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4574. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4575. }
  4576. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  4577. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  4578. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4579. EXPECT_EQ("HTTP/1.1", res->version);
  4580. EXPECT_EQ(StatusCode::OK_200, res->status);
  4581. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4582. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  4583. EXPECT_EQ("Hello World!", res->body);
  4584. }
  4585. TEST_F(ServerTest, GetMethod302) {
  4586. auto res = cli_.Get("/");
  4587. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4588. EXPECT_EQ(StatusCode::Found_302, res->status);
  4589. EXPECT_EQ("/hi", res->get_header_value("Location"));
  4590. }
  4591. TEST_F(ServerTest, GetMethod302Redirect) {
  4592. cli_.set_follow_location(true);
  4593. auto res = cli_.Get("/");
  4594. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4595. EXPECT_EQ(StatusCode::OK_200, res->status);
  4596. EXPECT_EQ("Hello World!", res->body);
  4597. EXPECT_EQ("/hi", res->location);
  4598. }
  4599. TEST_F(ServerTest, GetMethod404) {
  4600. auto res = cli_.Get("/invalid");
  4601. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4602. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4603. }
  4604. TEST_F(ServerTest, HeadMethod200) {
  4605. auto res = cli_.Head("/hi");
  4606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4607. EXPECT_EQ(StatusCode::OK_200, res->status);
  4608. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4609. EXPECT_TRUE(res->body.empty());
  4610. }
  4611. TEST_F(ServerTest, HeadMethod200Static) {
  4612. auto res = cli_.Head("/mount/dir/index.html");
  4613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4614. EXPECT_EQ(StatusCode::OK_200, res->status);
  4615. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4616. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  4617. EXPECT_TRUE(res->body.empty());
  4618. }
  4619. TEST_F(ServerTest, HeadMethod404) {
  4620. auto res = cli_.Head("/invalid");
  4621. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4622. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4623. EXPECT_TRUE(res->body.empty());
  4624. }
  4625. TEST_F(ServerTest, GetMethodPersonJohn) {
  4626. auto res = cli_.Get("/person/john");
  4627. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4628. EXPECT_EQ(StatusCode::OK_200, res->status);
  4629. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4630. EXPECT_EQ("programmer", res->body);
  4631. }
  4632. TEST_F(ServerTest, PostMethod1) {
  4633. auto res = cli_.Get("/person/john1");
  4634. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4635. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4636. res = cli_.Post("/person", "name=john1&note=coder",
  4637. "application/x-www-form-urlencoded");
  4638. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4639. ASSERT_EQ(StatusCode::OK_200, res->status);
  4640. res = cli_.Get("/person/john1");
  4641. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4642. ASSERT_EQ(StatusCode::OK_200, res->status);
  4643. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4644. ASSERT_EQ("coder", res->body);
  4645. }
  4646. TEST_F(ServerTest, PostMethod2) {
  4647. auto res = cli_.Get("/person/john2");
  4648. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4649. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4650. Params params;
  4651. params.emplace("name", "john2");
  4652. params.emplace("note", "coder");
  4653. res = cli_.Post("/person", params);
  4654. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4655. ASSERT_EQ(StatusCode::OK_200, res->status);
  4656. res = cli_.Get("/person/john2");
  4657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4658. ASSERT_EQ(StatusCode::OK_200, res->status);
  4659. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4660. ASSERT_EQ("coder", res->body);
  4661. }
  4662. TEST_F(ServerTest, PutMethod3) {
  4663. auto res = cli_.Get("/person/john3");
  4664. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4665. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4666. Params params;
  4667. params.emplace("name", "john3");
  4668. params.emplace("note", "coder");
  4669. res = cli_.Put("/person", params);
  4670. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4671. ASSERT_EQ(StatusCode::OK_200, res->status);
  4672. res = cli_.Get("/person/john3");
  4673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4674. ASSERT_EQ(StatusCode::OK_200, res->status);
  4675. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4676. ASSERT_EQ("coder", res->body);
  4677. }
  4678. TEST_F(ServerTest, DeleteMethod1) {
  4679. auto res = cli_.Get("/person/john4");
  4680. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4681. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4682. Params params;
  4683. params.emplace("name", "john4");
  4684. params.emplace("note", "coder");
  4685. res = cli_.Post("/person", params);
  4686. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4687. ASSERT_EQ(StatusCode::OK_200, res->status);
  4688. res = cli_.Get("/person/john4");
  4689. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4690. ASSERT_EQ(StatusCode::OK_200, res->status);
  4691. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4692. ASSERT_EQ("coder", res->body);
  4693. Params delete_params;
  4694. delete_params.emplace("name", "john4");
  4695. res = cli_.Delete("/person", delete_params);
  4696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4697. ASSERT_EQ(StatusCode::OK_200, res->status);
  4698. ASSERT_EQ("DELETED", res->body);
  4699. res = cli_.Get("/person/john4");
  4700. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4701. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4702. }
  4703. TEST_F(ServerTest, DeleteMethod2) {
  4704. auto res = cli_.Get("/person/john5");
  4705. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4706. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4707. Params params;
  4708. params.emplace("name", "john5");
  4709. params.emplace("note", "developer");
  4710. res = cli_.Post("/person", params);
  4711. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4712. ASSERT_EQ(StatusCode::OK_200, res->status);
  4713. res = cli_.Get("/person/john5");
  4714. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4715. ASSERT_EQ(StatusCode::OK_200, res->status);
  4716. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4717. ASSERT_EQ("developer", res->body);
  4718. Params delete_params;
  4719. delete_params.emplace("name", "john5");
  4720. Headers headers;
  4721. headers.emplace("Custom-Header", "test-value");
  4722. res = cli_.Delete("/person", headers, delete_params);
  4723. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4724. ASSERT_EQ(StatusCode::OK_200, res->status);
  4725. ASSERT_EQ("DELETED", res->body);
  4726. res = cli_.Get("/person/john5");
  4727. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4728. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4729. }
  4730. TEST_F(ServerTest, DeleteMethod3) {
  4731. auto res = cli_.Get("/person/john6");
  4732. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4733. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4734. Params params;
  4735. params.emplace("name", "john6");
  4736. params.emplace("note", "tester");
  4737. res = cli_.Post("/person", params);
  4738. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4739. ASSERT_EQ(StatusCode::OK_200, res->status);
  4740. res = cli_.Get("/person/john6");
  4741. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4742. ASSERT_EQ(StatusCode::OK_200, res->status);
  4743. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4744. ASSERT_EQ("tester", res->body);
  4745. Params delete_params;
  4746. delete_params.emplace("name", "john6");
  4747. Headers headers;
  4748. headers.emplace("Custom-Header", "test-value");
  4749. res = cli_.Delete("/person", headers, delete_params, nullptr);
  4750. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4751. ASSERT_EQ(StatusCode::OK_200, res->status);
  4752. ASSERT_EQ("DELETED", res->body);
  4753. res = cli_.Get("/person/john6");
  4754. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4755. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4756. }
  4757. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  4758. Params params;
  4759. params.emplace("json", JSON_DATA);
  4760. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  4761. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4762. ASSERT_EQ(StatusCode::OK_200, res->status);
  4763. ASSERT_EQ(JSON_DATA, res->body);
  4764. }
  4765. TEST_F(ServerTest, PostEmptyContent) {
  4766. auto res = cli_.Post("/empty", "", "text/plain");
  4767. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4768. ASSERT_EQ(StatusCode::OK_200, res->status);
  4769. ASSERT_EQ("empty", res->body);
  4770. }
  4771. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  4772. auto res = cli_.Post("/empty-no-content-type");
  4773. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4774. ASSERT_EQ(StatusCode::OK_200, res->status);
  4775. ASSERT_EQ("empty-no-content-type", res->body);
  4776. }
  4777. TEST_F(ServerTest, PostPathOnly) {
  4778. auto res = cli_.Post("/path-only");
  4779. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4780. ASSERT_EQ(StatusCode::OK_200, res->status);
  4781. ASSERT_EQ("path-only", res->body);
  4782. }
  4783. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  4784. auto res = cli_.Post("/path-headers-only",
  4785. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  4786. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4787. ASSERT_EQ(StatusCode::OK_200, res->status);
  4788. ASSERT_EQ("path-headers-only", res->body);
  4789. }
  4790. TEST_F(ServerTest, PostLarge) {
  4791. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  4792. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4793. ASSERT_EQ(StatusCode::OK_200, res->status);
  4794. EXPECT_EQ(LARGE_DATA, res->body);
  4795. }
  4796. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  4797. auto res = cli_.Put("/empty-no-content-type");
  4798. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4799. ASSERT_EQ(StatusCode::OK_200, res->status);
  4800. ASSERT_EQ("empty-no-content-type", res->body);
  4801. }
  4802. TEST_F(ServerTest, GetMethodDir) {
  4803. auto res = cli_.Get("/dir/");
  4804. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4805. EXPECT_EQ(StatusCode::OK_200, res->status);
  4806. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4807. auto body = R"(<html>
  4808. <head>
  4809. </head>
  4810. <body>
  4811. <a href="/dir/test.html">Test</a>
  4812. <a href="/hi">hi</a>
  4813. </body>
  4814. </html>
  4815. )";
  4816. EXPECT_EQ(body, res->body);
  4817. }
  4818. TEST_F(ServerTest, GetMethodDirTest) {
  4819. auto res = cli_.Get("/dir/test.html");
  4820. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4821. EXPECT_EQ(StatusCode::OK_200, res->status);
  4822. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4823. EXPECT_EQ("test.html", res->body);
  4824. }
  4825. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  4826. auto res = cli_.Get("/dir/../dir/test.html");
  4827. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4828. EXPECT_EQ(StatusCode::OK_200, res->status);
  4829. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4830. EXPECT_EQ("test.html", res->body);
  4831. }
  4832. TEST_F(ServerTest, GetMethodInvalidPath) {
  4833. auto res = cli_.Get("/dir/../test.html");
  4834. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4835. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4836. }
  4837. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  4838. auto res = cli_.Get("/../www/dir/test.html");
  4839. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4840. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4841. }
  4842. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  4843. auto res = cli_.Get("/dir/../../www/dir/test.html");
  4844. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4845. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4846. }
  4847. TEST_F(ServerTest, GetMethodDirMountTest) {
  4848. auto res = cli_.Get("/mount/dir/test.html");
  4849. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4850. EXPECT_EQ(StatusCode::OK_200, res->status);
  4851. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4852. EXPECT_EQ("test.html", res->body);
  4853. }
  4854. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  4855. auto res = cli_.Get("/mount/dir/../dir/test.html");
  4856. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4857. EXPECT_EQ(StatusCode::OK_200, res->status);
  4858. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4859. EXPECT_EQ("test.html", res->body);
  4860. }
  4861. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  4862. auto res = cli_.Get("/mount/dir/../test.html");
  4863. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4864. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4865. }
  4866. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  4867. auto res = cli_.Get("/mount/dir/test.html%00.js");
  4868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4869. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4870. }
  4871. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  4872. auto res = cli_.Get("/mount/../www2/dir/test.html");
  4873. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4874. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4875. }
  4876. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  4877. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  4878. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4879. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4880. }
  4881. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  4882. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  4883. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4884. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4885. }
  4886. TEST_F(ServerTest, PostMethod303) {
  4887. auto res = cli_.Post("/1", "body", "text/plain");
  4888. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4889. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  4890. EXPECT_EQ("/2", res->get_header_value("Location"));
  4891. }
  4892. TEST_F(ServerTest, PostMethod303Redirect) {
  4893. cli_.set_follow_location(true);
  4894. auto res = cli_.Post("/1", "body", "text/plain");
  4895. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4896. EXPECT_EQ(StatusCode::OK_200, res->status);
  4897. EXPECT_EQ("redirected.", res->body);
  4898. EXPECT_EQ("/2", res->location);
  4899. }
  4900. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  4901. auto res = cli_.Get("/dir/test.abcde");
  4902. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4903. EXPECT_EQ(StatusCode::OK_200, res->status);
  4904. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4905. EXPECT_EQ("abcde", res->body);
  4906. }
  4907. TEST_F(ServerTest, StaticFileRange) {
  4908. auto res =
  4909. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  4910. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4911. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4912. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4913. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4914. EXPECT_EQ(true, res->has_header("Content-Range"));
  4915. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  4916. EXPECT_EQ(std::string("cd"), res->body);
  4917. }
  4918. TEST_F(ServerTest, StaticFileRanges) {
  4919. auto res = cli_.Get("/dir/test.abcde",
  4920. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  4921. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4922. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4923. EXPECT_TRUE(
  4924. res->get_header_value("Content-Type")
  4925. .find(
  4926. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  4927. 0);
  4928. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  4929. }
  4930. TEST_F(ServerTest, StaticFileRangeHead) {
  4931. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  4932. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4933. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4934. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4935. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4936. EXPECT_EQ(true, res->has_header("Content-Range"));
  4937. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  4938. }
  4939. TEST_F(ServerTest, StaticFileRangeBigFile) {
  4940. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  4941. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4942. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4943. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4944. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  4945. EXPECT_EQ(true, res->has_header("Content-Range"));
  4946. EXPECT_EQ("bytes 1048571-1048575/1048576",
  4947. res->get_header_value("Content-Range"));
  4948. EXPECT_EQ("LAST\n", res->body);
  4949. }
  4950. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  4951. auto res =
  4952. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  4953. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4954. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4955. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4956. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  4957. EXPECT_EQ(true, res->has_header("Content-Range"));
  4958. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  4959. }
  4960. TEST_F(ServerTest, StaticFileBigFile) {
  4961. auto res = cli_.Get("/dir/1MB.txt");
  4962. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4963. EXPECT_EQ(StatusCode::OK_200, res->status);
  4964. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4965. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  4966. }
  4967. TEST_F(ServerTest, InvalidBaseDirMount) {
  4968. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  4969. }
  4970. TEST_F(ServerTest, Binary) {
  4971. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  4972. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  4973. "application/octet-stream");
  4974. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4975. ASSERT_EQ(StatusCode::OK_200, res->status);
  4976. ASSERT_EQ(4U, res->body.size());
  4977. res = cli_.Put("/binary", binary.data(), binary.size(),
  4978. "application/octet-stream");
  4979. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4980. ASSERT_EQ(StatusCode::OK_200, res->status);
  4981. ASSERT_EQ(4U, res->body.size());
  4982. res = cli_.Patch("/binary", binary.data(), binary.size(),
  4983. "application/octet-stream");
  4984. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4985. ASSERT_EQ(StatusCode::OK_200, res->status);
  4986. ASSERT_EQ(4U, res->body.size());
  4987. res = cli_.Delete("/binary", binary.data(), binary.size(),
  4988. "application/octet-stream");
  4989. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4990. ASSERT_EQ(StatusCode::OK_200, res->status);
  4991. ASSERT_EQ(4U, res->body.size());
  4992. }
  4993. TEST_F(ServerTest, BinaryString) {
  4994. auto binary = std::string("\x00\x01\x02\x03", 4);
  4995. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  4996. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4997. ASSERT_EQ(StatusCode::OK_200, res->status);
  4998. ASSERT_EQ(4U, res->body.size());
  4999. res = cli_.Put("/binary", binary, "application/octet-stream");
  5000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5001. ASSERT_EQ(StatusCode::OK_200, res->status);
  5002. ASSERT_EQ(4U, res->body.size());
  5003. res = cli_.Patch("/binary", binary, "application/octet-stream");
  5004. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5005. ASSERT_EQ(StatusCode::OK_200, res->status);
  5006. ASSERT_EQ(4U, res->body.size());
  5007. res = cli_.Delete("/binary", binary, "application/octet-stream");
  5008. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5009. ASSERT_EQ(StatusCode::OK_200, res->status);
  5010. ASSERT_EQ(4U, res->body.size());
  5011. }
  5012. TEST_F(ServerTest, EmptyRequest) {
  5013. auto res = cli_.Get("");
  5014. ASSERT_TRUE(!res);
  5015. EXPECT_EQ(Error::Connection, res.error());
  5016. }
  5017. TEST_F(ServerTest, LongRequest) {
  5018. std::string request;
  5019. for (size_t i = 0; i < 545; i++) {
  5020. request += "/TooLongRequest";
  5021. }
  5022. request += "OK";
  5023. auto res = cli_.Get(request.c_str());
  5024. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5025. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5026. }
  5027. TEST_F(ServerTest, TooLongRequest) {
  5028. std::string request;
  5029. for (size_t i = 0; i < 546; i++) {
  5030. request += "/TooLongRequest";
  5031. }
  5032. request += "_NG";
  5033. auto start = std::chrono::high_resolution_clock::now();
  5034. cli_.set_keep_alive(true);
  5035. auto res = cli_.Get(request.c_str());
  5036. auto end = std::chrono::high_resolution_clock::now();
  5037. auto elapsed =
  5038. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5039. .count();
  5040. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5041. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5042. EXPECT_LE(elapsed, 1000);
  5043. EXPECT_EQ("close", res->get_header_value("Connection"));
  5044. EXPECT_FALSE(cli_.is_socket_open());
  5045. }
  5046. TEST_F(ServerTest, AlmostTooLongRequest) {
  5047. // test for #2046 - URI length check shouldn't include other content on req
  5048. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  5049. // leading /, space, HTTP/1.1)
  5050. std::string request =
  5051. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  5052. auto res = cli_.Get(request.c_str());
  5053. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5054. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5055. }
  5056. TEST_F(ServerTest, LongHeader) {
  5057. Request req;
  5058. req.method = "GET";
  5059. req.path = "/hi";
  5060. std::string host_and_port;
  5061. host_and_port += HOST;
  5062. host_and_port += ":";
  5063. host_and_port += std::to_string(PORT);
  5064. req.headers.emplace("Host", host_and_port.c_str());
  5065. req.headers.emplace("Accept", "*/*");
  5066. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5067. req.headers.emplace(
  5068. "Header-Name",
  5069. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5070. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5071. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5072. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5073. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5074. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5075. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5076. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5077. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5078. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5079. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5080. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5081. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5082. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5083. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5084. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5085. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5086. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5087. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5088. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5089. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5090. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5091. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5092. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5093. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5094. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5095. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5096. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5097. "@@@@@@@@@@@@@@@@");
  5098. auto res = std::make_shared<Response>();
  5099. auto error = Error::Success;
  5100. auto ret = cli_.send(req, *res, error);
  5101. ASSERT_TRUE(ret);
  5102. EXPECT_EQ(StatusCode::OK_200, res->status);
  5103. }
  5104. TEST_F(ServerTest, LongQueryValue) {
  5105. auto start = std::chrono::high_resolution_clock::now();
  5106. cli_.set_keep_alive(true);
  5107. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  5108. auto end = std::chrono::high_resolution_clock::now();
  5109. auto elapsed =
  5110. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5111. .count();
  5112. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5113. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5114. EXPECT_LE(elapsed, 1000);
  5115. EXPECT_EQ("close", res->get_header_value("Connection"));
  5116. EXPECT_FALSE(cli_.is_socket_open());
  5117. }
  5118. TEST_F(ServerTest, TooLongQueryValue) {
  5119. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  5120. ASSERT_FALSE(res);
  5121. EXPECT_EQ(Error::Read, res.error());
  5122. }
  5123. TEST_F(ServerTest, TooLongHeader) {
  5124. Request req;
  5125. req.method = "GET";
  5126. req.path = "/hi";
  5127. std::string host_and_port;
  5128. host_and_port += HOST;
  5129. host_and_port += ":";
  5130. host_and_port += std::to_string(PORT);
  5131. req.headers.emplace("Host", host_and_port.c_str());
  5132. req.headers.emplace("Accept", "*/*");
  5133. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5134. req.headers.emplace(
  5135. "Header-Name",
  5136. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5137. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5138. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5139. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5140. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5141. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5142. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5143. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5144. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5145. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5146. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5147. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5148. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5149. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5150. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5151. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5152. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5153. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5154. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5155. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5156. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5157. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5158. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5159. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5160. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5161. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5162. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5163. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5164. "@@@@@@@@@@@@@@@@@");
  5165. auto res = std::make_shared<Response>();
  5166. auto error = Error::Success;
  5167. auto ret = cli_.send(req, *res, error);
  5168. ASSERT_TRUE(ret);
  5169. EXPECT_EQ(StatusCode::OK_200, res->status);
  5170. }
  5171. TEST_F(ServerTest, HeaderCountAtLimit) {
  5172. // Test with headers just under the 100 limit
  5173. httplib::Headers headers;
  5174. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  5175. // This should keep us just under the 100 header limit
  5176. for (int i = 0; i < 95; i++) {
  5177. std::string name = "X-Test-Header-" + std::to_string(i);
  5178. std::string value = "value" + std::to_string(i);
  5179. headers.emplace(name, value);
  5180. }
  5181. // This should work fine as we're under the limit
  5182. auto res = cli_.Get("/hi", headers);
  5183. EXPECT_TRUE(res);
  5184. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  5185. }
  5186. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  5187. // Test with many headers to exceed the 100 limit
  5188. httplib::Headers headers;
  5189. // Add 150 headers to definitely exceed the 100 limit
  5190. for (int i = 0; i < 150; i++) {
  5191. std::string name = "X-Test-Header-" + std::to_string(i);
  5192. std::string value = "value" + std::to_string(i);
  5193. headers.emplace(name, value);
  5194. }
  5195. // This should fail due to exceeding header count limit
  5196. cli_.set_keep_alive(true);
  5197. auto res = cli_.Get("/hi", headers);
  5198. // The server should respond with 400 Bad Request
  5199. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5200. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5201. EXPECT_EQ("close", res->get_header_value("Connection"));
  5202. EXPECT_FALSE(cli_.is_socket_open());
  5203. }
  5204. TEST_F(ServerTest, PercentEncoding) {
  5205. auto res = cli_.Get("/e%6edwith%");
  5206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5207. EXPECT_EQ(StatusCode::OK_200, res->status);
  5208. }
  5209. TEST_F(ServerTest, PercentEncodingUnicode) {
  5210. auto res = cli_.Get("/e%u006edwith%");
  5211. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5212. EXPECT_EQ(StatusCode::OK_200, res->status);
  5213. }
  5214. TEST_F(ServerTest, InvalidPercentEncoding) {
  5215. auto res = cli_.Get("/%endwith%");
  5216. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5217. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5218. }
  5219. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  5220. auto res = cli_.Get("/%uendwith%");
  5221. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5222. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5223. }
  5224. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  5225. auto res = cli_.Get("/hello?aaa=bbb%");
  5226. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5227. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5228. }
  5229. TEST_F(ServerTest, PlusSignEncoding) {
  5230. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  5231. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5232. EXPECT_EQ(StatusCode::OK_200, res->status);
  5233. EXPECT_EQ("a +b", res->body);
  5234. }
  5235. TEST_F(ServerTest, HeaderCountSecurityTest) {
  5236. // This test simulates a potential DoS attack using many headers
  5237. // to verify our security fix prevents memory exhaustion
  5238. httplib::Headers attack_headers;
  5239. // Attempt to add many headers like an attacker would (200 headers to far
  5240. // exceed limit)
  5241. for (int i = 0; i < 200; i++) {
  5242. std::string name = "X-Attack-Header-" + std::to_string(i);
  5243. std::string value = "attack_payload_" + std::to_string(i);
  5244. attack_headers.emplace(name, value);
  5245. }
  5246. // Try to POST with excessive headers
  5247. cli_.set_keep_alive(true);
  5248. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  5249. // Should either fail or return 400 Bad Request due to security limit
  5250. if (res) {
  5251. // If we get a response, it should be 400 Bad Request
  5252. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5253. EXPECT_EQ("close", res->get_header_value("Connection"));
  5254. }
  5255. EXPECT_FALSE(cli_.is_socket_open());
  5256. }
  5257. TEST_F(ServerTest, MultipartFormData) {
  5258. UploadFormDataItems items = {
  5259. {"text1", "text default", "", ""},
  5260. {"text2", "aωb", "", ""},
  5261. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5262. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  5263. {"file3", "", "", "application/octet-stream"},
  5264. {"file4", "", "", " application/json tmp-string "}};
  5265. auto res = cli_.Post("/multipart", items);
  5266. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5267. EXPECT_EQ(StatusCode::OK_200, res->status);
  5268. }
  5269. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  5270. UploadFormDataItems items = {
  5271. {"text", "default text", "", ""},
  5272. {"multi_text1", "aaaaa", "", ""},
  5273. {"multi_text1", "bbbbb", "", ""},
  5274. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5275. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  5276. "application/json"},
  5277. };
  5278. auto res = cli_.Post("/multipart/multi_file_values", items);
  5279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5280. EXPECT_EQ(StatusCode::OK_200, res->status);
  5281. }
  5282. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  5283. auto res = cli_.Get("/hi");
  5284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5285. EXPECT_EQ(StatusCode::OK_200, res->status);
  5286. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  5287. EXPECT_EQ("Hello World!", res->body);
  5288. }
  5289. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  5290. Request req;
  5291. req.method = "POST";
  5292. req.path = "/chunked";
  5293. std::string host_and_port;
  5294. host_and_port += HOST;
  5295. host_and_port += ":";
  5296. host_and_port += std::to_string(PORT);
  5297. req.headers.emplace("Host", host_and_port.c_str());
  5298. req.headers.emplace("Accept", "*/*");
  5299. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5300. req.headers.emplace("Content-Type", "text/plain");
  5301. req.headers.emplace("Content-Length", "0");
  5302. req.headers.emplace(
  5303. "Transfer-Encoding",
  5304. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  5305. // Client does not chunk, so make a chunked body manually.
  5306. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  5307. auto res = std::make_shared<Response>();
  5308. auto error = Error::Success;
  5309. auto ret = cli_.send(req, *res, error);
  5310. ASSERT_TRUE(ret);
  5311. EXPECT_EQ(StatusCode::OK_200, res->status);
  5312. }
  5313. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  5314. // rather than treat them as valid lengths.
  5315. template <typename ClientT>
  5316. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  5317. Request req;
  5318. req.method = "POST";
  5319. req.path = "/chunked";
  5320. std::string host_and_port;
  5321. host_and_port += HOST;
  5322. host_and_port += ":";
  5323. host_and_port += std::to_string(PORT);
  5324. req.headers.emplace("Host", host_and_port.c_str());
  5325. req.headers.emplace("Content-Length", "0");
  5326. req.headers.emplace("Transfer-Encoding", "chunked");
  5327. req.body = body;
  5328. auto res = std::make_shared<Response>();
  5329. auto error = Error::Success;
  5330. ASSERT_TRUE(cli.send(req, *res, error));
  5331. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5332. }
  5333. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  5334. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  5335. }
  5336. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  5337. expect_chunked_body_rejected(
  5338. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  5339. }
  5340. TEST_F(ServerTest, GetStreamed2) {
  5341. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  5342. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5343. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5344. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5345. EXPECT_EQ(true, res->has_header("Content-Range"));
  5346. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  5347. EXPECT_EQ(std::string("ab"), res->body);
  5348. }
  5349. TEST_F(ServerTest, GetStreamed) {
  5350. auto res = cli_.Get("/streamed");
  5351. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5352. EXPECT_EQ(StatusCode::OK_200, res->status);
  5353. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5354. EXPECT_EQ(std::string("aaabbb"), res->body);
  5355. }
  5356. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  5357. auto res = cli_.Get("/streamed-without-length",
  5358. Headers{make_range_header({{0, -1}})});
  5359. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5360. EXPECT_EQ(StatusCode::OK_200, res->status);
  5361. EXPECT_EQ(false, res->has_header("Content-Length"));
  5362. EXPECT_EQ(false, res->has_header("Content-Range"));
  5363. EXPECT_EQ(std::string("abcdefg"), res->body);
  5364. }
  5365. TEST_F(ServerTest, GetStreamedWithRange1) {
  5366. auto res =
  5367. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  5368. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5369. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5370. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5371. EXPECT_EQ(true, res->has_header("Content-Range"));
  5372. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  5373. EXPECT_EQ(std::string("def"), res->body);
  5374. }
  5375. TEST_F(ServerTest, GetStreamedWithRange2) {
  5376. auto res =
  5377. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  5378. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5379. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5380. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5381. EXPECT_EQ(true, res->has_header("Content-Range"));
  5382. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  5383. EXPECT_EQ(std::string("bcdefg"), res->body);
  5384. }
  5385. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  5386. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  5387. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5388. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5389. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5390. EXPECT_EQ(true, res->has_header("Content-Range"));
  5391. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  5392. EXPECT_EQ(std::string("efg"), res->body);
  5393. }
  5394. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  5395. auto res =
  5396. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-9999"}});
  5397. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5398. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5399. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5400. EXPECT_EQ(false, res->has_header("Content-Range"));
  5401. EXPECT_EQ(0U, res->body.size());
  5402. }
  5403. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  5404. // Only a 206 is served as a partial representation. Under any other status
  5405. // `apply_ranges()` reported the full content length, so the body must match
  5406. // that header, and the content provider must never be asked for an offset
  5407. // outside the representation.
  5408. auto check = [&](int status, const char *range) {
  5409. auto path =
  5410. std::string("/streamed-with-range?status=") + std::to_string(status);
  5411. auto ctx = path + " Range: " + range;
  5412. auto res = cli_.Get(path, Headers{{"Range", range}});
  5413. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  5414. EXPECT_EQ(status, res->status) << ctx;
  5415. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  5416. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  5417. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  5418. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  5419. };
  5420. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  5421. check(403, "bytes=3-5");
  5422. // The offset is far past the representation.
  5423. check(403, "bytes=100000-100200");
  5424. // `first_pos` is still -1 here, and the bounds asserts in
  5425. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  5426. check(403, "bytes=-3");
  5427. // `apply_ranges()` makes no boundary for a non-206 response, so the
  5428. // multipart branch would have written one that is empty.
  5429. check(403, "bytes=1-2, 4-5");
  5430. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  5431. // covers the whole representation.
  5432. check(200, "bytes=3-5");
  5433. check(200, "bytes=1-2, 4-5");
  5434. }
  5435. TEST_F(ServerTest, GetStreamedWithRangeError) {
  5436. auto res =
  5437. cli_.Get("/streamed-with-range",
  5438. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  5439. "92233720368547758079223372036854775807"}});
  5440. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5441. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5442. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5443. EXPECT_EQ(false, res->has_header("Content-Range"));
  5444. EXPECT_EQ(0U, res->body.size());
  5445. }
  5446. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  5447. auto res = cli_.Get(
  5448. "/with-range",
  5449. Headers{{"Range",
  5450. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  5451. {"Accept-Encoding", ""}});
  5452. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5453. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5454. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  5455. EXPECT_EQ(true, res->has_header("Content-Range"));
  5456. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  5457. EXPECT_EQ(std::string("abcdefg"), res->body);
  5458. }
  5459. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  5460. auto res = cli_.Get("/with-range", Headers{
  5461. {"Range", "bytes=0-"},
  5462. {"Accept-Encoding", ""},
  5463. });
  5464. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5465. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5466. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  5467. EXPECT_EQ(true, res->has_header("Content-Range"));
  5468. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  5469. EXPECT_EQ(std::string("abcdefg"), res->body);
  5470. }
  5471. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  5472. auto res = cli_.Get("/streamed-with-range",
  5473. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5474. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5475. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5476. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  5477. EXPECT_EQ(false, res->has_header("Content-Range"));
  5478. EXPECT_EQ(267U, res->body.size());
  5479. // Check that both range contents are present
  5480. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  5481. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  5482. // Check that Content-Range headers are present for both ranges
  5483. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  5484. std::string::npos);
  5485. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  5486. std::string::npos);
  5487. }
  5488. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  5489. Ranges ranges;
  5490. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  5491. ranges.emplace_back(0, -1);
  5492. }
  5493. auto res = cli_.Get("/streamed-with-range?error",
  5494. Headers{{make_range_header(ranges)}});
  5495. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5496. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5497. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5498. EXPECT_EQ(false, res->has_header("Content-Range"));
  5499. EXPECT_EQ(0U, res->body.size());
  5500. }
  5501. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  5502. auto res = cli_.Get("/streamed-with-range",
  5503. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  5504. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5505. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5506. EXPECT_EQ(5U, res->body.size());
  5507. // Check that overlapping ranges are coalesced into a single range
  5508. EXPECT_EQ("bcdef", res->body);
  5509. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  5510. // Should be single range, not multipart
  5511. EXPECT_TRUE(res->has_header("Content-Range"));
  5512. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5513. }
  5514. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  5515. auto res = cli_.Get("/streamed-with-range",
  5516. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  5517. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5518. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5519. EXPECT_EQ(268U, res->body.size());
  5520. // Check that both range contents are present
  5521. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  5522. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  5523. // Check that Content-Range headers are present for both ranges
  5524. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  5525. std::string::npos);
  5526. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  5527. std::string::npos);
  5528. }
  5529. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  5530. auto res = cli_.Get("/streamed-with-range",
  5531. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  5532. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5533. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5534. EXPECT_EQ(269U, res->body.size());
  5535. // Check that both duplicate range contents are present
  5536. size_t first_abc = res->body.find("abc\r\n");
  5537. EXPECT_TRUE(first_abc != std::string::npos);
  5538. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  5539. EXPECT_TRUE(second_abc != std::string::npos);
  5540. // Check that Content-Range headers are present for both ranges
  5541. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  5542. EXPECT_TRUE(first_range != std::string::npos);
  5543. size_t second_range =
  5544. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  5545. EXPECT_TRUE(second_range != std::string::npos);
  5546. }
  5547. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  5548. auto res =
  5549. cli_.Get("/streamed-with-range?error",
  5550. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  5551. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5552. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5553. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5554. EXPECT_EQ(false, res->has_header("Content-Range"));
  5555. EXPECT_EQ(0U, res->body.size());
  5556. }
  5557. TEST_F(ServerTest, GetStreamedEndless) {
  5558. uint64_t offset = 0;
  5559. auto res = cli_.Get("/streamed-cancel",
  5560. [&](const char * /*data*/, uint64_t data_length) {
  5561. if (offset < 100) {
  5562. offset += data_length;
  5563. return true;
  5564. }
  5565. return false;
  5566. });
  5567. ASSERT_TRUE(!res);
  5568. EXPECT_EQ(Error::Canceled, res.error());
  5569. }
  5570. TEST_F(ServerTest, ClientStop) {
  5571. std::atomic_size_t count{4};
  5572. std::vector<std::thread> threads;
  5573. for (auto i = count.load(); i != 0; --i) {
  5574. threads.emplace_back([&]() {
  5575. auto res = cli_.Get("/streamed-cancel",
  5576. [&](const char *, uint64_t) { return true; });
  5577. --count;
  5578. ASSERT_TRUE(!res);
  5579. EXPECT_TRUE(res.error() == Error::Canceled ||
  5580. res.error() == Error::Read || res.error() == Error::Write);
  5581. });
  5582. }
  5583. std::this_thread::sleep_for(std::chrono::seconds(2));
  5584. while (count != 0) {
  5585. cli_.stop();
  5586. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  5587. }
  5588. for (auto &t : threads) {
  5589. t.join();
  5590. }
  5591. }
  5592. TEST_F(ServerTest, GetWithRange1) {
  5593. auto res = cli_.Get("/with-range", Headers{
  5594. make_range_header({{3, 5}}),
  5595. {"Accept-Encoding", ""},
  5596. });
  5597. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5598. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5599. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5600. EXPECT_EQ(true, res->has_header("Content-Range"));
  5601. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  5602. EXPECT_EQ(std::string("def"), res->body);
  5603. }
  5604. TEST_F(ServerTest, GetWithRange2) {
  5605. auto res = cli_.Get("/with-range", Headers{
  5606. make_range_header({{1, -1}}),
  5607. {"Accept-Encoding", ""},
  5608. });
  5609. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5610. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5611. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5612. EXPECT_EQ(true, res->has_header("Content-Range"));
  5613. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  5614. EXPECT_EQ(std::string("bcdefg"), res->body);
  5615. }
  5616. TEST_F(ServerTest, GetWithRange3) {
  5617. auto res = cli_.Get("/with-range", Headers{
  5618. make_range_header({{0, 0}}),
  5619. {"Accept-Encoding", ""},
  5620. });
  5621. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5622. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5623. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  5624. EXPECT_EQ(true, res->has_header("Content-Range"));
  5625. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  5626. EXPECT_EQ(std::string("a"), res->body);
  5627. }
  5628. TEST_F(ServerTest, GetWithRange4) {
  5629. auto res = cli_.Get("/with-range", Headers{
  5630. make_range_header({{-1, 2}}),
  5631. {"Accept-Encoding", ""},
  5632. });
  5633. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5634. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5635. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5636. EXPECT_EQ(true, res->has_header("Content-Range"));
  5637. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  5638. EXPECT_EQ(std::string("fg"), res->body);
  5639. }
  5640. TEST_F(ServerTest, GetWithRange5) {
  5641. auto res = cli_.Get("/with-range", Headers{
  5642. make_range_header({{0, 5}}),
  5643. {"Accept-Encoding", ""},
  5644. });
  5645. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5646. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5647. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5648. EXPECT_EQ(true, res->has_header("Content-Range"));
  5649. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  5650. EXPECT_EQ(std::string("abcdef"), res->body);
  5651. }
  5652. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  5653. auto res =
  5654. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  5655. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5656. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5657. }
  5658. TEST_F(ServerTest, GetWithRangeMultipart) {
  5659. auto res =
  5660. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5661. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5662. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5663. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  5664. EXPECT_EQ(false, res->has_header("Content-Range"));
  5665. EXPECT_EQ(267U, res->body.size());
  5666. }
  5667. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  5668. auto res = cli_.Get("/with-range",
  5669. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  5670. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5671. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5672. }
  5673. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  5674. auto res = cli_.Get("/with-range-customized-response",
  5675. Headers{{make_range_header({{1, 2}})}});
  5676. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5677. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5678. EXPECT_EQ(true, res->has_header("Content-Length"));
  5679. EXPECT_EQ(false, res->has_header("Content-Range"));
  5680. EXPECT_EQ(JSON_DATA, res->body);
  5681. }
  5682. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  5683. auto res = cli_.Get("/with-range-customized-response",
  5684. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5685. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5686. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5687. EXPECT_EQ(true, res->has_header("Content-Length"));
  5688. EXPECT_EQ(false, res->has_header("Content-Range"));
  5689. EXPECT_EQ(JSON_DATA, res->body);
  5690. }
  5691. TEST_F(ServerTest, Issue1772) {
  5692. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  5693. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5694. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  5695. }
  5696. TEST_F(ServerTest, Issue609) {
  5697. auto res = cli_.Delete("/issue609");
  5698. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5699. EXPECT_EQ(StatusCode::OK_200, res->status);
  5700. EXPECT_EQ(std::string("ok"), res->body);
  5701. }
  5702. TEST_F(ServerTest, GetStreamedChunked) {
  5703. auto res = cli_.Get("/streamed-chunked");
  5704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5705. EXPECT_EQ(StatusCode::OK_200, res->status);
  5706. EXPECT_EQ(std::string("123456789"), res->body);
  5707. }
  5708. TEST_F(ServerTest, GetStreamedChunked2) {
  5709. auto res = cli_.Get("/streamed-chunked2");
  5710. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5711. EXPECT_EQ(StatusCode::OK_200, res->status);
  5712. EXPECT_EQ(std::string("123456789"), res->body);
  5713. }
  5714. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  5715. auto res = cli_.Get("/streamed-chunked-with-trailer");
  5716. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5717. EXPECT_EQ(StatusCode::OK_200, res->status);
  5718. EXPECT_EQ(std::string("123456789"), res->body);
  5719. EXPECT_TRUE(res->has_header("Trailer"));
  5720. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  5721. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  5722. // Trailers are now stored separately from headers (security fix)
  5723. EXPECT_EQ(2U, res->trailers.size());
  5724. EXPECT_TRUE(res->has_trailer("Dummy1"));
  5725. EXPECT_TRUE(res->has_trailer("Dummy2"));
  5726. EXPECT_FALSE(res->has_trailer("Dummy3"));
  5727. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  5728. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  5729. // Verify trailers are NOT in headers (security verification)
  5730. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  5731. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  5732. }
  5733. TEST_F(ServerTest, LargeChunkedPost) {
  5734. Request req;
  5735. req.method = "POST";
  5736. req.path = "/large-chunked";
  5737. std::string host_and_port;
  5738. host_and_port += HOST;
  5739. host_and_port += ":";
  5740. host_and_port += std::to_string(PORT);
  5741. req.headers.emplace("Host", host_and_port.c_str());
  5742. req.headers.emplace("Accept", "*/*");
  5743. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5744. req.headers.emplace("Content-Type", "text/plain");
  5745. req.headers.emplace("Content-Length", "0");
  5746. req.headers.emplace("Transfer-Encoding", "chunked");
  5747. std::string long_string(30 * 1024u, 'a');
  5748. std::string chunk = "7800\r\n" + long_string + "\r\n";
  5749. // Attempt to make a large enough post to exceed OS buffers, to test that
  5750. // the server handles short reads if the full chunk data isn't available.
  5751. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  5752. auto res = std::make_shared<Response>();
  5753. auto error = Error::Success;
  5754. auto ret = cli_.send(req, *res, error);
  5755. ASSERT_TRUE(ret);
  5756. EXPECT_EQ(StatusCode::OK_200, res->status);
  5757. }
  5758. TEST_F(ServerTest, GetMethodRemoteAddr) {
  5759. auto res = cli_.Get("/remote_addr");
  5760. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5761. EXPECT_EQ(StatusCode::OK_200, res->status);
  5762. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5763. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  5764. }
  5765. TEST_F(ServerTest, GetMethodLocalAddr) {
  5766. auto res = cli_.Get("/local_addr");
  5767. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5768. EXPECT_EQ(StatusCode::OK_200, res->status);
  5769. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5770. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  5771. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  5772. }
  5773. TEST_F(ServerTest, HTTPResponseSplitting) {
  5774. auto res = cli_.Get("/http_response_splitting");
  5775. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5776. EXPECT_EQ(StatusCode::OK_200, res->status);
  5777. }
  5778. TEST_F(ServerTest, SlowRequest) {
  5779. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5780. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5781. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5782. }
  5783. #if 0
  5784. TEST_F(ServerTest, SlowPost) {
  5785. char buffer[64 * 1024];
  5786. memset(buffer, 0x42, sizeof(buffer));
  5787. auto res = cli_.Post(
  5788. "/slowpost", 64 * 1024 * 1024,
  5789. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5790. auto ret = sink.write(buffer, sizeof(buffer));
  5791. EXPECT_TRUE(ret);
  5792. return true;
  5793. },
  5794. "text/plain");
  5795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5796. EXPECT_EQ(StatusCode::OK_200, res->status);
  5797. }
  5798. TEST_F(ServerTest, SlowPostFail) {
  5799. char buffer[64 * 1024];
  5800. memset(buffer, 0x42, sizeof(buffer));
  5801. cli_.set_write_timeout(std::chrono::seconds(0));
  5802. auto res = cli_.Post(
  5803. "/slowpost", 64 * 1024 * 1024,
  5804. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5805. sink.write(buffer, sizeof(buffer));
  5806. return true;
  5807. },
  5808. "text/plain");
  5809. ASSERT_TRUE(!res);
  5810. EXPECT_EQ(Error::Write, res.error());
  5811. }
  5812. #endif
  5813. TEST_F(ServerTest, Put) {
  5814. auto res = cli_.Put("/put", "PUT", "text/plain");
  5815. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5816. EXPECT_EQ(StatusCode::OK_200, res->status);
  5817. EXPECT_EQ("PUT", res->body);
  5818. }
  5819. TEST_F(ServerTest, PutWithContentProvider) {
  5820. auto res = cli_.Put(
  5821. "/put", 3,
  5822. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5823. sink.os << "PUT";
  5824. return true;
  5825. },
  5826. "text/plain");
  5827. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5828. EXPECT_EQ(StatusCode::OK_200, res->status);
  5829. EXPECT_EQ("PUT", res->body);
  5830. }
  5831. TEST_F(ServerTest, PostWithContentProviderAbort) {
  5832. auto res = cli_.Post(
  5833. "/post", 42,
  5834. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  5835. return false;
  5836. },
  5837. "text/plain");
  5838. ASSERT_TRUE(!res);
  5839. EXPECT_EQ(Error::Canceled, res.error());
  5840. }
  5841. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  5842. auto res = cli_.Put(
  5843. "/put",
  5844. [](size_t /*offset*/, DataSink &sink) {
  5845. sink.os << "PUT";
  5846. sink.done();
  5847. return true;
  5848. },
  5849. "text/plain");
  5850. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5851. EXPECT_EQ(StatusCode::OK_200, res->status);
  5852. EXPECT_EQ("PUT", res->body);
  5853. }
  5854. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  5855. auto res = cli_.Post(
  5856. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  5857. "text/plain");
  5858. ASSERT_TRUE(!res);
  5859. EXPECT_EQ(Error::Canceled, res.error());
  5860. }
  5861. TEST_F(ServerTest, PostLoopBack) {
  5862. std::string body;
  5863. auto res = cli_.Post(
  5864. "/post-loopback", 9,
  5865. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5866. EXPECT_EQ(9u, length);
  5867. sink.write("123", 3);
  5868. sink.write("456", 3);
  5869. sink.write("789", 3);
  5870. return true;
  5871. },
  5872. "text/plain",
  5873. [&body](const char *data, size_t data_length) {
  5874. body.append(data, data_length);
  5875. return true;
  5876. });
  5877. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5878. EXPECT_EQ(StatusCode::OK_200, res->status);
  5879. EXPECT_EQ("123456789", body);
  5880. }
  5881. TEST_F(ServerTest, PutLoopBack) {
  5882. std::string body;
  5883. auto res = cli_.Put(
  5884. "/put-loopback", 9,
  5885. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5886. EXPECT_EQ(9u, length);
  5887. sink.write("123", 3);
  5888. sink.write("456", 3);
  5889. sink.write("789", 3);
  5890. return true;
  5891. },
  5892. "text/plain",
  5893. [&body](const char *data, size_t data_length) {
  5894. body.append(data, data_length);
  5895. return true;
  5896. });
  5897. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5898. EXPECT_EQ(StatusCode::OK_200, res->status);
  5899. EXPECT_EQ("123456789", body);
  5900. }
  5901. TEST_F(ServerTest, PatchLoopBack) {
  5902. std::string body;
  5903. auto res = cli_.Patch(
  5904. "/patch-loopback", 9,
  5905. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5906. EXPECT_EQ(9u, length);
  5907. sink.write("123", 3);
  5908. sink.write("456", 3);
  5909. sink.write("789", 3);
  5910. return true;
  5911. },
  5912. "text/plain",
  5913. [&body](const char *data, size_t data_length) {
  5914. body.append(data, data_length);
  5915. return true;
  5916. });
  5917. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5918. EXPECT_EQ(StatusCode::OK_200, res->status);
  5919. EXPECT_EQ("123456789", body);
  5920. }
  5921. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  5922. std::string body;
  5923. auto res = cli_.Post(
  5924. "/post-loopback",
  5925. [](size_t /*offset*/, DataSink &sink) {
  5926. sink.write("123", 3);
  5927. sink.write("456", 3);
  5928. sink.write("789", 3);
  5929. sink.done();
  5930. return true;
  5931. },
  5932. "text/plain",
  5933. [&body](const char *data, size_t data_length) {
  5934. body.append(data, data_length);
  5935. return true;
  5936. });
  5937. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5938. EXPECT_EQ(StatusCode::OK_200, res->status);
  5939. EXPECT_EQ("123456789", body);
  5940. }
  5941. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5942. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  5943. cli_.set_compress(true);
  5944. auto res = cli_.Put(
  5945. "/put", 3,
  5946. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5947. sink.os << "PUT";
  5948. return true;
  5949. },
  5950. "text/plain");
  5951. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5952. EXPECT_EQ(StatusCode::OK_200, res->status);
  5953. EXPECT_EQ("PUT", res->body);
  5954. }
  5955. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  5956. cli_.set_compress(true);
  5957. auto res = cli_.Post(
  5958. "/post", 42,
  5959. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  5960. return false;
  5961. },
  5962. "text/plain");
  5963. ASSERT_TRUE(!res);
  5964. EXPECT_EQ(Error::Canceled, res.error());
  5965. }
  5966. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  5967. cli_.set_compress(true);
  5968. auto res = cli_.Put(
  5969. "/put",
  5970. [](size_t /*offset*/, DataSink &sink) {
  5971. sink.os << "PUT";
  5972. sink.done();
  5973. return true;
  5974. },
  5975. "text/plain");
  5976. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5977. EXPECT_EQ(StatusCode::OK_200, res->status);
  5978. EXPECT_EQ("PUT", res->body);
  5979. }
  5980. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  5981. cli_.set_compress(true);
  5982. auto res = cli_.Post(
  5983. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  5984. "text/plain");
  5985. ASSERT_TRUE(!res);
  5986. EXPECT_EQ(Error::Canceled, res.error());
  5987. }
  5988. TEST_F(ServerTest, PutLargeFileWithGzip) {
  5989. cli_.set_compress(true);
  5990. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  5991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5992. EXPECT_EQ(StatusCode::OK_200, res->status);
  5993. EXPECT_EQ(LARGE_DATA, res->body);
  5994. }
  5995. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  5996. #ifdef CPPHTTPLIB_SSL_ENABLED
  5997. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  5998. Client cli(s.c_str());
  5999. cli.enable_server_certificate_verification(false);
  6000. #else
  6001. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  6002. Client cli(s.c_str());
  6003. #endif
  6004. cli.set_compress(true);
  6005. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  6006. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6007. EXPECT_EQ(StatusCode::OK_200, res->status);
  6008. EXPECT_EQ(LARGE_DATA, res->body);
  6009. // The compressed size should be less than a 10th of the original. May vary
  6010. // depending on the zlib library.
  6011. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  6012. static_cast<uint64_t>(10 * 1024 * 1024));
  6013. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6014. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6015. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  6016. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  6017. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  6018. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  6019. #endif
  6020. }
  6021. TEST_F(ServerTest, PutContentWithDeflate) {
  6022. cli_.set_compress(false);
  6023. Headers headers;
  6024. headers.emplace("Content-Encoding", "deflate");
  6025. // PUT in deflate format:
  6026. auto res = cli_.Put("/put", headers,
  6027. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  6028. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6029. EXPECT_EQ(StatusCode::OK_200, res->status);
  6030. EXPECT_EQ("PUT", res->body);
  6031. }
  6032. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  6033. Headers headers;
  6034. headers.emplace("Accept-Encoding", "gzip, deflate");
  6035. auto res = cli_.Get("/streamed-chunked", headers);
  6036. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6037. EXPECT_EQ(StatusCode::OK_200, res->status);
  6038. EXPECT_EQ(std::string("123456789"), res->body);
  6039. }
  6040. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  6041. Headers headers;
  6042. headers.emplace("Accept-Encoding", "gzip, deflate");
  6043. auto res = cli_.Get("/streamed-chunked2", headers);
  6044. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6045. EXPECT_EQ(StatusCode::OK_200, res->status);
  6046. EXPECT_EQ(std::string("123456789"), res->body);
  6047. }
  6048. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  6049. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  6050. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6051. EXPECT_EQ(StatusCode::OK_200, res->status);
  6052. }
  6053. TEST(GzipDecompressor, ChunkedDecompression) {
  6054. std::string data;
  6055. for (size_t i = 0; i < 32 * 1024; ++i) {
  6056. data.push_back(static_cast<char>('a' + i % 26));
  6057. }
  6058. std::string compressed_data;
  6059. {
  6060. httplib::detail::gzip_compressor compressor;
  6061. bool result = compressor.compress(
  6062. data.data(), data.size(),
  6063. /*last=*/true,
  6064. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  6065. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  6066. compressed_data_size);
  6067. return true;
  6068. });
  6069. ASSERT_TRUE(result);
  6070. }
  6071. std::string decompressed_data;
  6072. {
  6073. httplib::detail::gzip_decompressor decompressor;
  6074. // Chunk size is chosen specifically to have a decompressed chunk size equal
  6075. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  6076. size_t chunk_size = 130;
  6077. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  6078. chunk_begin += chunk_size) {
  6079. size_t current_chunk_size =
  6080. std::min(compressed_data.size() - chunk_begin, chunk_size);
  6081. bool result = decompressor.decompress(
  6082. compressed_data.data() + chunk_begin, current_chunk_size,
  6083. [&](const char *decompressed_data_chunk,
  6084. size_t decompressed_data_chunk_size) {
  6085. decompressed_data.insert(decompressed_data.size(),
  6086. decompressed_data_chunk,
  6087. decompressed_data_chunk_size);
  6088. return true;
  6089. });
  6090. ASSERT_TRUE(result);
  6091. }
  6092. }
  6093. ASSERT_EQ(data, decompressed_data);
  6094. }
  6095. TEST(GzipDecompressor, DeflateDecompression) {
  6096. std::string original_text = "Raw deflate without gzip";
  6097. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6098. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6099. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6100. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  6101. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6102. std::string decompressed_data;
  6103. {
  6104. httplib::detail::gzip_decompressor decompressor;
  6105. bool result = decompressor.decompress(
  6106. compressed_data.data(), compressed_data.size(),
  6107. [&](const char *decompressed_data_chunk,
  6108. size_t decompressed_data_chunk_size) {
  6109. decompressed_data.insert(decompressed_data.size(),
  6110. decompressed_data_chunk,
  6111. decompressed_data_chunk_size);
  6112. return true;
  6113. });
  6114. ASSERT_TRUE(result);
  6115. }
  6116. ASSERT_EQ(original_text, decompressed_data);
  6117. }
  6118. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  6119. std::string original_text = "Raw deflate without gzip";
  6120. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6121. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6122. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6123. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  6124. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  6125. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6126. std::string decompressed_data;
  6127. {
  6128. httplib::detail::gzip_decompressor decompressor;
  6129. bool result = decompressor.decompress(
  6130. compressed_data.data(), compressed_data.size(),
  6131. [&](const char *decompressed_data_chunk,
  6132. size_t decompressed_data_chunk_size) {
  6133. decompressed_data.insert(decompressed_data.size(),
  6134. decompressed_data_chunk,
  6135. decompressed_data_chunk_size);
  6136. return true;
  6137. });
  6138. ASSERT_TRUE(result);
  6139. }
  6140. ASSERT_EQ(original_text, decompressed_data);
  6141. }
  6142. #endif
  6143. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6144. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  6145. Headers headers;
  6146. headers.emplace("Accept-Encoding", "br");
  6147. auto res = cli_.Get("/streamed-chunked", headers);
  6148. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6149. EXPECT_EQ(StatusCode::OK_200, res->status);
  6150. EXPECT_EQ(std::string("123456789"), res->body);
  6151. }
  6152. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  6153. Headers headers;
  6154. headers.emplace("Accept-Encoding", "br");
  6155. auto res = cli_.Get("/streamed-chunked2", headers);
  6156. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6157. EXPECT_EQ(StatusCode::OK_200, res->status);
  6158. EXPECT_EQ(std::string("123456789"), res->body);
  6159. }
  6160. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  6161. cli_.set_compress(true);
  6162. auto res = cli_.Put(
  6163. "/put", 3,
  6164. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6165. sink.os << "PUT";
  6166. return true;
  6167. },
  6168. "text/plain");
  6169. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6170. EXPECT_EQ(StatusCode::OK_200, res->status);
  6171. EXPECT_EQ("PUT", res->body);
  6172. }
  6173. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  6174. cli_.set_compress(true);
  6175. auto res = cli_.Put(
  6176. "/put",
  6177. [](size_t /*offset*/, DataSink &sink) {
  6178. sink.os << "PUT";
  6179. sink.done();
  6180. return true;
  6181. },
  6182. "text/plain");
  6183. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6184. EXPECT_EQ(StatusCode::OK_200, res->status);
  6185. EXPECT_EQ("PUT", res->body);
  6186. }
  6187. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  6188. cli_.set_compress(true);
  6189. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6190. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6191. EXPECT_EQ(StatusCode::OK_200, res->status);
  6192. EXPECT_EQ(LARGE_DATA, res->body);
  6193. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6194. }
  6195. #endif
  6196. TEST_F(ServerTest, Patch) {
  6197. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  6198. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6199. EXPECT_EQ(StatusCode::OK_200, res->status);
  6200. EXPECT_EQ("PATCH", res->body);
  6201. }
  6202. TEST_F(ServerTest, Delete) {
  6203. auto res = cli_.Delete("/delete");
  6204. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6205. EXPECT_EQ(StatusCode::OK_200, res->status);
  6206. EXPECT_EQ("DELETE", res->body);
  6207. }
  6208. TEST_F(ServerTest, DeleteContentReceiver) {
  6209. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  6210. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6211. EXPECT_EQ(StatusCode::OK_200, res->status);
  6212. EXPECT_EQ("content", res->body);
  6213. }
  6214. TEST_F(ServerTest, Options) {
  6215. auto res = cli_.Options("*");
  6216. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6217. EXPECT_EQ(StatusCode::OK_200, res->status);
  6218. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  6219. EXPECT_TRUE(res->body.empty());
  6220. }
  6221. TEST_F(ServerTest, URL) {
  6222. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  6223. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6224. EXPECT_EQ(StatusCode::OK_200, res->status);
  6225. }
  6226. TEST_F(ServerTest, ArrayParam) {
  6227. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  6228. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6229. EXPECT_EQ(StatusCode::OK_200, res->status);
  6230. }
  6231. TEST_F(ServerTest, ArrayParamValues) {
  6232. auto res =
  6233. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  6234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6235. EXPECT_EQ(StatusCode::OK_200, res->status);
  6236. }
  6237. TEST_F(ServerTest, NoMultipleHeaders) {
  6238. Headers headers = {{"Content-Length", "5"}};
  6239. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  6240. "text/plain");
  6241. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6242. EXPECT_EQ(StatusCode::OK_200, res->status);
  6243. }
  6244. TEST_F(ServerTest, PostContentReceiver) {
  6245. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  6246. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6247. ASSERT_EQ(StatusCode::OK_200, res->status);
  6248. ASSERT_EQ("content", res->body);
  6249. }
  6250. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  6251. UploadFormDataItems items = {
  6252. {"text1", "text default", "", ""},
  6253. {"text2", "aωb", "", ""},
  6254. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6255. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  6256. {"file3", "", "", "application/octet-stream"},
  6257. };
  6258. auto res = cli_.Post("/content_receiver", items);
  6259. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6260. EXPECT_EQ(StatusCode::OK_200, res->status);
  6261. }
  6262. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  6263. UploadFormDataItems items = {
  6264. {"text1", "text default", "", ""},
  6265. {"text2", "aωb", "", ""},
  6266. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6267. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  6268. {"file3", "", "", "application/octet-stream"},
  6269. };
  6270. auto boundary = std::string("+++++");
  6271. std::string body;
  6272. for (const auto &item : items) {
  6273. body += "--" + boundary + "\r\n";
  6274. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  6275. if (!item.filename.empty()) {
  6276. body += "; filename=\"" + item.filename + "\"";
  6277. }
  6278. body += "\r\n";
  6279. if (!item.content_type.empty()) {
  6280. body += "Content-Type: " + item.content_type + "\r\n";
  6281. }
  6282. body += "\r\n";
  6283. body += item.content + "\r\n";
  6284. }
  6285. body += "--" + boundary + "--\r\n";
  6286. std::string content_type = "multipart/form-data; boundary=" + boundary;
  6287. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  6288. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6289. EXPECT_EQ(StatusCode::OK_200, res->status);
  6290. }
  6291. TEST(MultipartFormDataTest, FieldEscaping) {
  6292. Server svr;
  6293. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  6294. const ContentReader &content_reader) {
  6295. ASSERT_TRUE(req.is_multipart_form_data());
  6296. std::vector<FormData> received;
  6297. content_reader(
  6298. [&](const FormData &file) {
  6299. received.push_back(file);
  6300. return true;
  6301. },
  6302. [&](const char *data, size_t data_length) {
  6303. received.back().content.append(data, data_length);
  6304. return true;
  6305. });
  6306. // '"', CR and LF in names and filenames are escaped following the
  6307. // WHATWG HTML standard, so each part still parses as a single part
  6308. // with no injected headers. Content types get CR/LF escaped too,
  6309. // while '"' (legal there, e.g. quoted charset) is preserved.
  6310. ASSERT_EQ(4U, received.size());
  6311. EXPECT_EQ("na%22me", received[0].name);
  6312. EXPECT_EQ("quoted name", received[0].content);
  6313. EXPECT_EQ("file", received[1].name);
  6314. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  6315. received[1].filename);
  6316. EXPECT_EQ("application/octet-stream", received[1].content_type);
  6317. EXPECT_EQ("injected", received[1].content);
  6318. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  6319. EXPECT_EQ("my%22file.txt", received[2].filename);
  6320. EXPECT_EQ("cr lf name", received[2].content);
  6321. EXPECT_EQ("typed", received[3].name);
  6322. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  6323. received[3].content_type);
  6324. EXPECT_EQ("typed content", received[3].content);
  6325. });
  6326. auto port = svr.bind_to_any_port("localhost");
  6327. auto t = std::thread([&]() { svr.listen_after_bind(); });
  6328. auto se = detail::scope_exit([&] {
  6329. svr.stop();
  6330. t.join();
  6331. ASSERT_FALSE(svr.is_running());
  6332. });
  6333. svr.wait_until_ready();
  6334. Client cli("localhost", port);
  6335. UploadFormDataItems items = {
  6336. {"na\"me", "quoted name", "", ""},
  6337. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  6338. "application/octet-stream"},
  6339. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  6340. {"typed", "typed content", "",
  6341. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  6342. };
  6343. auto res = cli.Post("/post", items);
  6344. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6345. EXPECT_EQ(StatusCode::OK_200, res->status);
  6346. }
  6347. TEST(MultipartFormDataTest, PublicWriterAPI) {
  6348. const UploadFormDataItems items = {
  6349. {"name1", "Content 1", "", ""},
  6350. {"name2", "Content 2", "file2.txt", "text/plain"},
  6351. };
  6352. Server svr;
  6353. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  6354. const ContentReader &content_reader) {
  6355. ASSERT_TRUE(req.is_multipart_form_data());
  6356. std::vector<FormData> received;
  6357. content_reader(
  6358. [&](const FormData &file) {
  6359. received.push_back(file);
  6360. return true;
  6361. },
  6362. [&](const char *data, size_t data_length) {
  6363. received.back().content.append(data, data_length);
  6364. return true;
  6365. });
  6366. ASSERT_EQ(2U, received.size());
  6367. EXPECT_EQ("name1", received[0].name);
  6368. EXPECT_EQ("Content 1", received[0].content);
  6369. EXPECT_EQ("name2", received[1].name);
  6370. EXPECT_EQ("Content 2", received[1].content);
  6371. EXPECT_EQ("file2.txt", received[1].filename);
  6372. EXPECT_EQ("text/plain", received[1].content_type);
  6373. });
  6374. auto port = svr.bind_to_any_port("localhost");
  6375. auto t = std::thread([&]() { svr.listen_after_bind(); });
  6376. auto se = detail::scope_exit([&] {
  6377. svr.stop();
  6378. t.join();
  6379. ASSERT_FALSE(svr.is_running());
  6380. });
  6381. svr.wait_until_ready();
  6382. Client cli("localhost", port);
  6383. // Whole-body serialization with a generated boundary
  6384. {
  6385. MultipartFormDataWriter writer;
  6386. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  6387. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  6388. writer.content_type());
  6389. auto body = writer.serialize(items);
  6390. EXPECT_EQ(body.size(), writer.content_length(items));
  6391. auto res = cli.Post("/post", body, writer.content_type());
  6392. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6393. EXPECT_EQ(StatusCode::OK_200, res->status);
  6394. }
  6395. // Per-part framing with a custom boundary via a content provider
  6396. {
  6397. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  6398. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  6399. MultipartFormDataWriter writer("custom-boundary_123");
  6400. EXPECT_EQ("custom-boundary_123", writer.boundary());
  6401. std::string body;
  6402. for (const auto &item : items) {
  6403. body += writer.item_begin(item);
  6404. body += item.content;
  6405. body += MultipartFormDataWriter::item_end();
  6406. }
  6407. body += writer.finish();
  6408. EXPECT_EQ(body.size(), writer.content_length(items));
  6409. auto res = cli.Post(
  6410. "/post", body.size(),
  6411. [&](size_t offset, size_t length, DataSink &sink) {
  6412. sink.write(body.data() + offset, length);
  6413. return true;
  6414. },
  6415. writer.content_type());
  6416. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6417. EXPECT_EQ(StatusCode::OK_200, res->status);
  6418. }
  6419. }
  6420. TEST_F(ServerTest, PostContentReceiverGzip) {
  6421. cli_.set_compress(true);
  6422. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  6423. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6424. ASSERT_EQ(StatusCode::OK_200, res->status);
  6425. ASSERT_EQ("content", res->body);
  6426. }
  6427. TEST_F(ServerTest, PutContentReceiver) {
  6428. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  6429. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6430. ASSERT_EQ(StatusCode::OK_200, res->status);
  6431. ASSERT_EQ("content", res->body);
  6432. }
  6433. TEST_F(ServerTest, PatchContentReceiver) {
  6434. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  6435. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6436. ASSERT_EQ(StatusCode::OK_200, res->status);
  6437. ASSERT_EQ("content", res->body);
  6438. }
  6439. template <typename ClientType>
  6440. void TestWithHeadersAndContentReceiver(
  6441. ClientType &cli,
  6442. std::function<Result(ClientType &, const std::string &, const Headers &,
  6443. const std::string &, const std::string &,
  6444. ContentReceiver, DownloadProgress)>
  6445. request_func) {
  6446. Headers headers;
  6447. headers.emplace("X-Custom-Header", "test-value");
  6448. std::string received_body;
  6449. auto res = request_func(
  6450. cli, "/content_receiver", headers, "content", "application/json",
  6451. [&](const char *data, size_t data_length) {
  6452. received_body.append(data, data_length);
  6453. return true;
  6454. },
  6455. nullptr);
  6456. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6457. EXPECT_EQ(StatusCode::OK_200, res->status);
  6458. EXPECT_EQ("content", received_body);
  6459. }
  6460. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  6461. #ifdef CPPHTTPLIB_SSL_ENABLED
  6462. using ClientT = SSLClient;
  6463. #else
  6464. using ClientT = Client;
  6465. #endif
  6466. TestWithHeadersAndContentReceiver<ClientT>(
  6467. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6468. const std::string &body, const std::string &content_type,
  6469. ContentReceiver receiver, DownloadProgress progress) {
  6470. return cli.Post(path, headers, body, content_type, receiver, progress);
  6471. });
  6472. }
  6473. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  6474. #ifdef CPPHTTPLIB_SSL_ENABLED
  6475. using ClientT = SSLClient;
  6476. #else
  6477. using ClientT = Client;
  6478. #endif
  6479. TestWithHeadersAndContentReceiver<ClientT>(
  6480. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6481. const std::string &body, const std::string &content_type,
  6482. ContentReceiver receiver, DownloadProgress progress) {
  6483. return cli.Put(path, headers, body, content_type, receiver, progress);
  6484. });
  6485. }
  6486. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  6487. #ifdef CPPHTTPLIB_SSL_ENABLED
  6488. using ClientT = SSLClient;
  6489. #else
  6490. using ClientT = Client;
  6491. #endif
  6492. TestWithHeadersAndContentReceiver<ClientT>(
  6493. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6494. const std::string &body, const std::string &content_type,
  6495. ContentReceiver receiver, DownloadProgress progress) {
  6496. return cli.Patch(path, headers, body, content_type, receiver, progress);
  6497. });
  6498. }
  6499. template <typename ClientType>
  6500. void TestWithHeadersAndContentReceiverWithProgress(
  6501. ClientType &cli,
  6502. std::function<Result(ClientType &, const std::string &, const Headers &,
  6503. const std::string &, const std::string &,
  6504. ContentReceiver, DownloadProgress)>
  6505. request_func) {
  6506. Headers headers;
  6507. headers.emplace("X-Test-Header", "progress-test");
  6508. std::string received_body;
  6509. auto progress_called = false;
  6510. auto res = request_func(
  6511. cli, "/content_receiver", headers, "content", "text/plain",
  6512. [&](const char *data, size_t data_length) {
  6513. received_body.append(data, data_length);
  6514. return true;
  6515. },
  6516. [&](uint64_t /*current*/, uint64_t /*total*/) {
  6517. progress_called = true;
  6518. return true;
  6519. });
  6520. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6521. EXPECT_EQ(StatusCode::OK_200, res->status);
  6522. EXPECT_EQ("content", received_body);
  6523. EXPECT_TRUE(progress_called);
  6524. }
  6525. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  6526. #ifdef CPPHTTPLIB_SSL_ENABLED
  6527. using ClientT = SSLClient;
  6528. #else
  6529. using ClientT = Client;
  6530. #endif
  6531. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  6532. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6533. const std::string &body, const std::string &content_type,
  6534. ContentReceiver receiver, DownloadProgress progress) {
  6535. return cli.Post(path, headers, body, content_type, receiver, progress);
  6536. });
  6537. }
  6538. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  6539. #ifdef CPPHTTPLIB_SSL_ENABLED
  6540. using ClientT = SSLClient;
  6541. #else
  6542. using ClientT = Client;
  6543. #endif
  6544. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  6545. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6546. const std::string &body, const std::string &content_type,
  6547. ContentReceiver receiver, DownloadProgress progress) {
  6548. return cli.Put(path, headers, body, content_type, receiver, progress);
  6549. });
  6550. }
  6551. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  6552. #ifdef CPPHTTPLIB_SSL_ENABLED
  6553. using ClientT = SSLClient;
  6554. #else
  6555. using ClientT = Client;
  6556. #endif
  6557. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  6558. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6559. const std::string &body, const std::string &content_type,
  6560. ContentReceiver receiver, DownloadProgress progress) {
  6561. return cli.Patch(path, headers, body, content_type, receiver, progress);
  6562. });
  6563. }
  6564. template <typename ClientType>
  6565. void TestWithHeadersAndContentReceiverError(
  6566. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  6567. const Headers &, const std::string &,
  6568. const std::string &, ContentReceiver)>
  6569. request_func) {
  6570. Headers headers;
  6571. headers.emplace("X-Error-Test", "true");
  6572. std::string received_body;
  6573. auto receiver_failed = false;
  6574. auto res =
  6575. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  6576. [&](const char *data, size_t data_length) {
  6577. received_body.append(data, data_length);
  6578. receiver_failed = true;
  6579. return false;
  6580. });
  6581. ASSERT_FALSE(res);
  6582. EXPECT_TRUE(receiver_failed);
  6583. }
  6584. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  6585. #ifdef CPPHTTPLIB_SSL_ENABLED
  6586. using ClientT = SSLClient;
  6587. #else
  6588. using ClientT = Client;
  6589. #endif
  6590. TestWithHeadersAndContentReceiverError<ClientT>(
  6591. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6592. const std::string &body, const std::string &content_type,
  6593. ContentReceiver receiver) {
  6594. return cli.Post(path, headers, body, content_type, receiver);
  6595. });
  6596. }
  6597. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  6598. #ifdef CPPHTTPLIB_SSL_ENABLED
  6599. using ClientT = SSLClient;
  6600. #else
  6601. using ClientT = Client;
  6602. #endif
  6603. TestWithHeadersAndContentReceiverError<ClientT>(
  6604. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6605. const std::string &body, const std::string &content_type,
  6606. ContentReceiver receiver) {
  6607. return cli.Put(path, headers, body, content_type, receiver);
  6608. });
  6609. }
  6610. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  6611. #ifdef CPPHTTPLIB_SSL_ENABLED
  6612. using ClientT = SSLClient;
  6613. #else
  6614. using ClientT = Client;
  6615. #endif
  6616. TestWithHeadersAndContentReceiverError<ClientT>(
  6617. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6618. const std::string &body, const std::string &content_type,
  6619. ContentReceiver receiver) {
  6620. return cli.Patch(path, headers, body, content_type, receiver);
  6621. });
  6622. }
  6623. TEST_F(ServerTest, PostQueryStringAndBody) {
  6624. auto res =
  6625. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  6626. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6627. ASSERT_EQ(StatusCode::OK_200, res->status);
  6628. }
  6629. TEST_F(ServerTest, HTTP2Magic) {
  6630. Request req;
  6631. req.method = "PRI";
  6632. req.path = "*";
  6633. req.body = "SM";
  6634. auto res = std::make_shared<Response>();
  6635. auto error = Error::Success;
  6636. auto ret = cli_.send(req, *res, error);
  6637. ASSERT_TRUE(ret);
  6638. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6639. }
  6640. TEST_F(ServerTest, KeepAlive) {
  6641. auto res = cli_.Get("/hi");
  6642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6643. EXPECT_EQ(StatusCode::OK_200, res->status);
  6644. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6645. EXPECT_EQ("Hello World!", res->body);
  6646. res = cli_.Get("/hi");
  6647. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6648. EXPECT_EQ(StatusCode::OK_200, res->status);
  6649. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6650. EXPECT_EQ("Hello World!", res->body);
  6651. res = cli_.Get("/hi");
  6652. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6653. EXPECT_EQ(StatusCode::OK_200, res->status);
  6654. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6655. EXPECT_EQ("Hello World!", res->body);
  6656. res = cli_.Get("/not-exist");
  6657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6658. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6659. res = cli_.Post("/empty", "", "text/plain");
  6660. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6661. EXPECT_EQ(StatusCode::OK_200, res->status);
  6662. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6663. EXPECT_EQ("empty", res->body);
  6664. EXPECT_EQ("close", res->get_header_value("Connection"));
  6665. res = cli_.Post(
  6666. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  6667. "text/plain");
  6668. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6669. EXPECT_EQ(StatusCode::OK_200, res->status);
  6670. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6671. EXPECT_EQ("empty", res->body);
  6672. cli_.set_keep_alive(false);
  6673. res = cli_.Get("/last-request");
  6674. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6675. EXPECT_EQ(StatusCode::OK_200, res->status);
  6676. EXPECT_EQ("close", res->get_header_value("Connection"));
  6677. }
  6678. TEST_F(ServerTest, TooManyRedirect) {
  6679. cli_.set_follow_location(true);
  6680. auto res = cli_.Get("/redirect/0");
  6681. ASSERT_TRUE(!res);
  6682. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  6683. }
  6684. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  6685. Request req;
  6686. req.method = "FOOBAR";
  6687. req.path = "/hi";
  6688. cli_.set_keep_alive(true);
  6689. auto res = cli_.send(req);
  6690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6691. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6692. EXPECT_EQ("close", res->get_header_value("Connection"));
  6693. EXPECT_FALSE(cli_.is_socket_open());
  6694. }
  6695. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  6696. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6697. TEST_F(ServerTest, Gzip) {
  6698. Headers headers;
  6699. headers.emplace("Accept-Encoding", "gzip, deflate");
  6700. auto res = cli_.Get("/compress", headers);
  6701. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6702. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6703. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6704. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6705. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6706. "7890123456789012345678901234567890",
  6707. res->body);
  6708. EXPECT_EQ(StatusCode::OK_200, res->status);
  6709. }
  6710. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  6711. Headers headers;
  6712. headers.emplace("Accept-Encoding", "gzip, deflate");
  6713. auto res = cli_.Get("/compress-with-charset", headers);
  6714. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6715. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6716. EXPECT_EQ("application/json; charset=utf-8",
  6717. res->get_header_value("Content-Type"));
  6718. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6719. "7890123456789012345678901234567890",
  6720. res->body);
  6721. EXPECT_EQ(StatusCode::OK_200, res->status);
  6722. }
  6723. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  6724. Headers headers;
  6725. headers.emplace("Accept-Encoding", "");
  6726. auto res = cli_.Get("/compress", headers);
  6727. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6728. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6729. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6730. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6731. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6732. "7890123456789012345678901234567890",
  6733. res->body);
  6734. EXPECT_EQ(StatusCode::OK_200, res->status);
  6735. }
  6736. TEST_F(ServerTest, GzipWithContentReceiver) {
  6737. Headers headers;
  6738. headers.emplace("Accept-Encoding", "gzip, deflate");
  6739. std::string body;
  6740. auto res = cli_.Get("/compress", headers,
  6741. [&](const char *data, uint64_t data_length) {
  6742. EXPECT_EQ(100U, data_length);
  6743. body.append(data, data_length);
  6744. return true;
  6745. });
  6746. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6747. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6748. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6749. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6750. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6751. "7890123456789012345678901234567890",
  6752. body);
  6753. EXPECT_EQ(StatusCode::OK_200, res->status);
  6754. }
  6755. TEST_F(ServerTest, GzipWithoutDecompressing) {
  6756. Headers headers;
  6757. headers.emplace("Accept-Encoding", "gzip, deflate");
  6758. cli_.set_decompress(false);
  6759. auto res = cli_.Get("/compress", headers);
  6760. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6761. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6762. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6763. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6764. EXPECT_EQ(33U, res->body.size());
  6765. EXPECT_EQ(StatusCode::OK_200, res->status);
  6766. }
  6767. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  6768. Headers headers;
  6769. headers.emplace("Accept-Encoding", "");
  6770. std::string body;
  6771. auto res = cli_.Get("/compress", headers,
  6772. [&](const char *data, uint64_t data_length) {
  6773. EXPECT_EQ(100U, data_length);
  6774. body.append(data, data_length);
  6775. return true;
  6776. });
  6777. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6778. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6779. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6780. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6781. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6782. "7890123456789012345678901234567890",
  6783. body);
  6784. EXPECT_EQ(StatusCode::OK_200, res->status);
  6785. }
  6786. TEST_F(ServerTest, NoGzip) {
  6787. Headers headers;
  6788. headers.emplace("Accept-Encoding", "gzip, deflate");
  6789. auto res = cli_.Get("/nocompress", headers);
  6790. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6791. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6792. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6793. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6794. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6795. "7890123456789012345678901234567890",
  6796. res->body);
  6797. EXPECT_EQ(StatusCode::OK_200, res->status);
  6798. }
  6799. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  6800. Headers headers;
  6801. headers.emplace("Accept-Encoding", "gzip, deflate");
  6802. std::string body;
  6803. auto res = cli_.Get("/nocompress", headers,
  6804. [&](const char *data, uint64_t data_length) {
  6805. EXPECT_EQ(100U, data_length);
  6806. body.append(data, data_length);
  6807. return true;
  6808. });
  6809. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6810. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6811. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6812. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6813. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6814. "7890123456789012345678901234567890",
  6815. body);
  6816. EXPECT_EQ(StatusCode::OK_200, res->status);
  6817. }
  6818. TEST_F(ServerTest, MultipartFormDataGzip) {
  6819. UploadFormDataItems items = {
  6820. {"key1", "test", "", ""},
  6821. {"key2", "--abcdefg123", "", ""},
  6822. };
  6823. cli_.set_compress(true);
  6824. auto res = cli_.Post("/compress-multipart", items);
  6825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6826. EXPECT_EQ(StatusCode::OK_200, res->status);
  6827. }
  6828. #endif
  6829. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6830. TEST_F(ServerTest, Brotli) {
  6831. Headers headers;
  6832. headers.emplace("Accept-Encoding", "br");
  6833. auto res = cli_.Get("/compress", headers);
  6834. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6835. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  6836. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6837. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  6838. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6839. "7890123456789012345678901234567890",
  6840. res->body);
  6841. EXPECT_EQ(StatusCode::OK_200, res->status);
  6842. }
  6843. #endif
  6844. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  6845. TEST_F(ServerTest, Zstd) {
  6846. Headers headers;
  6847. headers.emplace("Accept-Encoding", "zstd");
  6848. auto res = cli_.Get("/compress", headers);
  6849. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6850. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6851. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6852. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6853. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6854. "7890123456789012345678901234567890",
  6855. res->body);
  6856. EXPECT_EQ(StatusCode::OK_200, res->status);
  6857. }
  6858. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  6859. Headers headers;
  6860. headers.emplace("Accept-Encoding", "");
  6861. auto res = cli_.Get("/compress", headers);
  6862. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6863. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6864. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6865. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6866. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6867. "7890123456789012345678901234567890",
  6868. res->body);
  6869. EXPECT_EQ(StatusCode::OK_200, res->status);
  6870. }
  6871. TEST_F(ServerTest, ZstdWithContentReceiver) {
  6872. Headers headers;
  6873. headers.emplace("Accept-Encoding", "zstd");
  6874. std::string body;
  6875. auto res = cli_.Get("/compress", headers,
  6876. [&](const char *data, uint64_t data_length) {
  6877. EXPECT_EQ(100U, data_length);
  6878. body.append(data, data_length);
  6879. return true;
  6880. });
  6881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6882. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6883. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6884. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6885. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6886. "7890123456789012345678901234567890",
  6887. body);
  6888. EXPECT_EQ(StatusCode::OK_200, res->status);
  6889. }
  6890. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  6891. Headers headers;
  6892. headers.emplace("Accept-Encoding", "zstd");
  6893. cli_.set_decompress(false);
  6894. auto res = cli_.Get("/compress", headers);
  6895. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  6896. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  6897. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  6898. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  6899. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6900. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6901. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6902. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6903. EXPECT_EQ(StatusCode::OK_200, res->status);
  6904. ASSERT_EQ(26U, res->body.size());
  6905. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  6906. 0);
  6907. }
  6908. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  6909. Headers headers;
  6910. headers.emplace("Accept-Encoding", "");
  6911. std::string body;
  6912. auto res = cli_.Get("/compress", headers,
  6913. [&](const char *data, uint64_t data_length) {
  6914. EXPECT_EQ(100U, data_length);
  6915. body.append(data, data_length);
  6916. return true;
  6917. });
  6918. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6919. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6920. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6921. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6922. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6923. "7890123456789012345678901234567890",
  6924. body);
  6925. EXPECT_EQ(StatusCode::OK_200, res->status);
  6926. }
  6927. TEST_F(ServerTest, NoZstd) {
  6928. Headers headers;
  6929. headers.emplace("Accept-Encoding", "zstd");
  6930. auto res = cli_.Get("/nocompress", headers);
  6931. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6932. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6933. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6934. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6935. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6936. "7890123456789012345678901234567890",
  6937. res->body);
  6938. EXPECT_EQ(StatusCode::OK_200, res->status);
  6939. }
  6940. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  6941. Headers headers;
  6942. headers.emplace("Accept-Encoding", "zstd");
  6943. std::string body;
  6944. auto res = cli_.Get("/nocompress", headers,
  6945. [&](const char *data, uint64_t data_length) {
  6946. EXPECT_EQ(100U, data_length);
  6947. body.append(data, data_length);
  6948. return true;
  6949. });
  6950. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6951. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6952. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6953. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6954. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6955. "7890123456789012345678901234567890",
  6956. body);
  6957. EXPECT_EQ(StatusCode::OK_200, res->status);
  6958. }
  6959. // TODO: How to enable zstd ??
  6960. TEST_F(ServerTest, MultipartFormDataZstd) {
  6961. UploadFormDataItems items = {
  6962. {"key1", "test", "", ""},
  6963. {"key2", "--abcdefg123", "", ""},
  6964. };
  6965. Headers headers;
  6966. headers.emplace("Accept-Encoding", "zstd");
  6967. cli_.set_compress(true);
  6968. auto res = cli_.Post("/compress-multipart", headers, items);
  6969. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6970. EXPECT_EQ(StatusCode::OK_200, res->status);
  6971. }
  6972. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  6973. Headers headers;
  6974. headers.emplace("Accept-Encoding", "zstd");
  6975. cli_.set_compress(true);
  6976. auto res = cli_.Put(
  6977. "/put", headers, 3,
  6978. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6979. sink.os << "PUT";
  6980. return true;
  6981. },
  6982. "text/plain");
  6983. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6984. EXPECT_EQ(StatusCode::OK_200, res->status);
  6985. EXPECT_EQ("PUT", res->body);
  6986. }
  6987. // Pre-compression logging tests
  6988. TEST_F(ServerTest, PreCompressionLogging) {
  6989. // Test data for compression (matches the actual /compress endpoint content)
  6990. const std::string test_content =
  6991. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6992. "3456789012345678901234567890";
  6993. // Variables to capture logging data
  6994. std::string pre_compression_body;
  6995. std::string pre_compression_content_type;
  6996. std::string pre_compression_content_encoding;
  6997. std::string post_compression_body;
  6998. std::string post_compression_content_type;
  6999. std::string post_compression_content_encoding;
  7000. // Set up pre-compression logger
  7001. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  7002. const Response &res) {
  7003. pre_compression_body = res.body;
  7004. pre_compression_content_type = res.get_header_value("Content-Type");
  7005. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  7006. });
  7007. // Set up post-compression logger
  7008. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  7009. post_compression_body = res.body;
  7010. post_compression_content_type = res.get_header_value("Content-Type");
  7011. post_compression_content_encoding =
  7012. res.get_header_value("Content-Encoding");
  7013. });
  7014. // Test with gzip compression
  7015. Headers headers;
  7016. headers.emplace("Accept-Encoding", "gzip");
  7017. auto res = cli_.Get("/compress", headers);
  7018. // Verify response was compressed
  7019. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7020. EXPECT_EQ(StatusCode::OK_200, res->status);
  7021. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7022. // Verify pre-compression logger captured uncompressed content
  7023. EXPECT_EQ(test_content, pre_compression_body);
  7024. EXPECT_EQ("text/plain", pre_compression_content_type);
  7025. EXPECT_TRUE(pre_compression_content_encoding
  7026. .empty()); // No encoding header before compression
  7027. // Verify post-compression logger captured compressed content
  7028. EXPECT_NE(test_content,
  7029. post_compression_body); // Should be different after compression
  7030. EXPECT_EQ("text/plain", post_compression_content_type);
  7031. EXPECT_EQ("gzip", post_compression_content_encoding);
  7032. // Verify compressed content is smaller
  7033. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  7034. }
  7035. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  7036. const std::string test_content =
  7037. "123456789012345678901234567890123456789012345678901234567890123456789012"
  7038. "3456789012345678901234567890";
  7039. std::string pre_compression_body;
  7040. std::string post_compression_body;
  7041. svr_.set_pre_compression_logger(
  7042. [&](const Request & /*req*/, const Response &res) {
  7043. pre_compression_body = res.body;
  7044. });
  7045. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  7046. post_compression_body = res.body;
  7047. });
  7048. Headers headers;
  7049. headers.emplace("Accept-Encoding", "br");
  7050. auto res = cli_.Get("/compress", headers);
  7051. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7052. EXPECT_EQ(StatusCode::OK_200, res->status);
  7053. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  7054. // Verify pre-compression content is uncompressed
  7055. EXPECT_EQ(test_content, pre_compression_body);
  7056. // Verify post-compression content is compressed
  7057. EXPECT_NE(test_content, post_compression_body);
  7058. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  7059. }
  7060. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  7061. const std::string test_content =
  7062. "123456789012345678901234567890123456789012345678901234567890123456789012"
  7063. "3456789012345678901234567890";
  7064. std::string pre_compression_body;
  7065. std::string post_compression_body;
  7066. svr_.set_pre_compression_logger(
  7067. [&](const Request & /*req*/, const Response &res) {
  7068. pre_compression_body = res.body;
  7069. });
  7070. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  7071. post_compression_body = res.body;
  7072. });
  7073. // Request without compression (use /nocompress endpoint)
  7074. Headers headers;
  7075. auto res = cli_.Get("/nocompress", headers);
  7076. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7077. EXPECT_EQ(StatusCode::OK_200, res->status);
  7078. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7079. // Pre-compression logger should not be called when no compression is applied
  7080. EXPECT_TRUE(
  7081. pre_compression_body.empty()); // Pre-compression logger not called
  7082. EXPECT_EQ(
  7083. test_content,
  7084. post_compression_body); // Post-compression logger captures final content
  7085. }
  7086. TEST_F(ServerTest, LoggerSeesContentLength) {
  7087. size_t logged_content_length = 0;
  7088. std::string logged_content_length_header;
  7089. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  7090. logged_content_length = res.content_length_;
  7091. logged_content_length_header = res.get_header_value("Content-Length");
  7092. });
  7093. auto res = cli_.Get("/nocompress");
  7094. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7095. EXPECT_EQ(StatusCode::OK_200, res->status);
  7096. EXPECT_EQ(res->body.size(), logged_content_length);
  7097. EXPECT_EQ(std::to_string(logged_content_length),
  7098. logged_content_length_header);
  7099. }
  7100. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  7101. const std::string test_content =
  7102. "123456789012345678901234567890123456789012345678901234567890123456789012"
  7103. "3456789012345678901234567890";
  7104. std::string pre_compression_body;
  7105. bool pre_logger_called = false;
  7106. // Set only pre-compression logger
  7107. svr_.set_pre_compression_logger(
  7108. [&](const Request & /*req*/, const Response &res) {
  7109. pre_compression_body = res.body;
  7110. pre_logger_called = true;
  7111. });
  7112. Headers headers;
  7113. headers.emplace("Accept-Encoding", "gzip");
  7114. auto res = cli_.Get("/compress", headers);
  7115. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7116. EXPECT_EQ(StatusCode::OK_200, res->status);
  7117. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7118. // Verify pre-compression logger was called
  7119. EXPECT_TRUE(pre_logger_called);
  7120. EXPECT_EQ(test_content, pre_compression_body);
  7121. }
  7122. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  7123. {
  7124. // Test with Expect: 100-continue header - success case
  7125. // Server returns 100 Continue, client sends body, server returns 200 OK
  7126. Request req;
  7127. req.method = "POST";
  7128. req.path = "/post-large";
  7129. req.set_header("Expect", "100-continue");
  7130. req.body = LARGE_DATA;
  7131. Response res;
  7132. auto error = Error::Success;
  7133. cli_.set_keep_alive(true);
  7134. auto ret = cli_.send(req, res, error);
  7135. EXPECT_TRUE(ret);
  7136. EXPECT_EQ(StatusCode::OK_200, res.status);
  7137. EXPECT_EQ(LARGE_DATA, res.body);
  7138. }
  7139. {
  7140. // Test with Expect: 100-continue header - error case
  7141. // Client should not send the body when server returns an error
  7142. Request req;
  7143. req.method = "POST";
  7144. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  7145. req.set_header("Expect", "100-continue");
  7146. req.body = LARGE_DATA;
  7147. Response res;
  7148. auto error = Error::Success;
  7149. auto start = std::chrono::high_resolution_clock::now();
  7150. cli_.set_keep_alive(true);
  7151. auto ret = cli_.send(req, res, error);
  7152. auto end = std::chrono::high_resolution_clock::now();
  7153. auto elapsed =
  7154. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  7155. .count();
  7156. // With Expect: 100-continue, request completes successfully but with error
  7157. EXPECT_TRUE(ret);
  7158. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  7159. EXPECT_EQ("close", res.get_header_value("Connection"));
  7160. EXPECT_FALSE(cli_.is_socket_open());
  7161. EXPECT_LE(elapsed, 2000);
  7162. }
  7163. {
  7164. // Send an extra GET request to ensure error recovery without hanging
  7165. Request req;
  7166. req.method = "GET";
  7167. req.path = "/hi";
  7168. auto start = std::chrono::high_resolution_clock::now();
  7169. auto res = cli_.send(req);
  7170. auto end = std::chrono::high_resolution_clock::now();
  7171. auto elapsed =
  7172. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  7173. .count();
  7174. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7175. EXPECT_EQ(StatusCode::OK_200, res->status);
  7176. EXPECT_EQ("Hello World!", res->body);
  7177. EXPECT_LE(elapsed, 500);
  7178. }
  7179. }
  7180. TEST(ZstdDecompressor, ChunkedDecompression) {
  7181. std::string data;
  7182. for (size_t i = 0; i < 32 * 1024; ++i) {
  7183. data.push_back(static_cast<char>('a' + i % 26));
  7184. }
  7185. std::string compressed_data;
  7186. {
  7187. httplib::detail::zstd_compressor compressor;
  7188. bool result = compressor.compress(
  7189. data.data(), data.size(),
  7190. /*last=*/true,
  7191. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  7192. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  7193. compressed_data_size);
  7194. return true;
  7195. });
  7196. ASSERT_TRUE(result);
  7197. }
  7198. std::string decompressed_data;
  7199. {
  7200. httplib::detail::zstd_decompressor decompressor;
  7201. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7202. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7203. size_t chunk_size = 130;
  7204. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7205. chunk_begin += chunk_size) {
  7206. size_t current_chunk_size =
  7207. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7208. bool result = decompressor.decompress(
  7209. compressed_data.data() + chunk_begin, current_chunk_size,
  7210. [&](const char *decompressed_data_chunk,
  7211. size_t decompressed_data_chunk_size) {
  7212. decompressed_data.insert(decompressed_data.size(),
  7213. decompressed_data_chunk,
  7214. decompressed_data_chunk_size);
  7215. return true;
  7216. });
  7217. ASSERT_TRUE(result);
  7218. }
  7219. }
  7220. ASSERT_EQ(data, decompressed_data);
  7221. }
  7222. TEST(ZstdDecompressor, Decompress) {
  7223. std::string original_text = "Compressed with ZSTD";
  7224. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  7225. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  7226. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  7227. 0x20, 0x5a, 0x53, 0x54, 0x44};
  7228. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7229. std::string decompressed_data;
  7230. {
  7231. httplib::detail::zstd_decompressor decompressor;
  7232. bool result = decompressor.decompress(
  7233. compressed_data.data(), compressed_data.size(),
  7234. [&](const char *decompressed_data_chunk,
  7235. size_t decompressed_data_chunk_size) {
  7236. decompressed_data.insert(decompressed_data.size(),
  7237. decompressed_data_chunk,
  7238. decompressed_data_chunk_size);
  7239. return true;
  7240. });
  7241. ASSERT_TRUE(result);
  7242. }
  7243. ASSERT_EQ(original_text, decompressed_data);
  7244. }
  7245. #endif
  7246. // Sends a raw request to a server listening at HOST:PORT.
  7247. static bool send_request(time_t read_timeout_sec, const std::string &req,
  7248. std::string *resp = nullptr, int port = PORT) {
  7249. auto error = Error::Success;
  7250. auto client_sock = detail::create_client_socket(
  7251. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  7252. /*connection_timeout_sec=*/5, 0,
  7253. /*read_timeout_sec=*/5, 0,
  7254. /*write_timeout_sec=*/5, 0, std::string(), error);
  7255. if (client_sock == INVALID_SOCKET) { return false; }
  7256. auto ret = detail::process_client_socket(
  7257. client_sock, read_timeout_sec, 0, 0, 0, 0,
  7258. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  7259. if (req.size() !=
  7260. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  7261. return false;
  7262. }
  7263. char buf[512];
  7264. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  7265. while (line_reader.getline()) {
  7266. if (resp) { *resp += line_reader.ptr(); }
  7267. }
  7268. return true;
  7269. });
  7270. detail::close_socket(client_sock);
  7271. return ret;
  7272. }
  7273. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  7274. Server svr;
  7275. std::string header_value;
  7276. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  7277. header_value = req.get_header_value("foo");
  7278. res.set_content("ok", "text/plain");
  7279. });
  7280. thread t = thread([&] { svr.listen(HOST, PORT); });
  7281. auto se = detail::scope_exit([&] {
  7282. svr.stop();
  7283. t.join();
  7284. ASSERT_FALSE(svr.is_running());
  7285. });
  7286. svr.wait_until_ready();
  7287. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  7288. // like characters are not treated the same - use vertical tab and escape.
  7289. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  7290. "foo: \t \v bar \x1B\t \r\n"
  7291. "Connection: close\r\n"
  7292. "\r\n";
  7293. std::string res;
  7294. ASSERT_TRUE(send_request(5, req, &res));
  7295. EXPECT_EQ(header_value, "");
  7296. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  7297. }
  7298. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  7299. Server svr;
  7300. std::string received;
  7301. svr.Get("/order", [&](const Request &req, Response &res) {
  7302. received = entries_to_string(req.headers);
  7303. res.set_content("ok", "text/plain");
  7304. });
  7305. auto port = svr.bind_to_any_port(HOST);
  7306. thread t = thread([&] { svr.listen_after_bind(); });
  7307. auto se = detail::scope_exit([&] {
  7308. svr.stop();
  7309. t.join();
  7310. ASSERT_FALSE(svr.is_running());
  7311. });
  7312. svr.wait_until_ready();
  7313. const std::string req = "GET /order HTTP/1.1\r\n"
  7314. "X-First: 1\r\n"
  7315. "X-Dup: a\r\n"
  7316. "X-Second: 2\r\n"
  7317. "X-Dup: b\r\n"
  7318. "Connection: close\r\n"
  7319. "\r\n";
  7320. std::string res;
  7321. ASSERT_TRUE(send_request(5, req, &res, port));
  7322. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7323. EXPECT_EQ("X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ", received);
  7324. }
  7325. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  7326. Server svr;
  7327. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  7328. res.set_header("Set-Cookie", "first=1");
  7329. res.set_header("X-Between", "y");
  7330. res.set_header("Set-Cookie", "second=2");
  7331. res.set_content("ok", "text/plain");
  7332. });
  7333. auto port = svr.bind_to_any_port(HOST);
  7334. thread t = thread([&] { svr.listen_after_bind(); });
  7335. auto se = detail::scope_exit([&] {
  7336. svr.stop();
  7337. t.join();
  7338. ASSERT_FALSE(svr.is_running());
  7339. });
  7340. svr.wait_until_ready();
  7341. Client cli(HOST, port);
  7342. auto res = cli.Get("/cookies");
  7343. ASSERT_TRUE(res);
  7344. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  7345. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  7346. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  7347. }
  7348. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  7349. Server svr;
  7350. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  7351. auto i = new int(0);
  7352. res.set_header("Trailer", "X-Safe, X-Reflected");
  7353. res.set_chunked_content_provider(
  7354. "text/plain",
  7355. [i](size_t /*offset*/, DataSink &sink) {
  7356. if (*i == 0) {
  7357. sink.os << "body";
  7358. } else {
  7359. Headers trailer;
  7360. // A valid trailer that must survive.
  7361. trailer.emplace("X-Safe", "safe");
  7362. // Attacker-controlled value carrying CR/LF (response splitting).
  7363. trailer.emplace("X-Reflected",
  7364. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  7365. // Attacker-controlled name carrying CR/LF.
  7366. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  7367. sink.done_with_trailer(trailer);
  7368. }
  7369. (*i)++;
  7370. return true;
  7371. },
  7372. [i](bool /*success*/) { delete i; });
  7373. });
  7374. thread t = thread([&] { svr.listen(HOST, PORT); });
  7375. auto se = detail::scope_exit([&] {
  7376. svr.stop();
  7377. t.join();
  7378. ASSERT_FALSE(svr.is_running());
  7379. });
  7380. svr.wait_until_ready();
  7381. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  7382. "Host: " + HOST +
  7383. "\r\n"
  7384. "Connection: close\r\n"
  7385. "\r\n";
  7386. std::string res;
  7387. ASSERT_TRUE(send_request(5, req, &res));
  7388. // The injected fields must not appear anywhere in the raw response.
  7389. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  7390. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  7391. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  7392. // Invalid trailers are dropped entirely, matching set_header().
  7393. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  7394. // The valid trailer still passes through.
  7395. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  7396. }
  7397. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  7398. Server svr;
  7399. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  7400. // res.headers is a public field an application can populate directly,
  7401. // bypassing set_header()'s validation (e.g. reflecting a request value).
  7402. // A valid header that must survive.
  7403. res.headers.emplace("X-Safe", "safe");
  7404. // Attacker-controlled value carrying CR/LF (response splitting).
  7405. res.headers.emplace("X-Reflected",
  7406. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  7407. // Attacker-controlled name carrying CR/LF.
  7408. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  7409. res.set_content("body", "text/plain");
  7410. });
  7411. thread t = thread([&] { svr.listen(HOST, PORT); });
  7412. auto se = detail::scope_exit([&] {
  7413. svr.stop();
  7414. t.join();
  7415. ASSERT_FALSE(svr.is_running());
  7416. });
  7417. svr.wait_until_ready();
  7418. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  7419. "Host: " + HOST +
  7420. "\r\n"
  7421. "Connection: close\r\n"
  7422. "\r\n";
  7423. std::string res;
  7424. ASSERT_TRUE(send_request(5, req, &res));
  7425. // The injected fields must not appear anywhere in the raw response.
  7426. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  7427. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  7428. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  7429. // Invalid headers are dropped entirely, matching set_header().
  7430. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  7431. // The valid header still passes through.
  7432. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  7433. }
  7434. // Forward declaration: in split builds split.py strips `inline` and moves the
  7435. // definition into httplib.cc, so detail::write_request_line is not visible from
  7436. // the public httplib.h. Re-declaring it here lets the tests link against the
  7437. // symbol in both header-only and split builds.
  7438. namespace httplib {
  7439. namespace detail {
  7440. ssize_t write_request_line(Stream &strm, const std::string &method,
  7441. const std::string &path);
  7442. } // namespace detail
  7443. } // namespace httplib
  7444. TEST(RequestLineInjectionTest, RejectsCRLFInTarget) {
  7445. // A well-formed target is written verbatim.
  7446. {
  7447. detail::BufferStream strm;
  7448. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  7449. EXPECT_GT(n, 0);
  7450. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  7451. }
  7452. // A target carrying CR/LF must be rejected before anything reaches the wire,
  7453. // otherwise it splits the request line and injects a header or a whole
  7454. // request. This is what a decoded redirect Location ("%0D%0A") turns into
  7455. // when path encoding is disabled.
  7456. const std::string evil_targets[] = {
  7457. "/a\r\nInjected: pwned",
  7458. "/a\rInjected",
  7459. "/a\nInjected",
  7460. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  7461. };
  7462. for (const auto &evil : evil_targets) {
  7463. detail::BufferStream strm;
  7464. auto n = detail::write_request_line(strm, "GET", evil);
  7465. EXPECT_LT(n, 0);
  7466. EXPECT_TRUE(strm.get_buffer().empty());
  7467. }
  7468. }
  7469. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  7470. // End-to-end counterpart to RejectsCRLFInTarget. With path encoding disabled
  7471. // the client transmits the target verbatim, so a CR/LF-bearing target -- what
  7472. // a redirect Location "%0D%0A" decodes to -- reaches write_request. The
  7473. // client must fail cleanly with Error::Write instead of putting a
  7474. // request-line-less, header-injecting request on the wire.
  7475. Server svr;
  7476. svr.Get("/a", [](const Request &, Response &res) {
  7477. res.set_content("ok", "text/plain");
  7478. });
  7479. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7480. auto se = detail::scope_exit([&] {
  7481. svr.stop();
  7482. thread.join();
  7483. ASSERT_FALSE(svr.is_running());
  7484. });
  7485. svr.wait_until_ready();
  7486. {
  7487. Client cli(HOST, PORT);
  7488. cli.set_path_encode(false);
  7489. // The request is rejected before anything is written, so the connection
  7490. // stays silent and the subsequent response read would otherwise block for
  7491. // the full default read timeout. Shorten it -- the assertion is on the
  7492. // error, not the timeout.
  7493. cli.set_read_timeout(1, 0);
  7494. auto res = cli.Get("/a\r\nInjected: pwned");
  7495. EXPECT_FALSE(res);
  7496. EXPECT_EQ(Error::Write, res.error());
  7497. }
  7498. }
  7499. // Sends a raw request and verifies that there isn't a crash or exception.
  7500. static void test_raw_request(const std::string &req,
  7501. std::string *out = nullptr) {
  7502. Server svr;
  7503. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7504. res.set_content("ok", "text/plain");
  7505. });
  7506. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  7507. res.set_content("ok", "text/plain");
  7508. });
  7509. svr.Get("/header_field_value_check",
  7510. [&](const Request & /*req*/, Response &res) {
  7511. res.set_content("ok", "text/plain");
  7512. });
  7513. // Server read timeout must be longer than the client read timeout for the
  7514. // bug to reproduce, probably to force the server to process a request
  7515. // without a trailing blank line.
  7516. const time_t client_read_timeout_sec = 1;
  7517. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  7518. bool listen_thread_ok = false;
  7519. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  7520. auto se = detail::scope_exit([&] {
  7521. svr.stop();
  7522. t.join();
  7523. ASSERT_FALSE(svr.is_running());
  7524. EXPECT_TRUE(listen_thread_ok);
  7525. });
  7526. svr.wait_until_ready();
  7527. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  7528. }
  7529. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  7530. // A certain header line causes an exception if the header property is parsed
  7531. // naively with a single regex. This occurs with libc++ but not libstdc++.
  7532. test_raw_request(
  7533. "GET /hi HTTP/1.1\r\n"
  7534. " : "
  7535. " "
  7536. " ");
  7537. }
  7538. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  7539. // A certain header line causes an exception if the header property *name* is
  7540. // parsed with a regular expression starting with "(.+?):" - this is a non-
  7541. // greedy matcher and requires backtracking when there are a lot of ":"
  7542. // characters.
  7543. // This occurs with libc++ but not libstdc++.
  7544. test_raw_request(
  7545. "GET /hi HTTP/1.1\r\n"
  7546. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  7547. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  7548. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  7549. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  7550. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  7551. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  7552. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  7553. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  7554. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  7555. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  7556. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  7557. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  7558. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  7559. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  7560. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  7561. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  7562. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  7563. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  7564. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  7565. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  7566. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  7567. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  7568. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  7569. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  7570. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  7571. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  7572. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  7573. "&&&%%%");
  7574. }
  7575. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  7576. // Make sure this doesn't crash the server.
  7577. // In a previous version of the header line regex, the "\r" rendered the line
  7578. // unparsable and the regex engine repeatedly backtracked, trying to look for
  7579. // a new position where the leading white space ended and the field value
  7580. // began.
  7581. // The crash occurs with libc++ but not libstdc++.
  7582. test_raw_request("GET /hi HTTP/1.1\r\n"
  7583. "a:" +
  7584. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  7585. "\r\n"
  7586. "\r\n");
  7587. }
  7588. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  7589. std::string out;
  7590. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  7591. "Content-Type: text/plain\r\n"
  7592. "Transfer-Encoding: chunked\r\n"
  7593. "\r\n"
  7594. "nothex\r\n",
  7595. &out);
  7596. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7597. }
  7598. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  7599. std::string out;
  7600. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  7601. "Content-Type: text/plain\r\n"
  7602. "Transfer-Encoding: chunked\r\n"
  7603. "\r\n"
  7604. "3\r\n"
  7605. "xyz\r\n"
  7606. "NaN\r\n",
  7607. &out);
  7608. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7609. }
  7610. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  7611. std::string out;
  7612. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  7613. "Content-Type: text/plain\r\n"
  7614. "Transfer-Encoding: chunked\r\n"
  7615. "\r\n"
  7616. // Length is too large for 64 bits.
  7617. "1ffffffffffffffff\r\n"
  7618. "xyz\r\n",
  7619. &out);
  7620. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7621. }
  7622. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  7623. test_raw_request("GET /hi HTTP/1.1\r\n"
  7624. "Content-Type: text/plain\r\n\r");
  7625. }
  7626. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  7627. std::string out;
  7628. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  7629. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7630. }
  7631. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  7632. Server svr;
  7633. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  7634. EXPECT_TRUE(!req.remote_addr.empty());
  7635. });
  7636. thread t = thread([&] { svr.listen(HOST, PORT); });
  7637. auto se = detail::scope_exit([&] {
  7638. svr.stop();
  7639. t.join();
  7640. ASSERT_FALSE(svr.is_running());
  7641. });
  7642. svr.wait_until_ready();
  7643. // Send an invalid request line to trigger Bad Request
  7644. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  7645. std::string out;
  7646. ASSERT_TRUE(send_request(5, bad_req, &out));
  7647. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7648. }
  7649. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  7650. std::string out;
  7651. std::string request(
  7652. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  7653. test_raw_request(request, &out);
  7654. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7655. }
  7656. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  7657. std::string out;
  7658. std::string request(
  7659. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  7660. test_raw_request(request, &out);
  7661. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7662. }
  7663. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  7664. std::string out;
  7665. std::string request(
  7666. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  7667. test_raw_request(request, &out);
  7668. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7669. }
  7670. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  7671. std::string out;
  7672. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  7673. "Test: \r\n\r\n",
  7674. &out);
  7675. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  7676. }
  7677. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  7678. Server svr;
  7679. std::string x_custom;
  7680. std::string cookie;
  7681. std::string xff;
  7682. std::string x_unicode;
  7683. std::string x_iis;
  7684. svr.Get("/check", [&](const Request &req, Response &res) {
  7685. x_custom = req.get_header_value("X-Custom");
  7686. cookie = req.get_header_value("Cookie");
  7687. xff = req.get_header_value("X-Forwarded-For");
  7688. x_unicode = req.get_header_value("X-Unicode");
  7689. x_iis = req.get_header_value("X-IIS");
  7690. res.set_content("ok", "text/plain");
  7691. });
  7692. thread t = thread([&] { svr.listen(HOST, PORT); });
  7693. auto se = detail::scope_exit([&] {
  7694. svr.stop();
  7695. t.join();
  7696. ASSERT_FALSE(svr.is_running());
  7697. });
  7698. svr.wait_until_ready();
  7699. const std::string req = "GET /check HTTP/1.1\r\n"
  7700. "Host: localhost\r\n"
  7701. "X-Custom: a%0D%0AInjected: b\r\n"
  7702. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  7703. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  7704. "X-Unicode: %E3%81%82\r\n"
  7705. "X-IIS: %u00E9\r\n"
  7706. "Connection: close\r\n"
  7707. "\r\n";
  7708. std::string res;
  7709. ASSERT_TRUE(send_request(5, req, &res));
  7710. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7711. // Every value must be returned verbatim (wire form), with no decoding.
  7712. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  7713. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  7714. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  7715. EXPECT_EQ("%E3%81%82", x_unicode);
  7716. EXPECT_EQ("%u00E9", x_iis);
  7717. }
  7718. // Applications that previously relied on automatic percent-decoding can
  7719. // reproduce the old behavior by explicitly calling decode_path_component()
  7720. // or, for RFC 3986 conformance, decode_uri_component().
  7721. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  7722. Server svr;
  7723. std::string decoded;
  7724. svr.Get("/check", [&](const Request &req, Response &res) {
  7725. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  7726. res.set_content("ok", "text/plain");
  7727. });
  7728. thread t = thread([&] { svr.listen(HOST, PORT); });
  7729. auto se = detail::scope_exit([&] {
  7730. svr.stop();
  7731. t.join();
  7732. ASSERT_FALSE(svr.is_running());
  7733. });
  7734. svr.wait_until_ready();
  7735. const std::string req = "GET /check HTTP/1.1\r\n"
  7736. "Host: localhost\r\n"
  7737. "X-Custom: hello%20world\r\n"
  7738. "Connection: close\r\n"
  7739. "\r\n";
  7740. std::string res;
  7741. ASSERT_TRUE(send_request(5, req, &res));
  7742. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7743. EXPECT_EQ("hello world", decoded);
  7744. }
  7745. // Regression test for #2033. Browsers send Referer values that include
  7746. // percent-encoded characters such as %0A inside the URL. Decoding the
  7747. // header value would either trip the post-decode CR/LF/NUL guard (the
  7748. // original bug, returning 400) or, after that guard was relaxed, silently
  7749. // store a literal LF — both unacceptable. The wire form must round-trip.
  7750. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  7751. Server svr;
  7752. std::string referer;
  7753. svr.Get("/check", [&](const Request &req, Response &res) {
  7754. referer = req.get_header_value("Referer");
  7755. res.set_content("ok", "text/plain");
  7756. });
  7757. thread t = thread([&] { svr.listen(HOST, PORT); });
  7758. auto se = detail::scope_exit([&] {
  7759. svr.stop();
  7760. t.join();
  7761. ASSERT_FALSE(svr.is_running());
  7762. });
  7763. svr.wait_until_ready();
  7764. const std::string req = "GET /check HTTP/1.1\r\n"
  7765. "Host: localhost\r\n"
  7766. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  7767. "Connection: close\r\n"
  7768. "\r\n";
  7769. std::string res;
  7770. ASSERT_TRUE(send_request(5, req, &res));
  7771. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7772. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  7773. }
  7774. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  7775. Server svr;
  7776. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  7777. res.set_header("Cache-Control", "no-cache");
  7778. res.set_chunked_content_provider(
  7779. "text/event-stream", [](size_t offset, DataSink &sink) {
  7780. std::string s = "data:";
  7781. s += std::to_string(offset);
  7782. s += "\n\n";
  7783. auto ret = sink.write(s.data(), s.size());
  7784. EXPECT_TRUE(ret);
  7785. std::this_thread::sleep_for(std::chrono::seconds(1));
  7786. return true;
  7787. });
  7788. });
  7789. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7790. svr.wait_until_ready();
  7791. Client client(HOST, PORT);
  7792. const Headers headers = {{"Accept", "text/event-stream"}};
  7793. auto get_thread = std::thread([&client, &headers]() {
  7794. auto res = client.Get(
  7795. "/events", headers,
  7796. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  7797. });
  7798. auto se = detail::scope_exit([&] {
  7799. svr.stop();
  7800. get_thread.join();
  7801. listen_thread.join();
  7802. ASSERT_FALSE(svr.is_running());
  7803. });
  7804. // Give GET time to get a few messages.
  7805. std::this_thread::sleep_for(std::chrono::seconds(2));
  7806. }
  7807. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  7808. httplib::Server svr;
  7809. svr.Post("/hi",
  7810. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  7811. res.status = StatusCode::OK_200;
  7812. });
  7813. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7814. svr.wait_until_ready();
  7815. Client cli(HOST, PORT);
  7816. auto res = cli.Post("/hi", "data", "text/plain");
  7817. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7818. EXPECT_EQ(StatusCode::OK_200, res->status);
  7819. svr.stop();
  7820. thread.join();
  7821. ASSERT_FALSE(svr.is_running());
  7822. res = cli.Post("/hi", "data", "text/plain");
  7823. ASSERT_FALSE(res);
  7824. }
  7825. TEST(ServerStopTest, ListenFailure) {
  7826. Server svr;
  7827. auto t = thread([&]() {
  7828. auto ret = svr.listen("????", PORT);
  7829. EXPECT_FALSE(ret);
  7830. });
  7831. svr.wait_until_ready();
  7832. svr.stop();
  7833. t.join();
  7834. }
  7835. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  7836. TEST(ServerStopTest, Decommision) {
  7837. Server svr;
  7838. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  7839. for (int i = 0; i < 4; i++) {
  7840. auto is_even = !(i % 2);
  7841. std::thread t{[&] {
  7842. try {
  7843. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  7844. if (is_even) {
  7845. throw std::runtime_error("Some thing that happens to go wrong.");
  7846. }
  7847. svr.listen(HOST, PORT);
  7848. } catch (...) { svr.decommission(); }
  7849. }};
  7850. svr.wait_until_ready();
  7851. // Server is up
  7852. {
  7853. Client cli(HOST, PORT);
  7854. auto res = cli.Get("/hi");
  7855. if (is_even) {
  7856. EXPECT_FALSE(res);
  7857. } else {
  7858. EXPECT_TRUE(res);
  7859. EXPECT_EQ("hi...", res->body);
  7860. }
  7861. }
  7862. svr.stop();
  7863. t.join();
  7864. // Server is down...
  7865. {
  7866. Client cli(HOST, PORT);
  7867. auto res = cli.Get("/hi");
  7868. EXPECT_FALSE(res);
  7869. }
  7870. }
  7871. }
  7872. #endif
  7873. // Helper function for string body upload progress tests
  7874. template <typename SetupHandler, typename ClientCall>
  7875. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  7876. ClientCall &&client_call,
  7877. const string &body) {
  7878. Server svr;
  7879. setup_handler(svr);
  7880. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7881. auto se = detail::scope_exit([&] {
  7882. svr.stop();
  7883. t.join();
  7884. });
  7885. svr.wait_until_ready();
  7886. Client cli(HOST, PORT);
  7887. vector<uint64_t> progress_values;
  7888. bool progress_called = false;
  7889. auto res =
  7890. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  7891. progress_values.push_back(current);
  7892. progress_called = true;
  7893. return true;
  7894. });
  7895. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7896. EXPECT_EQ(200, res->status);
  7897. EXPECT_TRUE(progress_called);
  7898. }
  7899. TEST(UploadProgressTest, PostStringBodyBasic) {
  7900. TestStringBodyUploadProgress(
  7901. [](Server &svr) {
  7902. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  7903. res.set_content("received", "text/plain");
  7904. });
  7905. },
  7906. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7907. return cli.Post("/test", body, "text/plain", progress_callback);
  7908. },
  7909. "test data for upload progress");
  7910. }
  7911. TEST(UploadProgressTest, PutStringBodyBasic) {
  7912. TestStringBodyUploadProgress(
  7913. [](Server &svr) {
  7914. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  7915. res.set_content("put received", "text/plain");
  7916. });
  7917. },
  7918. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7919. return cli.Put("/test", body, "text/plain", progress_callback);
  7920. },
  7921. "put test data for upload progress");
  7922. }
  7923. TEST(UploadProgressTest, PatchStringBodyBasic) {
  7924. TestStringBodyUploadProgress(
  7925. [](Server &svr) {
  7926. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  7927. res.set_content("patch received", "text/plain");
  7928. });
  7929. },
  7930. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7931. return cli.Patch("/test", body, "text/plain", progress_callback);
  7932. },
  7933. "patch test data for upload progress");
  7934. }
  7935. // Helper function for content provider upload progress tests
  7936. template <typename SetupHandler, typename ClientCall>
  7937. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  7938. ClientCall &&client_call) {
  7939. Server svr;
  7940. setup_handler(svr);
  7941. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7942. auto se = detail::scope_exit([&] {
  7943. svr.stop();
  7944. t.join();
  7945. });
  7946. svr.wait_until_ready();
  7947. Client cli(HOST, PORT);
  7948. vector<uint64_t> progress_values;
  7949. auto res =
  7950. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  7951. progress_values.push_back(current);
  7952. return true;
  7953. });
  7954. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7955. EXPECT_EQ(200, res->status);
  7956. EXPECT_FALSE(progress_values.empty());
  7957. }
  7958. TEST(UploadProgressTest, PostContentProviderProgress) {
  7959. TestContentProviderUploadProgress(
  7960. [](Server &svr) {
  7961. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  7962. res.set_content("provider received", "text/plain");
  7963. });
  7964. },
  7965. [](Client &cli, UploadProgress progress_callback) {
  7966. return cli.Post(
  7967. "/test", 10,
  7968. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  7969. sink.os << "test data";
  7970. return true;
  7971. },
  7972. "text/plain", progress_callback);
  7973. });
  7974. }
  7975. // Helper function for multipart upload progress tests
  7976. template <typename SetupHandler, typename ClientCall>
  7977. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  7978. ClientCall &&client_call,
  7979. const string &endpoint) {
  7980. Server svr;
  7981. setup_handler(svr);
  7982. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7983. auto se = detail::scope_exit([&] {
  7984. svr.stop();
  7985. t.join();
  7986. });
  7987. svr.wait_until_ready();
  7988. Client cli(HOST, PORT);
  7989. vector<uint64_t> progress_values;
  7990. UploadFormDataItems items = {
  7991. {"field1", "value1", "", ""},
  7992. {"field2", "longer value for progress tracking test", "", ""},
  7993. {"file1", "file content data for upload progress", "test.txt",
  7994. "text/plain"}};
  7995. auto res = client_call(cli, endpoint, items,
  7996. [&](uint64_t current, uint64_t /*total*/) -> bool {
  7997. progress_values.push_back(current);
  7998. return true;
  7999. });
  8000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8001. EXPECT_EQ(200, res->status);
  8002. EXPECT_FALSE(progress_values.empty());
  8003. }
  8004. TEST(UploadProgressTest, PostMultipartProgress) {
  8005. TestMultipartUploadProgress(
  8006. [](Server &svr) {
  8007. svr.Post("/multipart", [](const Request &req, Response &res) {
  8008. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  8009. res.set_content("multipart received", "text/plain");
  8010. });
  8011. },
  8012. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  8013. UploadProgress progress_callback) {
  8014. return cli.Post(endpoint, items, progress_callback);
  8015. },
  8016. "/multipart");
  8017. }
  8018. // Helper function for basic download progress tests
  8019. template <typename SetupHandler, typename ClientCall>
  8020. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  8021. ClientCall &&client_call, const string &endpoint,
  8022. size_t expected_content_size) {
  8023. Server svr;
  8024. setup_handler(svr);
  8025. thread t = thread([&]() { svr.listen(HOST, PORT); });
  8026. auto se = detail::scope_exit([&] {
  8027. svr.stop();
  8028. t.join();
  8029. });
  8030. svr.wait_until_ready();
  8031. Client cli(HOST, PORT);
  8032. vector<uint64_t> progress_values;
  8033. auto res = client_call(cli, endpoint,
  8034. [&](uint64_t current, uint64_t /*total*/) -> bool {
  8035. progress_values.push_back(current);
  8036. return true;
  8037. });
  8038. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8039. EXPECT_EQ(200, res->status);
  8040. EXPECT_FALSE(progress_values.empty());
  8041. EXPECT_EQ(expected_content_size, res->body.size());
  8042. }
  8043. TEST(DownloadProgressTest, GetBasic) {
  8044. TestBasicDownloadProgress(
  8045. [](Server &svr) {
  8046. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  8047. string content(1000, 'D');
  8048. res.set_content(content, "text/plain");
  8049. });
  8050. },
  8051. [](Client &cli, const string &endpoint,
  8052. DownloadProgress progress_callback) {
  8053. return cli.Get(endpoint, progress_callback);
  8054. },
  8055. "/download", 1000u);
  8056. }
  8057. // Helper function for content receiver download progress tests
  8058. template <typename SetupHandler, typename ClientCall>
  8059. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  8060. ClientCall &&client_call,
  8061. const string &endpoint,
  8062. size_t expected_content_size) {
  8063. Server svr;
  8064. setup_handler(svr);
  8065. thread t = thread([&]() { svr.listen(HOST, PORT); });
  8066. auto se = detail::scope_exit([&] {
  8067. svr.stop();
  8068. t.join();
  8069. });
  8070. svr.wait_until_ready();
  8071. Client cli(HOST, PORT);
  8072. vector<uint64_t> progress_values;
  8073. string received_body;
  8074. auto res = client_call(
  8075. cli, endpoint,
  8076. [&](const char *data, size_t data_length) -> bool {
  8077. received_body.append(data, data_length);
  8078. return true;
  8079. },
  8080. [&](uint64_t current, uint64_t /*total*/) -> bool {
  8081. progress_values.push_back(current);
  8082. return true;
  8083. });
  8084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8085. EXPECT_EQ(200, res->status);
  8086. EXPECT_FALSE(progress_values.empty());
  8087. EXPECT_EQ(expected_content_size, received_body.size());
  8088. EXPECT_TRUE(res->body.empty());
  8089. }
  8090. TEST(DownloadProgressTest, GetWithContentReceiver) {
  8091. TestContentReceiverDownloadProgress(
  8092. [](Server &svr) {
  8093. svr.Get("/download-receiver",
  8094. [](const Request & /*req*/, Response &res) {
  8095. string content(2000, 'R');
  8096. res.set_content(content, "text/plain");
  8097. });
  8098. },
  8099. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  8100. DownloadProgress progress_callback) {
  8101. return cli.Get(endpoint, content_receiver, progress_callback);
  8102. },
  8103. "/download-receiver", 2000u);
  8104. }
  8105. TEST(StreamingTest, NoContentLengthStreaming) {
  8106. Server svr;
  8107. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  8108. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  8109. if (offset < 6) {
  8110. sink.os << (offset < 3 ? "a" : "b");
  8111. } else {
  8112. sink.done();
  8113. }
  8114. return true;
  8115. });
  8116. });
  8117. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8118. auto listen_se = detail::scope_exit([&] {
  8119. svr.stop();
  8120. listen_thread.join();
  8121. ASSERT_FALSE(svr.is_running());
  8122. });
  8123. svr.wait_until_ready();
  8124. Client client(HOST, PORT);
  8125. auto get_thread = std::thread([&client]() {
  8126. std::string s;
  8127. auto res =
  8128. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  8129. s += std::string(data, len);
  8130. return true;
  8131. });
  8132. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8133. EXPECT_EQ(StatusCode::OK_200, res->status);
  8134. EXPECT_EQ("aaabbb", s);
  8135. });
  8136. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  8137. // Give GET time to get a few messages.
  8138. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  8139. }
  8140. TEST(MountTest, Unmount) {
  8141. Server svr;
  8142. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8143. auto se = detail::scope_exit([&] {
  8144. svr.stop();
  8145. listen_thread.join();
  8146. ASSERT_FALSE(svr.is_running());
  8147. });
  8148. svr.wait_until_ready();
  8149. Client cli("localhost", PORT);
  8150. svr.set_mount_point("/mount2", "./www2");
  8151. auto res = cli.Get("/");
  8152. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8153. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8154. res = cli.Get("/mount2/dir/test.html");
  8155. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8156. EXPECT_EQ(StatusCode::OK_200, res->status);
  8157. svr.set_mount_point("/", "./www");
  8158. res = cli.Get("/dir/");
  8159. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8160. EXPECT_EQ(StatusCode::OK_200, res->status);
  8161. svr.remove_mount_point("/");
  8162. res = cli.Get("/dir/");
  8163. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8164. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8165. svr.remove_mount_point("/mount2");
  8166. res = cli.Get("/mount2/dir/test.html");
  8167. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8168. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8169. }
  8170. TEST(MountTest, PathSegmentBoundary) {
  8171. Server svr;
  8172. svr.set_mount_point("/mount2", "./www2");
  8173. svr.set_mount_point("/", "./www");
  8174. auto port = svr.bind_to_any_port(HOST);
  8175. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  8176. auto se = detail::scope_exit([&] {
  8177. svr.stop();
  8178. listen_thread.join();
  8179. ASSERT_FALSE(svr.is_running());
  8180. });
  8181. svr.wait_until_ready();
  8182. Client cli(HOST, port);
  8183. auto res = cli.Get("/mount2/dir/test.html");
  8184. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8185. EXPECT_EQ(StatusCode::OK_200, res->status);
  8186. // "/mount2" must not match part-way through a path segment.
  8187. res = cli.Get("/mount2dir/test.html");
  8188. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8189. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8190. // A mount point ending in '/' keeps matching every path below it.
  8191. res = cli.Get("/dir/test.html");
  8192. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8193. EXPECT_EQ(StatusCode::OK_200, res->status);
  8194. }
  8195. TEST(MountTest, Redicect) {
  8196. Server svr;
  8197. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8198. auto se = detail::scope_exit([&] {
  8199. svr.stop();
  8200. listen_thread.join();
  8201. ASSERT_FALSE(svr.is_running());
  8202. });
  8203. svr.set_mount_point("/", "./www");
  8204. svr.wait_until_ready();
  8205. Client cli("localhost", PORT);
  8206. auto res = cli.Get("/dir/");
  8207. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8208. EXPECT_EQ(StatusCode::OK_200, res->status);
  8209. res = cli.Get("/dir");
  8210. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8211. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  8212. res = cli.Get("/file");
  8213. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8214. EXPECT_EQ(StatusCode::OK_200, res->status);
  8215. res = cli.Get("/file/");
  8216. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8217. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8218. cli.set_follow_location(true);
  8219. res = cli.Get("/dir");
  8220. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8221. EXPECT_EQ(StatusCode::OK_200, res->status);
  8222. }
  8223. TEST(MountTest, MultibytesPathName) {
  8224. Server svr;
  8225. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8226. auto se = detail::scope_exit([&] {
  8227. svr.stop();
  8228. listen_thread.join();
  8229. ASSERT_FALSE(svr.is_running());
  8230. });
  8231. svr.set_mount_point("/", "./www");
  8232. svr.wait_until_ready();
  8233. Client cli("localhost", PORT);
  8234. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  8235. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8236. EXPECT_EQ(StatusCode::OK_200, res->status);
  8237. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  8238. }
  8239. #ifdef _WIN32
  8240. // Issue #2435: mmap::open() must succeed even when another handle holds
  8241. // the file open for writing (e.g. an active log file).
  8242. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  8243. const char *path = "mmap_concurrent_writer_test.txt";
  8244. const char *content = "hello";
  8245. {
  8246. std::ofstream f(path, std::ios::binary);
  8247. f.write(content, static_cast<std::streamsize>(strlen(content)));
  8248. }
  8249. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  8250. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  8251. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  8252. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  8253. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  8254. detail::mmap m(path);
  8255. ASSERT_TRUE(m.is_open());
  8256. EXPECT_EQ(strlen(content), m.size());
  8257. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  8258. }
  8259. #endif
  8260. #ifndef _WIN32
  8261. // A failed ::mmap() must not be reported as an open mapping, otherwise data()
  8262. // hands the caller the MAP_FAILED sentinel. A directory is the easiest way to
  8263. // reach it, since ::open() and fstat() succeed for one but ::mmap() doesn't.
  8264. TEST(MmapTest, FailedMappingIsNotOpen) {
  8265. const char *path = "./mmap_failed_mapping_test_dir";
  8266. ASSERT_EQ(0, ::mkdir(path, 0755));
  8267. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  8268. detail::mmap m(path);
  8269. EXPECT_FALSE(m.is_open());
  8270. EXPECT_EQ(0U, m.size());
  8271. EXPECT_NE(static_cast<const void *>(m.data()),
  8272. static_cast<const void *>(MAP_FAILED));
  8273. }
  8274. #endif
  8275. TEST(KeepAliveTest, ReadTimeout) {
  8276. Server svr;
  8277. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  8278. std::this_thread::sleep_for(std::chrono::seconds(2));
  8279. res.set_content("a", "text/plain");
  8280. });
  8281. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  8282. res.set_content("b", "text/plain");
  8283. });
  8284. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8285. auto se = detail::scope_exit([&] {
  8286. svr.stop();
  8287. listen_thread.join();
  8288. ASSERT_FALSE(svr.is_running());
  8289. });
  8290. svr.wait_until_ready();
  8291. Client cli("localhost", PORT);
  8292. cli.set_keep_alive(true);
  8293. cli.set_read_timeout(std::chrono::seconds(1));
  8294. auto resa = cli.Get("/a");
  8295. ASSERT_FALSE(resa);
  8296. EXPECT_EQ(Error::Read, resa.error());
  8297. auto resb = cli.Get("/b");
  8298. ASSERT_TRUE(resb);
  8299. EXPECT_EQ(StatusCode::OK_200, resb->status);
  8300. EXPECT_EQ("b", resb->body);
  8301. }
  8302. TEST(KeepAliveTest, MaxCount) {
  8303. size_t keep_alive_max_count = 3;
  8304. Server svr;
  8305. svr.set_keep_alive_max_count(keep_alive_max_count);
  8306. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  8307. res.set_content("Hello World!", "text/plain");
  8308. });
  8309. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8310. auto se = detail::scope_exit([&] {
  8311. svr.stop();
  8312. listen_thread.join();
  8313. ASSERT_FALSE(svr.is_running());
  8314. });
  8315. svr.wait_until_ready();
  8316. Client cli(HOST, PORT);
  8317. cli.set_keep_alive(true);
  8318. for (size_t i = 0; i < 5; i++) {
  8319. auto result = cli.Get("/hi");
  8320. ASSERT_TRUE(result);
  8321. EXPECT_EQ(StatusCode::OK_200, result->status);
  8322. if (i == keep_alive_max_count - 1) {
  8323. EXPECT_EQ("close", result->get_header_value("Connection"));
  8324. } else {
  8325. EXPECT_FALSE(result->has_header("Connection"));
  8326. }
  8327. }
  8328. }
  8329. TEST(KeepAliveTest, Issue1041) {
  8330. Server svr;
  8331. svr.set_keep_alive_timeout(3);
  8332. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  8333. res.set_content("Hello World!", "text/plain");
  8334. });
  8335. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8336. auto se = detail::scope_exit([&] {
  8337. svr.stop();
  8338. listen_thread.join();
  8339. ASSERT_FALSE(svr.is_running());
  8340. });
  8341. svr.wait_until_ready();
  8342. Client cli(HOST, PORT);
  8343. cli.set_keep_alive(true);
  8344. auto result = cli.Get("/hi");
  8345. ASSERT_TRUE(result);
  8346. EXPECT_EQ(StatusCode::OK_200, result->status);
  8347. std::this_thread::sleep_for(std::chrono::seconds(5));
  8348. result = cli.Get("/hi");
  8349. ASSERT_TRUE(result);
  8350. EXPECT_EQ(StatusCode::OK_200, result->status);
  8351. }
  8352. TEST(KeepAliveTest, Issue1959) {
  8353. Server svr;
  8354. svr.set_keep_alive_timeout(5);
  8355. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  8356. res.set_content("a", "text/plain");
  8357. });
  8358. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8359. auto se = detail::scope_exit([&] {
  8360. if (!svr.is_running()) return;
  8361. svr.stop();
  8362. listen_thread.join();
  8363. ASSERT_FALSE(svr.is_running());
  8364. });
  8365. svr.wait_until_ready();
  8366. Client cli("localhost", PORT);
  8367. cli.set_keep_alive(true);
  8368. using namespace std::chrono;
  8369. auto start = steady_clock::now();
  8370. cli.Get("/a");
  8371. svr.stop();
  8372. listen_thread.join();
  8373. auto end = steady_clock::now();
  8374. auto elapsed = duration_cast<milliseconds>(end - start).count();
  8375. EXPECT_LT(elapsed, 5000);
  8376. }
  8377. #ifdef CPPHTTPLIB_SSL_ENABLED
  8378. TEST(KeepAliveTest, SSLClientReconnection) {
  8379. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8380. ASSERT_TRUE(svr.is_valid());
  8381. svr.set_keep_alive_timeout(1);
  8382. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  8383. res.set_content("Hello World!", "text/plain");
  8384. });
  8385. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8386. auto se = detail::scope_exit([&] {
  8387. svr.stop();
  8388. listen_thread.join();
  8389. ASSERT_FALSE(svr.is_running());
  8390. });
  8391. svr.wait_until_ready();
  8392. SSLClient cli(HOST, PORT);
  8393. cli.enable_server_certificate_verification(false);
  8394. cli.set_keep_alive(true);
  8395. auto result = cli.Get("/hi");
  8396. ASSERT_TRUE(result);
  8397. EXPECT_EQ(StatusCode::OK_200, result->status);
  8398. result = cli.Get("/hi");
  8399. ASSERT_TRUE(result);
  8400. EXPECT_EQ(StatusCode::OK_200, result->status);
  8401. std::this_thread::sleep_for(std::chrono::seconds(2));
  8402. // Recoonect
  8403. result = cli.Get("/hi");
  8404. ASSERT_TRUE(result);
  8405. EXPECT_EQ(StatusCode::OK_200, result->status);
  8406. result = cli.Get("/hi");
  8407. ASSERT_TRUE(result);
  8408. EXPECT_EQ(StatusCode::OK_200, result->status);
  8409. }
  8410. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  8411. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8412. ASSERT_TRUE(svr.is_valid());
  8413. svr.set_keep_alive_timeout(1);
  8414. std::string content = "reconnect";
  8415. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  8416. res.set_content("Hello World!", "text/plain");
  8417. });
  8418. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8419. auto se = detail::scope_exit([&] {
  8420. svr.stop();
  8421. listen_thread.join();
  8422. ASSERT_FALSE(svr.is_running());
  8423. });
  8424. svr.wait_until_ready();
  8425. SSLClient cli(HOST, PORT);
  8426. cli.enable_server_certificate_verification(false);
  8427. cli.set_keep_alive(true);
  8428. auto result = cli.Post(
  8429. "/hi", content.size(),
  8430. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8431. sink.write(content.c_str(), content.size());
  8432. return true;
  8433. },
  8434. "text/plain");
  8435. ASSERT_TRUE(result);
  8436. EXPECT_EQ(200, result->status);
  8437. std::this_thread::sleep_for(std::chrono::seconds(2));
  8438. // Recoonect
  8439. result = cli.Post(
  8440. "/hi", content.size(),
  8441. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8442. sink.write(content.c_str(), content.size());
  8443. return true;
  8444. },
  8445. "text/plain");
  8446. ASSERT_TRUE(result);
  8447. EXPECT_EQ(200, result->status);
  8448. result = cli.Post(
  8449. "/hi", content.size(),
  8450. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8451. sink.write(content.c_str(), content.size());
  8452. return true;
  8453. },
  8454. "text/plain");
  8455. ASSERT_TRUE(result);
  8456. EXPECT_EQ(200, result->status);
  8457. }
  8458. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  8459. using namespace httplib::tls;
  8460. {
  8461. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8462. ASSERT_TRUE(svr.is_valid());
  8463. svr.Get("/sni", [&](const Request &req, Response &res) {
  8464. std::string expected = req.sni();
  8465. EXPECT_EQ(expected, req.get_param_value("expected"));
  8466. res.set_content("ok", "text/plain");
  8467. });
  8468. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8469. auto se = detail::scope_exit([&] {
  8470. svr.stop();
  8471. listen_thread.join();
  8472. ASSERT_FALSE(svr.is_running());
  8473. });
  8474. svr.wait_until_ready();
  8475. {
  8476. SSLClient cli("localhost", PORT);
  8477. cli.enable_server_certificate_verification(false);
  8478. auto res = cli.Get("/sni?expected=localhost");
  8479. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8480. }
  8481. {
  8482. SSLClient cli("::1", PORT);
  8483. cli.enable_server_certificate_verification(false);
  8484. auto res = cli.Get("/sni?expected=");
  8485. // NOTE: This may fail if the server is listening on IPv4 only
  8486. // (e.g., when localhost resolves to 127.0.0.1 only)
  8487. if (res) {
  8488. EXPECT_EQ(StatusCode::OK_200, res->status);
  8489. } else {
  8490. EXPECT_EQ(Error::Connection, res.error());
  8491. }
  8492. }
  8493. }
  8494. }
  8495. #endif
  8496. TEST(ClientProblemDetectionTest, ContentProvider) {
  8497. Server svr;
  8498. size_t content_length = 1024 * 1024;
  8499. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  8500. res.set_content_provider(
  8501. content_length, "text/plain",
  8502. [&](size_t offset, size_t length, DataSink &sink) {
  8503. auto out_len = std::min(length, static_cast<size_t>(1024));
  8504. std::string out(out_len, '@');
  8505. sink.write(out.data(), out_len);
  8506. return offset < 4096;
  8507. },
  8508. [](bool success) { ASSERT_FALSE(success); });
  8509. });
  8510. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  8511. res.set_content_provider(
  8512. 0, "text/plain",
  8513. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  8514. EXPECT_TRUE(false);
  8515. return true;
  8516. },
  8517. [](bool success) { ASSERT_FALSE(success); });
  8518. });
  8519. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8520. auto se = detail::scope_exit([&] {
  8521. svr.stop();
  8522. listen_thread.join();
  8523. ASSERT_FALSE(svr.is_running());
  8524. });
  8525. svr.wait_until_ready();
  8526. Client cli("localhost", PORT);
  8527. {
  8528. auto res = cli.Get("/hi", [&](const char * /*data*/,
  8529. size_t /*data_length*/) { return false; });
  8530. ASSERT_FALSE(res);
  8531. }
  8532. {
  8533. auto res = cli.Get("/empty", [&](const char * /*data*/,
  8534. size_t /*data_length*/) { return false; });
  8535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8536. }
  8537. }
  8538. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  8539. Server svr;
  8540. svr.set_error_handler([](Request const &, Response &res) -> void {
  8541. res.set_chunked_content_provider(
  8542. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  8543. sink.os << "hello";
  8544. sink.os << "world";
  8545. sink.done();
  8546. return true;
  8547. });
  8548. });
  8549. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8550. auto se = detail::scope_exit([&] {
  8551. svr.stop();
  8552. listen_thread.join();
  8553. ASSERT_FALSE(svr.is_running());
  8554. });
  8555. svr.wait_until_ready();
  8556. Client cli("localhost", PORT);
  8557. auto res = cli.Get("/");
  8558. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8559. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8560. EXPECT_EQ("helloworld", res->body);
  8561. }
  8562. TEST(LongPollingTest, ClientCloseDetection) {
  8563. Server svr;
  8564. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  8565. res.set_chunked_content_provider(
  8566. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  8567. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  8568. sink.os << "hello";
  8569. auto count = 10;
  8570. while (count > 0 && sink.is_writable()) {
  8571. this_thread::sleep_for(chrono::milliseconds(10));
  8572. count--;
  8573. }
  8574. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  8575. return true;
  8576. });
  8577. });
  8578. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8579. auto se = detail::scope_exit([&] {
  8580. svr.stop();
  8581. listen_thread.join();
  8582. ASSERT_FALSE(svr.is_running());
  8583. });
  8584. svr.wait_until_ready();
  8585. Client cli("localhost", PORT);
  8586. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  8587. EXPECT_EQ("hello", string(data, data_length));
  8588. return false; // close the socket immediately.
  8589. });
  8590. ASSERT_FALSE(res);
  8591. }
  8592. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  8593. Server svr;
  8594. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  8595. res.set_chunked_content_provider(
  8596. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  8597. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  8598. sink.os << "hello";
  8599. EXPECT_TRUE(sink.os.good());
  8600. // Wait for the client to close the connection
  8601. auto count = 10;
  8602. while (count > 0 && sink.is_writable()) {
  8603. this_thread::sleep_for(chrono::milliseconds(10));
  8604. count--;
  8605. }
  8606. // After client disconnect, write repeatedly until the socket
  8607. // write actually fails (small writes may be absorbed by the
  8608. // kernel buffer)
  8609. std::string chunk(1024, 'x');
  8610. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  8611. sink.os << chunk;
  8612. }
  8613. EXPECT_TRUE(sink.os.fail());
  8614. return true;
  8615. });
  8616. });
  8617. auto port = svr.bind_to_any_port("localhost");
  8618. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  8619. auto se = detail::scope_exit([&] {
  8620. svr.stop();
  8621. listen_thread.join();
  8622. ASSERT_FALSE(svr.is_running());
  8623. });
  8624. svr.wait_until_ready();
  8625. Client cli("localhost", port);
  8626. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  8627. EXPECT_EQ("hello", string(data, data_length));
  8628. return false; // close the socket immediately.
  8629. });
  8630. ASSERT_FALSE(res);
  8631. }
  8632. TEST(GetWithParametersTest, GetWithParameters) {
  8633. Server svr;
  8634. svr.Get("/", [&](const Request &req, Response &) {
  8635. EXPECT_EQ("world", req.get_param_value("hello"));
  8636. EXPECT_EQ("world2", req.get_param_value("hello2"));
  8637. EXPECT_EQ("world3", req.get_param_value("hello3"));
  8638. });
  8639. svr.Get("/params", [&](const Request &req, Response &) {
  8640. EXPECT_EQ("world", req.get_param_value("hello"));
  8641. EXPECT_EQ("world2", req.get_param_value("hello2"));
  8642. EXPECT_EQ("world3", req.get_param_value("hello3"));
  8643. });
  8644. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  8645. EXPECT_EQ("resource-id", req.matches[1]);
  8646. EXPECT_EQ("foo", req.get_param_value("param1"));
  8647. EXPECT_EQ("bar", req.get_param_value("param2"));
  8648. });
  8649. svr.Get("/users/:id", [&](const Request &req, Response &) {
  8650. EXPECT_EQ("user-id", req.path_params.at("id"));
  8651. EXPECT_EQ("foo", req.get_param_value("param1"));
  8652. EXPECT_EQ("bar", req.get_param_value("param2"));
  8653. });
  8654. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  8655. auto se = detail::scope_exit([&] {
  8656. svr.stop();
  8657. listen_thread.join();
  8658. ASSERT_FALSE(svr.is_running());
  8659. });
  8660. svr.wait_until_ready();
  8661. {
  8662. Client cli(HOST, PORT);
  8663. Params params;
  8664. params.emplace("hello", "world");
  8665. params.emplace("hello2", "world2");
  8666. params.emplace("hello3", "world3");
  8667. auto res = cli.Get("/", params, Headers{});
  8668. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8669. EXPECT_EQ(StatusCode::OK_200, res->status);
  8670. }
  8671. {
  8672. Client cli(HOST, PORT);
  8673. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  8674. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8675. EXPECT_EQ(StatusCode::OK_200, res->status);
  8676. }
  8677. {
  8678. Client cli(HOST, PORT);
  8679. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  8680. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8681. EXPECT_EQ(StatusCode::OK_200, res->status);
  8682. }
  8683. {
  8684. Client cli(HOST, PORT);
  8685. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  8686. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8687. EXPECT_EQ(StatusCode::OK_200, res->status);
  8688. }
  8689. }
  8690. TEST(GetWithParametersTest, GetWithParameters2) {
  8691. Server svr;
  8692. svr.Get("/", [&](const Request &req, Response &res) {
  8693. auto text = req.get_param_value("hello");
  8694. res.set_content(text, "text/plain");
  8695. });
  8696. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8697. auto se = detail::scope_exit([&] {
  8698. svr.stop();
  8699. listen_thread.join();
  8700. ASSERT_FALSE(svr.is_running());
  8701. });
  8702. svr.wait_until_ready();
  8703. Client cli("localhost", PORT);
  8704. Params params;
  8705. params.emplace("hello", "world");
  8706. std::string body;
  8707. auto res = cli.Get("/", params, Headers{},
  8708. [&](const char *data, size_t data_length) {
  8709. body.append(data, data_length);
  8710. return true;
  8711. });
  8712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8713. EXPECT_EQ(StatusCode::OK_200, res->status);
  8714. EXPECT_EQ("world", body);
  8715. }
  8716. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  8717. Server svr;
  8718. svr.Get("/search", [&](const Request &req, Response &res) {
  8719. auto q = req.get_param_value("q");
  8720. res.set_content(q, "text/plain");
  8721. });
  8722. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8723. auto se = detail::scope_exit([&] {
  8724. svr.stop();
  8725. listen_thread.join();
  8726. ASSERT_FALSE(svr.is_running());
  8727. });
  8728. svr.wait_until_ready();
  8729. Client cli("localhost", PORT);
  8730. // Verify that Get(path, params) works without requiring Headers argument
  8731. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  8732. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8733. EXPECT_EQ(StatusCode::OK_200, res->status);
  8734. EXPECT_EQ("cpp-httplib", res->body);
  8735. }
  8736. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  8737. auto host = "httpbingo.org";
  8738. auto path = std::string{"/range/32"};
  8739. #ifdef CPPHTTPLIB_SSL_ENABLED
  8740. SSLClient cli(host);
  8741. #else
  8742. Client cli(host);
  8743. #endif
  8744. cli.set_default_headers({make_range_header({{1, 10}})});
  8745. cli.set_connection_timeout(5);
  8746. {
  8747. auto res = cli.Get(path);
  8748. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8749. EXPECT_EQ("bcdefghijk", res->body);
  8750. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8751. }
  8752. {
  8753. auto res = cli.Get(path);
  8754. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8755. EXPECT_EQ("bcdefghijk", res->body);
  8756. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8757. }
  8758. }
  8759. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  8760. Server svr;
  8761. svr.set_default_headers({{"Hello", "World"}});
  8762. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  8763. res.set_content("ok", "text/plain");
  8764. });
  8765. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8766. auto se = detail::scope_exit([&] {
  8767. svr.stop();
  8768. listen_thread.join();
  8769. ASSERT_FALSE(svr.is_running());
  8770. });
  8771. svr.wait_until_ready();
  8772. Client cli("localhost", PORT);
  8773. auto res = cli.Get("/");
  8774. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8775. EXPECT_EQ(StatusCode::OK_200, res->status);
  8776. EXPECT_EQ("ok", res->body);
  8777. EXPECT_EQ("World", res->get_header_value("Hello"));
  8778. }
  8779. #ifdef CPPHTTPLIB_SSL_ENABLED
  8780. TEST(KeepAliveTest, ReadTimeoutSSL) {
  8781. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8782. ASSERT_TRUE(svr.is_valid());
  8783. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  8784. std::this_thread::sleep_for(std::chrono::seconds(2));
  8785. res.set_content("a", "text/plain");
  8786. });
  8787. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  8788. res.set_content("b", "text/plain");
  8789. });
  8790. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8791. auto se = detail::scope_exit([&] {
  8792. svr.stop();
  8793. listen_thread.join();
  8794. ASSERT_FALSE(svr.is_running());
  8795. });
  8796. svr.wait_until_ready();
  8797. SSLClient cli("localhost", PORT);
  8798. cli.enable_server_certificate_verification(false);
  8799. cli.set_keep_alive(true);
  8800. cli.set_read_timeout(std::chrono::seconds(1));
  8801. auto resa = cli.Get("/a");
  8802. ASSERT_TRUE(!resa);
  8803. EXPECT_EQ(Error::Read, resa.error());
  8804. auto resb = cli.Get("/b");
  8805. ASSERT_TRUE(resb);
  8806. EXPECT_EQ(StatusCode::OK_200, resb->status);
  8807. EXPECT_EQ("b", resb->body);
  8808. }
  8809. #endif
  8810. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  8811. protected:
  8812. ServerTestWithAI_PASSIVE()
  8813. : cli_(HOST, PORT)
  8814. #ifdef CPPHTTPLIB_SSL_ENABLED
  8815. ,
  8816. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  8817. #endif
  8818. {
  8819. #ifdef CPPHTTPLIB_SSL_ENABLED
  8820. cli_.enable_server_certificate_verification(false);
  8821. #endif
  8822. }
  8823. virtual void SetUp() {
  8824. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  8825. res.set_content("Hello World!", "text/plain");
  8826. });
  8827. t_ = thread(
  8828. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  8829. svr_.wait_until_ready();
  8830. }
  8831. virtual void TearDown() {
  8832. svr_.stop();
  8833. t_.join();
  8834. }
  8835. #ifdef CPPHTTPLIB_SSL_ENABLED
  8836. SSLClient cli_;
  8837. SSLServer svr_;
  8838. #else
  8839. Client cli_;
  8840. Server svr_;
  8841. #endif
  8842. thread t_;
  8843. };
  8844. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  8845. auto res = cli_.Get("/hi");
  8846. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8847. EXPECT_EQ(StatusCode::OK_200, res->status);
  8848. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8849. EXPECT_EQ("Hello World!", res->body);
  8850. }
  8851. class ServerUpDownTest : public ::testing::Test {
  8852. protected:
  8853. ServerUpDownTest() : cli_(HOST, PORT) {}
  8854. virtual void SetUp() {
  8855. t_ = thread([&]() {
  8856. svr_.bind_to_any_port(HOST);
  8857. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  8858. ASSERT_TRUE(svr_.listen_after_bind());
  8859. });
  8860. svr_.wait_until_ready();
  8861. }
  8862. virtual void TearDown() {
  8863. svr_.stop();
  8864. t_.join();
  8865. }
  8866. Client cli_;
  8867. Server svr_;
  8868. thread t_;
  8869. };
  8870. TEST_F(ServerUpDownTest, QuickStartStop) {
  8871. // Should not crash, especially when run with
  8872. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  8873. }
  8874. class PayloadMaxLengthTest : public ::testing::Test {
  8875. protected:
  8876. PayloadMaxLengthTest()
  8877. : cli_(HOST, PORT)
  8878. #ifdef CPPHTTPLIB_SSL_ENABLED
  8879. ,
  8880. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  8881. #endif
  8882. {
  8883. #ifdef CPPHTTPLIB_SSL_ENABLED
  8884. cli_.enable_server_certificate_verification(false);
  8885. #endif
  8886. }
  8887. virtual void SetUp() {
  8888. svr_.set_payload_max_length(8);
  8889. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  8890. res.set_content("test", "text/plain");
  8891. });
  8892. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  8893. svr_.wait_until_ready();
  8894. }
  8895. virtual void TearDown() {
  8896. svr_.stop();
  8897. t_.join();
  8898. }
  8899. #ifdef CPPHTTPLIB_SSL_ENABLED
  8900. SSLClient cli_;
  8901. SSLServer svr_;
  8902. #else
  8903. Client cli_;
  8904. Server svr_;
  8905. #endif
  8906. thread t_;
  8907. };
  8908. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  8909. auto res = cli_.Post("/test", "123456789", "text/plain");
  8910. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8911. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8912. res = cli_.Post("/test", "12345678", "text/plain");
  8913. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8914. EXPECT_EQ(StatusCode::OK_200, res->status);
  8915. }
  8916. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  8917. // Test chunked encoding with payload exceeding the 8-byte limit
  8918. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  8919. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  8920. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8921. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8922. }
  8923. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  8924. // Test chunked encoding with payload within the 8-byte limit
  8925. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  8926. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  8927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8928. EXPECT_EQ(StatusCode::OK_200, res->status);
  8929. }
  8930. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  8931. // Test using send_request to send chunked data exceeding payload limit
  8932. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  8933. "Host: " +
  8934. std::string(HOST) + ":" + std::to_string(PORT) +
  8935. "\r\n"
  8936. "Transfer-Encoding: chunked\r\n"
  8937. "Connection: close\r\n"
  8938. "\r\n"
  8939. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  8940. "0123456789\r\n"
  8941. "0\r\n" // End chunk
  8942. "\r\n";
  8943. std::string response;
  8944. bool result = send_request(1, chunked_request, &response);
  8945. if (!result) {
  8946. // If send_request fails, it might be because the server closed the
  8947. // connection due to payload limit enforcement, which is acceptable
  8948. SUCCEED()
  8949. << "Server rejected oversized chunked request (connection closed)";
  8950. } else {
  8951. // If we got a response, check if it's an error response or connection was
  8952. // closed early Short response length indicates connection was closed due to
  8953. // payload limit
  8954. if (response.length() <= 10) {
  8955. SUCCEED() << "Server closed connection for oversized chunked request";
  8956. } else {
  8957. // Check for error status codes
  8958. EXPECT_TRUE(response.find("413") != std::string::npos ||
  8959. response.find("Payload Too Large") != std::string::npos ||
  8960. response.find("400") != std::string::npos);
  8961. }
  8962. }
  8963. }
  8964. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  8965. // Test request without Content-Length header exceeding payload limit
  8966. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8967. "Host: " +
  8968. std::string(HOST) + ":" +
  8969. std::to_string(PORT) +
  8970. "\r\n"
  8971. "Connection: close\r\n"
  8972. "\r\n";
  8973. // Add payload exceeding the 8-byte limit
  8974. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  8975. request_without_content_length += large_payload;
  8976. std::string response;
  8977. bool result = send_request(1, request_without_content_length, &response);
  8978. if (!result) {
  8979. // If send_request fails, server likely closed connection due to payload
  8980. // limit
  8981. SUCCEED() << "Server rejected oversized request without Content-Length "
  8982. "(connection closed)";
  8983. } else {
  8984. // Check if server responded with error or closed connection early
  8985. if (response.length() <= 10) {
  8986. SUCCEED() << "Server closed connection for oversized request without "
  8987. "Content-Length";
  8988. } else {
  8989. // Check for error status codes
  8990. EXPECT_TRUE(response.find("413") != std::string::npos ||
  8991. response.find("Payload Too Large") != std::string::npos ||
  8992. response.find("400") != std::string::npos);
  8993. }
  8994. }
  8995. }
  8996. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  8997. // Test request without Content-Length header within payload limit
  8998. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8999. "Host: " +
  9000. std::string(HOST) + ":" +
  9001. std::to_string(PORT) +
  9002. "\r\n"
  9003. "Connection: close\r\n"
  9004. "\r\n";
  9005. // Add payload within the 8-byte limit
  9006. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  9007. request_without_content_length += small_payload;
  9008. std::string response;
  9009. bool result = send_request(1, request_without_content_length, &response);
  9010. // For requests without Content-Length, the server may have different behavior
  9011. // The key is that it should not reject due to payload limit for small
  9012. // payloads
  9013. if (result) {
  9014. // Check for any HTTP response (success or error, but not connection closed)
  9015. if (response.length() > 10) {
  9016. SUCCEED()
  9017. << "Server processed request without Content-Length within limit";
  9018. } else {
  9019. // Short response might indicate connection closed, which is acceptable
  9020. SUCCEED() << "Server closed connection for request without "
  9021. "Content-Length (acceptable behavior)";
  9022. }
  9023. } else {
  9024. // Connection failure might be due to protocol requirements
  9025. SUCCEED() << "Connection issue with request without Content-Length "
  9026. "(environment-specific)";
  9027. }
  9028. }
  9029. class LargePayloadMaxLengthTest : public ::testing::Test {
  9030. protected:
  9031. LargePayloadMaxLengthTest()
  9032. : cli_(HOST, PORT)
  9033. #ifdef CPPHTTPLIB_SSL_ENABLED
  9034. ,
  9035. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  9036. #endif
  9037. {
  9038. #ifdef CPPHTTPLIB_SSL_ENABLED
  9039. cli_.enable_server_certificate_verification(false);
  9040. #endif
  9041. }
  9042. virtual void SetUp() {
  9043. // Set 10MB payload limit
  9044. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  9045. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  9046. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  9047. res.set_content("Large payload test", "text/plain");
  9048. });
  9049. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  9050. svr_.wait_until_ready();
  9051. }
  9052. virtual void TearDown() {
  9053. svr_.stop();
  9054. t_.join();
  9055. }
  9056. #ifdef CPPHTTPLIB_SSL_ENABLED
  9057. SSLClient cli_;
  9058. SSLServer svr_;
  9059. #else
  9060. Client cli_;
  9061. Server svr_;
  9062. #endif
  9063. thread t_;
  9064. };
  9065. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  9066. // Test chunked encoding with payload within 10MB limit
  9067. std::string medium_payload(5 * 1024 * 1024,
  9068. 'A'); // 5MB payload, within 10MB limit
  9069. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  9070. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9071. EXPECT_EQ(StatusCode::OK_200, res->status);
  9072. }
  9073. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  9074. // Test chunked encoding with payload exceeding 10MB limit
  9075. std::string large_payload(12 * 1024 * 1024,
  9076. 'B'); // 12MB payload, exceeds 10MB limit
  9077. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  9078. // Server may either return 413 or close the connection
  9079. if (res) {
  9080. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  9081. } else {
  9082. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  9083. }
  9084. }
  9085. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  9086. // Test request without Content-Length header within 10MB limit
  9087. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  9088. "Host: " +
  9089. std::string(HOST) + ":" +
  9090. std::to_string(PORT) +
  9091. "\r\n"
  9092. "Connection: close\r\n"
  9093. "\r\n";
  9094. // Add 1MB payload (within 10MB limit)
  9095. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  9096. request_without_content_length += medium_payload;
  9097. std::string response;
  9098. bool result = send_request(5, request_without_content_length, &response);
  9099. if (result) {
  9100. // Should get a proper HTTP response for payloads within limit
  9101. if (response.length() > 10) {
  9102. SUCCEED() << "Server processed 1MB request without Content-Length within "
  9103. "10MB limit";
  9104. } else {
  9105. SUCCEED() << "Server closed connection (acceptable behavior for no "
  9106. "Content-Length)";
  9107. }
  9108. } else {
  9109. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  9110. }
  9111. }
  9112. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  9113. // Test request without Content-Length header exceeding 10MB limit
  9114. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  9115. "Host: " +
  9116. std::string(HOST) + ":" +
  9117. std::to_string(PORT) +
  9118. "\r\n"
  9119. "Connection: close\r\n"
  9120. "\r\n";
  9121. // Add 12MB payload (exceeds 10MB limit)
  9122. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  9123. request_without_content_length += large_payload;
  9124. std::string response;
  9125. bool result = send_request(10, request_without_content_length, &response);
  9126. if (!result) {
  9127. // Server should close connection due to payload limit
  9128. SUCCEED() << "Server rejected 12MB request without Content-Length "
  9129. "(connection closed)";
  9130. } else {
  9131. // Check for error response
  9132. if (response.length() <= 10) {
  9133. SUCCEED()
  9134. << "Server closed connection for 12MB request exceeding 10MB limit";
  9135. } else {
  9136. EXPECT_TRUE(response.find("413") != std::string::npos ||
  9137. response.find("Payload Too Large") != std::string::npos ||
  9138. response.find("400") != std::string::npos);
  9139. }
  9140. }
  9141. }
  9142. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9143. // `payload_max_length` is not enforced on decompressed body in ContentReader
  9144. // path.
  9145. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  9146. Server svr;
  9147. const size_t LIMIT = 64 * 1024; // 64KB
  9148. svr.set_payload_max_length(LIMIT);
  9149. size_t total = 0;
  9150. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  9151. const ContentReader &content_reader) {
  9152. content_reader([&](const char * /*data*/, size_t len) {
  9153. total += len;
  9154. return true;
  9155. });
  9156. res.status = 200;
  9157. res.set_content("stream_ok", "text/plain");
  9158. });
  9159. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9160. auto se = detail::scope_exit([&] {
  9161. svr.stop();
  9162. thread.join();
  9163. ASSERT_FALSE(svr.is_running());
  9164. });
  9165. svr.wait_until_ready();
  9166. // Prepare 256KB raw data and gzip-compress it
  9167. std::string raw(256 * 1024, 'A');
  9168. std::string gz;
  9169. {
  9170. z_stream zs{};
  9171. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  9172. Z_DEFAULT_STRATEGY);
  9173. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  9174. zs.avail_in = static_cast<uInt>(raw.size());
  9175. char outbuf[4096];
  9176. int ret;
  9177. do {
  9178. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  9179. zs.avail_out = sizeof(outbuf);
  9180. ret = deflate(&zs, Z_FINISH);
  9181. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  9182. } while (ret != Z_STREAM_END);
  9183. deflateEnd(&zs);
  9184. }
  9185. Client cli(HOST, PORT);
  9186. cli.set_connection_timeout(std::chrono::seconds(5));
  9187. Headers headers = {{"Content-Encoding", "gzip"}};
  9188. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  9189. "application/octet-stream");
  9190. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9191. // Server must reject oversized decompressed payloads with 413.
  9192. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  9193. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  9194. EXPECT_LE(total, LIMIT);
  9195. }
  9196. #ifndef CPPHTTPLIB_SSL_ENABLED
  9197. // For a request with neither Content-Length nor Transfer-Encoding, the
  9198. // non-SSL raw-socket fallback in read_content_core() used to hand the
  9199. // compressed wire bytes straight to the ContentReader without ever routing
  9200. // them through the decompressor, so payload_max_length_ only bounded the
  9201. // compressed size on the wire, not the decompressed size.
  9202. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  9203. Server svr;
  9204. const size_t LIMIT = 64 * 1024; // 64KB
  9205. svr.set_payload_max_length(LIMIT);
  9206. size_t total = 0;
  9207. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  9208. const ContentReader &content_reader) {
  9209. content_reader([&](const char * /*data*/, size_t len) {
  9210. total += len;
  9211. return true;
  9212. });
  9213. res.status = 200;
  9214. res.set_content("stream_ok", "text/plain");
  9215. });
  9216. auto port = svr.bind_to_any_port(HOST);
  9217. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9218. auto se = detail::scope_exit([&] {
  9219. svr.stop();
  9220. thread.join();
  9221. ASSERT_FALSE(svr.is_running());
  9222. });
  9223. svr.wait_until_ready();
  9224. // Prepare 256KB raw data and gzip-compress it, same payload as the
  9225. // StreamingGzipDecompression test above.
  9226. std::string raw(256 * 1024, 'A');
  9227. std::string gz;
  9228. {
  9229. httplib::detail::gzip_compressor compressor;
  9230. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  9231. [&](const char *chunk, size_t len) {
  9232. gz.append(chunk, len);
  9233. return true;
  9234. });
  9235. ASSERT_TRUE(result);
  9236. }
  9237. // Send the gzip body over raw TCP with neither Content-Length nor
  9238. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  9239. // kicks in.
  9240. std::string req = "POST /stream HTTP/1.1\r\n"
  9241. "Host: " +
  9242. std::string(HOST) + ":" + std::to_string(port) +
  9243. "\r\n"
  9244. "Content-Encoding: gzip\r\n"
  9245. "Connection: close\r\n"
  9246. "\r\n" +
  9247. gz;
  9248. std::string response;
  9249. ASSERT_TRUE(send_request(5, req, &response, port));
  9250. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  9251. EXPECT_LE(total, LIMIT);
  9252. }
  9253. #endif
  9254. #endif
  9255. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  9256. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  9257. // the payload must be passed through untouched instead of being rejected.
  9258. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  9259. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  9260. Server svr;
  9261. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  9262. res.set_content(body, "image/jpeg");
  9263. res.set_header("Content-Encoding", "UTF-8");
  9264. });
  9265. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  9266. res.set_content(body, "image/jpeg");
  9267. res.set_header("Content-Encoding", "identity");
  9268. });
  9269. svr.Post("/echo", [](const Request &req, Response &res) {
  9270. res.set_content(req.body, "image/jpeg");
  9271. });
  9272. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9273. auto se = detail::scope_exit([&] {
  9274. svr.stop();
  9275. t.join();
  9276. ASSERT_FALSE(svr.is_running());
  9277. });
  9278. svr.wait_until_ready();
  9279. Client cli(HOST, PORT);
  9280. {
  9281. auto res = cli.Get("/image");
  9282. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9283. EXPECT_EQ(StatusCode::OK_200, res->status);
  9284. EXPECT_EQ(body, res->body);
  9285. }
  9286. {
  9287. auto res = cli.Get("/identity");
  9288. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9289. EXPECT_EQ(StatusCode::OK_200, res->status);
  9290. EXPECT_EQ(body, res->body);
  9291. }
  9292. {
  9293. // The same applies to a request body reaching the server.
  9294. Headers headers = {{"Content-Encoding", "UTF-8"}};
  9295. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  9296. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9297. EXPECT_EQ(StatusCode::OK_200, res->status);
  9298. EXPECT_EQ(body, res->body);
  9299. }
  9300. }
  9301. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  9302. // gzip-encoded response even when the build has no zlib support.
  9303. static const char GZIPPED_HELLO_WORLD[] = {
  9304. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  9305. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  9306. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  9307. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  9308. // A content coding is a whole token, not something the field value merely
  9309. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  9310. // as "fibre" look like Brotli, and turned a multi-coding value like
  9311. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  9312. // it was never meant to see.
  9313. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  9314. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  9315. Server svr;
  9316. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  9317. res.set_content(body, "image/jpeg");
  9318. res.set_header("Content-Encoding", "fibre");
  9319. });
  9320. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  9321. res.set_content(body, "image/jpeg");
  9322. res.set_header("Content-Encoding", "gzip, br");
  9323. });
  9324. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  9325. res.set_content(body, "image/jpeg");
  9326. res.set_header("Content-Encoding", "x-zstd-ish");
  9327. });
  9328. auto port = svr.bind_to_any_port(HOST);
  9329. thread t = thread([&]() { svr.listen_after_bind(); });
  9330. auto se = detail::scope_exit([&] {
  9331. svr.stop();
  9332. t.join();
  9333. ASSERT_FALSE(svr.is_running());
  9334. });
  9335. svr.wait_until_ready();
  9336. Client cli(HOST, port);
  9337. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  9338. auto res = cli.Get(path);
  9339. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  9340. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  9341. // Not a coding we recognize, so the payload comes back untouched
  9342. EXPECT_EQ(body, res->body) << path;
  9343. }
  9344. }
  9345. // A content coding cpp-httplib recognizes but was not built with must be
  9346. // reported as such. Handing the still-compressed payload back to the caller
  9347. // would silently corrupt it.
  9348. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  9349. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  9350. Server svr;
  9351. // "image/jpeg" keeps the server from applying a content coding of its own,
  9352. // so the hand-crafted Content-Encoding below survives.
  9353. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  9354. res.set_content(gzipped, "image/jpeg");
  9355. res.set_header("Content-Encoding", "gzip");
  9356. });
  9357. // Content codings are case-insensitive (RFC 9110 8.4.1).
  9358. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  9359. res.set_content(gzipped, "image/jpeg");
  9360. res.set_header("Content-Encoding", "GZIP");
  9361. });
  9362. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9363. auto se = detail::scope_exit([&] {
  9364. svr.stop();
  9365. t.join();
  9366. ASSERT_FALSE(svr.is_running());
  9367. });
  9368. svr.wait_until_ready();
  9369. Client cli(HOST, PORT);
  9370. {
  9371. auto res = cli.Get("/gzipped");
  9372. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9373. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9374. EXPECT_EQ("Hello World!", res->body);
  9375. #else
  9376. ASSERT_FALSE(res);
  9377. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  9378. #endif
  9379. }
  9380. {
  9381. // open_stream() must behave the same way.
  9382. auto handle = cli.open_stream("GET", "/gzipped");
  9383. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9384. ASSERT_TRUE(handle.is_valid());
  9385. std::string received;
  9386. char buf[256];
  9387. ssize_t n;
  9388. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  9389. received.append(buf, static_cast<size_t>(n));
  9390. }
  9391. EXPECT_EQ("Hello World!", received);
  9392. #else
  9393. EXPECT_FALSE(handle.is_valid());
  9394. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  9395. #endif
  9396. }
  9397. {
  9398. // A differently-cased coding must not be mistaken for an unknown one, or
  9399. // the body would be handed back still compressed.
  9400. auto res = cli.Get("/gzipped-uppercase");
  9401. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9402. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9403. EXPECT_EQ("Hello World!", res->body);
  9404. #else
  9405. ASSERT_FALSE(res);
  9406. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  9407. #endif
  9408. }
  9409. }
  9410. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  9411. // the same message as the comma-joined one, so both have to be read the same
  9412. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  9413. // single gzip coding, and a body the sender says was encoded twice was handed
  9414. // back after one pass, still compressed but presented as decoded.
  9415. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  9416. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  9417. Server svr;
  9418. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  9419. res.set_content(body, "image/jpeg");
  9420. res.headers.emplace("Content-Encoding", "gzip");
  9421. res.headers.emplace("Content-Encoding", "gzip");
  9422. });
  9423. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  9424. res.set_content(body, "image/jpeg");
  9425. res.set_header("Content-Encoding", "gzip, gzip");
  9426. });
  9427. auto port = svr.bind_to_any_port(HOST);
  9428. thread t = thread([&]() { svr.listen_after_bind(); });
  9429. auto se = detail::scope_exit([&] {
  9430. svr.stop();
  9431. t.join();
  9432. ASSERT_FALSE(svr.is_running());
  9433. });
  9434. svr.wait_until_ready();
  9435. Client cli(HOST, port);
  9436. // Two codings is not something cpp-httplib decodes, so both representations
  9437. // take the pass-through path rather than one of them being gunzipped once.
  9438. for (const char *path : {"/split", "/joined"}) {
  9439. auto res = cli.Get(path);
  9440. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  9441. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  9442. EXPECT_EQ(body, res->body) << path;
  9443. }
  9444. }
  9445. // Regression test for DoS vulnerability: a malicious server sending a response
  9446. // without Content-Length header must not cause unbounded memory consumption on
  9447. // the client side. The client should stop reading after a reasonable limit,
  9448. // similar to the server-side set_payload_max_length protection.
  9449. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  9450. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  9451. #ifndef _WIN32
  9452. signal(SIGPIPE, SIG_IGN);
  9453. #endif
  9454. auto server_thread = std::thread([] {
  9455. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  9456. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9457. default_socket_options(srv);
  9458. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9459. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9460. sockaddr_in addr{};
  9461. addr.sin_family = AF_INET;
  9462. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9463. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9464. int opt = 1;
  9465. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9466. #ifdef _WIN32
  9467. reinterpret_cast<const char *>(&opt),
  9468. #else
  9469. &opt,
  9470. #endif
  9471. sizeof(opt));
  9472. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9473. ::listen(srv, 1);
  9474. sockaddr_in cli_addr{};
  9475. socklen_t cli_len = sizeof(cli_addr);
  9476. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9477. if (cli != INVALID_SOCKET) {
  9478. char buf[4096];
  9479. ::recv(cli, buf, sizeof(buf), 0);
  9480. // Malicious response: no Content-Length, no chunked encoding
  9481. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9482. "Connection: close\r\n"
  9483. "\r\n";
  9484. ::send(cli,
  9485. #ifdef _WIN32
  9486. static_cast<const char *>(response_header.c_str()),
  9487. static_cast<int>(response_header.size()),
  9488. #else
  9489. response_header.c_str(), response_header.size(),
  9490. #endif
  9491. 0);
  9492. // Send 10MB of data
  9493. std::string chunk(64 * 1024, 'A');
  9494. size_t total_sent = 0;
  9495. while (total_sent < MALICIOUS_DATA_SIZE) {
  9496. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  9497. auto sent = ::send(cli,
  9498. #ifdef _WIN32
  9499. static_cast<const char *>(chunk.c_str()),
  9500. static_cast<int>(to_send),
  9501. #else
  9502. chunk.c_str(), to_send,
  9503. #endif
  9504. 0);
  9505. if (sent <= 0) break;
  9506. total_sent += static_cast<size_t>(sent);
  9507. }
  9508. detail::close_socket(cli);
  9509. }
  9510. detail::close_socket(srv);
  9511. });
  9512. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9513. size_t total_read = 0;
  9514. {
  9515. Client cli("127.0.0.1", PORT + 2);
  9516. cli.set_read_timeout(5, 0);
  9517. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  9518. auto stream = cli.open_stream("GET", "/malicious");
  9519. ASSERT_TRUE(stream.is_valid());
  9520. char buffer[64 * 1024];
  9521. ssize_t n;
  9522. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  9523. total_read += static_cast<size_t>(n);
  9524. }
  9525. } // StreamHandle and Client destroyed here, closing the socket
  9526. server_thread.join();
  9527. // With set_payload_max_length, the client must stop reading before consuming
  9528. // all 10MB. The read loop should be cut off at or near the configured limit.
  9529. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  9530. << "Client read " << total_read << " bytes, exceeding the configured "
  9531. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  9532. }
  9533. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  9534. // the entire response body without truncation.
  9535. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  9536. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  9537. #ifndef _WIN32
  9538. signal(SIGPIPE, SIG_IGN);
  9539. #endif
  9540. auto server_thread = std::thread([] {
  9541. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9542. default_socket_options(srv);
  9543. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9544. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9545. sockaddr_in addr{};
  9546. addr.sin_family = AF_INET;
  9547. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9548. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9549. int opt = 1;
  9550. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9551. #ifdef _WIN32
  9552. reinterpret_cast<const char *>(&opt),
  9553. #else
  9554. &opt,
  9555. #endif
  9556. sizeof(opt));
  9557. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9558. ::listen(srv, 1);
  9559. sockaddr_in cli_addr{};
  9560. socklen_t cli_len = sizeof(cli_addr);
  9561. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9562. if (cli != INVALID_SOCKET) {
  9563. char buf[4096];
  9564. ::recv(cli, buf, sizeof(buf), 0);
  9565. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9566. "Connection: close\r\n"
  9567. "\r\n";
  9568. ::send(cli,
  9569. #ifdef _WIN32
  9570. static_cast<const char *>(response_header.c_str()),
  9571. static_cast<int>(response_header.size()),
  9572. #else
  9573. response_header.c_str(), response_header.size(),
  9574. #endif
  9575. 0);
  9576. std::string chunk(64 * 1024, 'A');
  9577. size_t total_sent = 0;
  9578. while (total_sent < DATA_SIZE) {
  9579. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  9580. auto sent = ::send(cli,
  9581. #ifdef _WIN32
  9582. static_cast<const char *>(chunk.c_str()),
  9583. static_cast<int>(to_send),
  9584. #else
  9585. chunk.c_str(), to_send,
  9586. #endif
  9587. 0);
  9588. if (sent <= 0) break;
  9589. total_sent += static_cast<size_t>(sent);
  9590. }
  9591. #ifdef _WIN32
  9592. ::shutdown(cli, SD_SEND);
  9593. #else
  9594. ::shutdown(cli, SHUT_WR);
  9595. #endif
  9596. // Drain until the client closes its end, ensuring all data is delivered
  9597. char drain[1024];
  9598. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  9599. detail::close_socket(cli);
  9600. }
  9601. detail::close_socket(srv);
  9602. });
  9603. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9604. size_t total_read = 0;
  9605. {
  9606. Client cli("127.0.0.1", PORT + 2);
  9607. cli.set_read_timeout(5, 0);
  9608. cli.set_payload_max_length(0); // 0 means no limit
  9609. auto stream = cli.open_stream("GET", "/data");
  9610. ASSERT_TRUE(stream.is_valid());
  9611. char buffer[64 * 1024];
  9612. ssize_t n;
  9613. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  9614. total_read += static_cast<size_t>(n);
  9615. }
  9616. }
  9617. server_thread.join();
  9618. EXPECT_EQ(total_read, DATA_SIZE)
  9619. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  9620. << " bytes without truncation, but only read " << total_read << " bytes.";
  9621. }
  9622. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  9623. // enormous Content-Length must not cause the client to pre-allocate a huge
  9624. // response body buffer. The reservation is capped at payload_max_length_, and
  9625. // the read itself fails when the body exceeds the limit.
  9626. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  9627. #ifndef _WIN32
  9628. signal(SIGPIPE, SIG_IGN);
  9629. #endif
  9630. auto server_thread = std::thread([] {
  9631. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9632. default_socket_options(srv);
  9633. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9634. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9635. sockaddr_in addr{};
  9636. addr.sin_family = AF_INET;
  9637. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9638. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9639. int opt = 1;
  9640. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9641. #ifdef _WIN32
  9642. reinterpret_cast<const char *>(&opt),
  9643. #else
  9644. &opt,
  9645. #endif
  9646. sizeof(opt));
  9647. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9648. ::listen(srv, 1);
  9649. sockaddr_in cli_addr{};
  9650. socklen_t cli_len = sizeof(cli_addr);
  9651. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9652. if (cli != INVALID_SOCKET) {
  9653. char buf[4096];
  9654. ::recv(cli, buf, sizeof(buf), 0);
  9655. // Malicious response: claim a 20GB body but send only a tiny payload.
  9656. std::string response = "HTTP/1.1 200 OK\r\n"
  9657. "Content-Length: 20000000000\r\n"
  9658. "\r\n"
  9659. "abc";
  9660. ::send(cli,
  9661. #ifdef _WIN32
  9662. static_cast<const char *>(response.c_str()),
  9663. static_cast<int>(response.size()),
  9664. #else
  9665. response.c_str(), response.size(),
  9666. #endif
  9667. 0);
  9668. detail::close_socket(cli);
  9669. }
  9670. detail::close_socket(srv);
  9671. });
  9672. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9673. {
  9674. Client cli("127.0.0.1", PORT + 2);
  9675. cli.set_read_timeout(5, 0);
  9676. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  9677. // result in a 20GB pre-allocation. The Get() call is expected to fail
  9678. // (server claims more bytes than payload_max_length permits), but it must
  9679. // not exhaust memory before getting there.
  9680. auto res = cli.Get("/malicious");
  9681. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  9682. }
  9683. server_thread.join();
  9684. }
  9685. // Verify that content_receiver bypasses the default payload_max_length,
  9686. // allowing streaming downloads larger than 100MB without requiring an explicit
  9687. // set_payload_max_length call.
  9688. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  9689. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  9690. #ifndef _WIN32
  9691. signal(SIGPIPE, SIG_IGN);
  9692. #endif
  9693. auto server_thread = std::thread([] {
  9694. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9695. default_socket_options(srv);
  9696. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9697. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9698. sockaddr_in addr{};
  9699. addr.sin_family = AF_INET;
  9700. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9701. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9702. int opt = 1;
  9703. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9704. #ifdef _WIN32
  9705. reinterpret_cast<const char *>(&opt),
  9706. #else
  9707. &opt,
  9708. #endif
  9709. sizeof(opt));
  9710. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9711. ::listen(srv, 1);
  9712. sockaddr_in cli_addr{};
  9713. socklen_t cli_len = sizeof(cli_addr);
  9714. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9715. if (cli != INVALID_SOCKET) {
  9716. char buf[4096];
  9717. ::recv(cli, buf, sizeof(buf), 0);
  9718. // Response with Content-Length larger than default 100MB limit
  9719. auto content_length = std::to_string(DATA_SIZE);
  9720. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9721. "Content-Length: " +
  9722. content_length +
  9723. "\r\n"
  9724. "Connection: close\r\n"
  9725. "\r\n";
  9726. ::send(cli,
  9727. #ifdef _WIN32
  9728. static_cast<const char *>(response_header.c_str()),
  9729. static_cast<int>(response_header.size()),
  9730. #else
  9731. response_header.c_str(), response_header.size(),
  9732. #endif
  9733. 0);
  9734. std::string chunk(64 * 1024, 'A');
  9735. size_t total_sent = 0;
  9736. while (total_sent < DATA_SIZE) {
  9737. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  9738. auto sent = ::send(cli,
  9739. #ifdef _WIN32
  9740. static_cast<const char *>(chunk.c_str()),
  9741. static_cast<int>(to_send),
  9742. #else
  9743. chunk.c_str(), to_send,
  9744. #endif
  9745. 0);
  9746. if (sent <= 0) break;
  9747. total_sent += static_cast<size_t>(sent);
  9748. }
  9749. detail::close_socket(cli);
  9750. }
  9751. detail::close_socket(srv);
  9752. });
  9753. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9754. size_t total_received = 0;
  9755. {
  9756. Client cli("127.0.0.1", PORT + 2);
  9757. cli.set_read_timeout(10, 0);
  9758. // Do NOT call set_payload_max_length — use the default 100MB limit
  9759. auto res =
  9760. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  9761. total_received += data_length;
  9762. return true;
  9763. });
  9764. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9765. EXPECT_EQ(StatusCode::OK_200, res->status);
  9766. }
  9767. server_thread.join();
  9768. EXPECT_EQ(total_received, DATA_SIZE)
  9769. << "With content_receiver, the client should read all " << DATA_SIZE
  9770. << " bytes despite the default 100MB payload_max_length, but only read "
  9771. << total_received << " bytes.";
  9772. }
  9773. // Verify that an explicit set_payload_max_length smaller than the response is
  9774. // enforced even when a content_receiver is used.
  9775. TEST(ClientVulnerabilityTest,
  9776. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  9777. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  9778. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  9779. #ifndef _WIN32
  9780. signal(SIGPIPE, SIG_IGN);
  9781. #endif
  9782. auto server_thread = std::thread([] {
  9783. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9784. default_socket_options(srv);
  9785. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9786. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9787. sockaddr_in addr{};
  9788. addr.sin_family = AF_INET;
  9789. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9790. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9791. int opt = 1;
  9792. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9793. #ifdef _WIN32
  9794. reinterpret_cast<const char *>(&opt),
  9795. #else
  9796. &opt,
  9797. #endif
  9798. sizeof(opt));
  9799. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9800. ::listen(srv, 1);
  9801. sockaddr_in cli_addr{};
  9802. socklen_t cli_len = sizeof(cli_addr);
  9803. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9804. if (cli != INVALID_SOCKET) {
  9805. char buf[4096];
  9806. ::recv(cli, buf, sizeof(buf), 0);
  9807. auto content_length = std::to_string(DATA_SIZE);
  9808. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9809. "Content-Length: " +
  9810. content_length +
  9811. "\r\n"
  9812. "Connection: close\r\n"
  9813. "\r\n";
  9814. ::send(cli,
  9815. #ifdef _WIN32
  9816. static_cast<const char *>(response_header.c_str()),
  9817. static_cast<int>(response_header.size()),
  9818. #else
  9819. response_header.c_str(), response_header.size(),
  9820. #endif
  9821. 0);
  9822. std::string chunk(64 * 1024, 'A');
  9823. size_t total_sent = 0;
  9824. while (total_sent < DATA_SIZE) {
  9825. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  9826. auto sent = ::send(cli,
  9827. #ifdef _WIN32
  9828. static_cast<const char *>(chunk.c_str()),
  9829. static_cast<int>(to_send),
  9830. #else
  9831. chunk.c_str(), to_send,
  9832. #endif
  9833. 0);
  9834. if (sent <= 0) break;
  9835. total_sent += static_cast<size_t>(sent);
  9836. }
  9837. detail::close_socket(cli);
  9838. }
  9839. detail::close_socket(srv);
  9840. });
  9841. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9842. size_t total_received = 0;
  9843. {
  9844. Client cli("127.0.0.1", PORT + 2);
  9845. cli.set_read_timeout(10, 0);
  9846. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  9847. auto res =
  9848. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  9849. total_received += data_length;
  9850. return true;
  9851. });
  9852. // Should fail because 200MB exceeds the explicit 150MB limit
  9853. EXPECT_FALSE(res);
  9854. }
  9855. server_thread.join();
  9856. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  9857. << "Client with content_receiver should respect the explicit "
  9858. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  9859. << total_received << " bytes.";
  9860. }
  9861. // Verify that an explicit set_payload_max_length larger than the response
  9862. // allows the content_receiver to read all data successfully.
  9863. TEST(ClientVulnerabilityTest,
  9864. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  9865. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  9866. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  9867. #ifndef _WIN32
  9868. signal(SIGPIPE, SIG_IGN);
  9869. #endif
  9870. auto server_thread = std::thread([] {
  9871. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9872. default_socket_options(srv);
  9873. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9874. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9875. sockaddr_in addr{};
  9876. addr.sin_family = AF_INET;
  9877. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9878. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9879. int opt = 1;
  9880. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9881. #ifdef _WIN32
  9882. reinterpret_cast<const char *>(&opt),
  9883. #else
  9884. &opt,
  9885. #endif
  9886. sizeof(opt));
  9887. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9888. ::listen(srv, 1);
  9889. sockaddr_in cli_addr{};
  9890. socklen_t cli_len = sizeof(cli_addr);
  9891. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9892. if (cli != INVALID_SOCKET) {
  9893. char buf[4096];
  9894. ::recv(cli, buf, sizeof(buf), 0);
  9895. auto content_length = std::to_string(DATA_SIZE);
  9896. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9897. "Content-Length: " +
  9898. content_length +
  9899. "\r\n"
  9900. "Connection: close\r\n"
  9901. "\r\n";
  9902. ::send(cli,
  9903. #ifdef _WIN32
  9904. static_cast<const char *>(response_header.c_str()),
  9905. static_cast<int>(response_header.size()),
  9906. #else
  9907. response_header.c_str(), response_header.size(),
  9908. #endif
  9909. 0);
  9910. std::string chunk(64 * 1024, 'A');
  9911. size_t total_sent = 0;
  9912. while (total_sent < DATA_SIZE) {
  9913. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  9914. auto sent = ::send(cli,
  9915. #ifdef _WIN32
  9916. static_cast<const char *>(chunk.c_str()),
  9917. static_cast<int>(to_send),
  9918. #else
  9919. chunk.c_str(), to_send,
  9920. #endif
  9921. 0);
  9922. if (sent <= 0) break;
  9923. total_sent += static_cast<size_t>(sent);
  9924. }
  9925. #ifdef _WIN32
  9926. ::shutdown(cli, SD_SEND);
  9927. #else
  9928. ::shutdown(cli, SHUT_WR);
  9929. #endif
  9930. char drain[1024];
  9931. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  9932. detail::close_socket(cli);
  9933. }
  9934. detail::close_socket(srv);
  9935. });
  9936. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9937. size_t total_received = 0;
  9938. {
  9939. Client cli("127.0.0.1", PORT + 2);
  9940. cli.set_read_timeout(10, 0);
  9941. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  9942. auto res =
  9943. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  9944. total_received += data_length;
  9945. return true;
  9946. });
  9947. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9948. EXPECT_EQ(StatusCode::OK_200, res->status);
  9949. }
  9950. server_thread.join();
  9951. EXPECT_EQ(total_received, DATA_SIZE)
  9952. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  9953. << " bytes (larger than " << DATA_SIZE
  9954. << " bytes response), content_receiver should read all data, but only "
  9955. "read "
  9956. << total_received << " bytes.";
  9957. }
  9958. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  9959. // Regression test for "zip bomb" attack on the client side: a malicious server
  9960. // sends a small gzip-compressed response that decompresses to a huge payload.
  9961. // The client must enforce payload_max_length on the decompressed size.
  9962. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  9963. constexpr size_t DECOMPRESSED_SIZE =
  9964. 10 * 1024 * 1024; // 10MB after decompression
  9965. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  9966. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  9967. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  9968. std::string compressed;
  9969. {
  9970. httplib::detail::gzip_compressor compressor;
  9971. bool ok =
  9972. compressor.compress(uncompressed.data(), uncompressed.size(),
  9973. /*last=*/true, [&](const char *buf, size_t len) {
  9974. compressed.append(buf, len);
  9975. return true;
  9976. });
  9977. ASSERT_TRUE(ok);
  9978. }
  9979. // Sanity: compressed data should be much smaller than the decompressed size
  9980. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  9981. #ifndef _WIN32
  9982. signal(SIGPIPE, SIG_IGN);
  9983. #endif
  9984. // Set up the listening socket in the main thread so the server is guaranteed
  9985. // to be ready before the client connects (eliminates race condition).
  9986. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9987. default_socket_options(srv);
  9988. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9989. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9990. sockaddr_in addr{};
  9991. addr.sin_family = AF_INET;
  9992. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  9993. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9994. int opt = 1;
  9995. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9996. #ifdef _WIN32
  9997. reinterpret_cast<const char *>(&opt),
  9998. #else
  9999. &opt,
  10000. #endif
  10001. sizeof(opt));
  10002. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  10003. ASSERT_EQ(0, ::listen(srv, 1));
  10004. auto server_thread = std::thread([&compressed, srv] {
  10005. sockaddr_in cli_addr{};
  10006. socklen_t cli_len = sizeof(cli_addr);
  10007. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10008. if (cli != INVALID_SOCKET) {
  10009. // Read the full HTTP request (until \r\n\r\n)
  10010. char buf[4096];
  10011. size_t total = 0;
  10012. while (total < sizeof(buf)) {
  10013. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  10014. if (n <= 0) break;
  10015. total += static_cast<size_t>(n);
  10016. // Check for end of headers
  10017. if (total >= 4) {
  10018. std::string req(buf, total);
  10019. if (req.find("\r\n\r\n") != std::string::npos) break;
  10020. }
  10021. }
  10022. // Malicious response: gzip-compressed body, no Content-Length
  10023. std::string response_header = "HTTP/1.1 200 OK\r\n"
  10024. "Content-Encoding: gzip\r\n"
  10025. "Connection: close\r\n"
  10026. "\r\n";
  10027. ::send(cli,
  10028. #ifdef _WIN32
  10029. static_cast<const char *>(response_header.c_str()),
  10030. static_cast<int>(response_header.size()),
  10031. #else
  10032. response_header.c_str(), response_header.size(),
  10033. #endif
  10034. 0);
  10035. // Send the compressed payload (small on the wire, huge when decompressed)
  10036. size_t total_sent = 0;
  10037. while (total_sent < compressed.size()) {
  10038. auto to_send = std::min(compressed.size() - total_sent,
  10039. static_cast<size_t>(64 * 1024));
  10040. auto sent =
  10041. ::send(cli,
  10042. #ifdef _WIN32
  10043. static_cast<const char *>(compressed.c_str() + total_sent),
  10044. static_cast<int>(to_send),
  10045. #else
  10046. compressed.c_str() + total_sent, to_send,
  10047. #endif
  10048. 0);
  10049. if (sent <= 0) break;
  10050. total_sent += static_cast<size_t>(sent);
  10051. }
  10052. detail::close_socket(cli);
  10053. }
  10054. });
  10055. auto se = detail::scope_exit([&] {
  10056. detail::close_socket(srv);
  10057. server_thread.join();
  10058. });
  10059. size_t total_decompressed = 0;
  10060. {
  10061. Client cli("127.0.0.1", PORT + 3);
  10062. cli.set_read_timeout(5, 0);
  10063. cli.set_decompress(true);
  10064. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  10065. auto stream = cli.open_stream("GET", "/zipbomb");
  10066. ASSERT_TRUE(stream.is_valid());
  10067. char buffer[64 * 1024];
  10068. ssize_t n;
  10069. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  10070. total_decompressed += static_cast<size_t>(n);
  10071. }
  10072. }
  10073. // The decompressed size must be capped by payload_max_length. Without
  10074. // protection, the client would decompress the full 10MB from a tiny
  10075. // compressed payload, enabling a zip bomb DoS attack.
  10076. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  10077. << "Client decompressed " << total_decompressed
  10078. << " bytes from a gzip response. The decompressed size should be "
  10079. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  10080. }
  10081. #endif
  10082. TEST(HostAndPortPropertiesTest, NoSSL) {
  10083. httplib::Client cli("www.google.com", 1234);
  10084. ASSERT_EQ("www.google.com", cli.host());
  10085. ASSERT_EQ(1234, cli.port());
  10086. }
  10087. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  10088. httplib::Client cli("www.google.com:1234");
  10089. ASSERT_EQ("www.google.com", cli.host());
  10090. ASSERT_EQ(1234, cli.port());
  10091. }
  10092. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  10093. // Port number that overflows int — should not crash, client becomes invalid
  10094. httplib::Client cli("http://www.google.com:99999999999999999999");
  10095. ASSERT_FALSE(cli.is_valid());
  10096. }
  10097. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  10098. // Port 99999 exceeds valid range (1-65535) — should not crash
  10099. httplib::Client cli("http://www.google.com:99999");
  10100. ASSERT_FALSE(cli.is_valid());
  10101. }
  10102. #ifdef CPPHTTPLIB_SSL_ENABLED
  10103. TEST(HostAndPortPropertiesTest, SSL) {
  10104. httplib::SSLClient cli("www.google.com");
  10105. ASSERT_EQ("www.google.com", cli.host());
  10106. ASSERT_EQ(443, cli.port());
  10107. }
  10108. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  10109. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  10110. std::string cert;
  10111. read_file(CA_CERT_FILE, cert);
  10112. httplib::SSLClient httplib_client("www.google.com");
  10113. // Load CA store first time
  10114. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  10115. // Load CA store second time (update)
  10116. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  10117. // Verify client is still valid and can make connections
  10118. httplib_client.enable_server_certificate_verification(true);
  10119. auto res = httplib_client.Get("/");
  10120. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10121. // Google may return 200 or 301 depending on various factors
  10122. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  10123. res->status == StatusCode::MovedPermanently_301);
  10124. }
  10125. TEST(SSLClientTest, ServerNameIndication_Online) {
  10126. auto host = "httpbingo.org";
  10127. auto path = std::string{"/get"};
  10128. SSLClient cli(host, 443);
  10129. auto res = cli.Get(path);
  10130. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10131. ASSERT_EQ(StatusCode::OK_200, res->status);
  10132. }
  10133. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  10134. // Use a site that will cause SSL verification failure due to self-signed cert
  10135. SSLClient cli("self-signed.badssl.com", 443);
  10136. cli.enable_server_certificate_verification(true);
  10137. auto res = cli.Get("/");
  10138. ASSERT_TRUE(!res);
  10139. EXPECT_EQ(Error::SSLServerVerification, res.error());
  10140. // Verify backend error is captured for SSLServerVerification
  10141. // This occurs when certificate verification fails
  10142. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  10143. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  10144. EXPECT_NE(0UL, res.ssl_backend_error());
  10145. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10146. // For OpenSSL, ssl_error is 0 for verification errors
  10147. EXPECT_EQ(0, res.ssl_error());
  10148. #if !defined(_WIN32) || \
  10149. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  10150. // On non-Windows or when Windows Schannel is disabled, the error comes
  10151. // from OpenSSL's verification
  10152. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  10153. res.ssl_backend_error());
  10154. #endif
  10155. #endif
  10156. }
  10157. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  10158. // Use a site where hostname doesn't match the certificate
  10159. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  10160. SSLClient cli("wrong.host.badssl.com", 443);
  10161. cli.enable_server_certificate_verification(true);
  10162. cli.enable_server_hostname_verification(true);
  10163. auto res = cli.Get("/");
  10164. ASSERT_TRUE(!res);
  10165. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  10166. // Verify backend error is captured for hostname verification failure
  10167. EXPECT_NE(0UL, res.ssl_backend_error());
  10168. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10169. // For OpenSSL, ssl_error is 0 for verification errors
  10170. EXPECT_EQ(0, res.ssl_error());
  10171. #if !defined(_WIN32) || \
  10172. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  10173. // On non-Windows or when Windows Schannel is disabled, the error comes
  10174. // from OpenSSL's hostname verification
  10175. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  10176. res.ssl_backend_error());
  10177. #endif
  10178. #endif
  10179. }
  10180. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  10181. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  10182. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  10183. SSLClient cli("www.google.com", 443);
  10184. cli.enable_server_certificate_verification(true);
  10185. auto res = cli.Get("/");
  10186. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  10187. }
  10188. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  10189. SSLClient cli("www.google.com", 443);
  10190. cli.enable_server_certificate_verification(true);
  10191. cli.enable_windows_certificate_verification(false);
  10192. auto res = cli.Get("/");
  10193. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  10194. }
  10195. #endif
  10196. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  10197. Client cli("https://google.com");
  10198. auto res = cli.Get("/");
  10199. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10200. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10201. }
  10202. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  10203. SSLClient cli("google.com");
  10204. cli.set_ca_cert_path(CA_CERT_FILE);
  10205. auto res = cli.Get("/");
  10206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10207. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10208. }
  10209. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  10210. SSLClient cli("google.com");
  10211. cli.enable_server_certificate_verification(true);
  10212. cli.set_ca_cert_path("hello");
  10213. auto res = cli.Get("/");
  10214. ASSERT_TRUE(!res);
  10215. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  10216. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  10217. // should be set
  10218. EXPECT_EQ(0, res.ssl_error());
  10219. // Verify backend error is captured for SSLLoadingCerts
  10220. // This error occurs when loading CA certificates fails
  10221. EXPECT_NE(0UL, res.ssl_backend_error());
  10222. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10223. // OpenSSL specific error codes:
  10224. // > openssl errstr 0x80000002
  10225. // error:80000002:system library::No such file or directory
  10226. // > openssl errstr 0xA000126
  10227. // error:0A000126:SSL routines::unexpected eof while reading
  10228. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  10229. res.ssl_backend_error() == 0xA000126);
  10230. #endif
  10231. }
  10232. TEST(SSLClientTest, ServerCertificateVerification4) {
  10233. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10234. ASSERT_TRUE(svr.is_valid());
  10235. svr.Get("/test", [&](const Request &, Response &res) {
  10236. res.set_content("test", "text/plain");
  10237. svr.stop();
  10238. ASSERT_TRUE(true);
  10239. });
  10240. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10241. auto se = detail::scope_exit([&] {
  10242. t.join();
  10243. ASSERT_FALSE(svr.is_running());
  10244. });
  10245. svr.wait_until_ready();
  10246. SSLClient cli("127.0.0.1", PORT);
  10247. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  10248. cli.enable_server_certificate_verification(true);
  10249. cli.set_connection_timeout(30);
  10250. auto res = cli.Get("/test");
  10251. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10252. ASSERT_EQ(StatusCode::OK_200, res->status);
  10253. }
  10254. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  10255. std::string cert;
  10256. read_file(CA_CERT_FILE, cert);
  10257. SSLClient cli("google.com");
  10258. cli.load_ca_cert_store(cert.data(), cert.size());
  10259. const auto res = cli.Get("/");
  10260. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10261. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10262. }
  10263. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  10264. // clang-format off
  10265. static constexpr char cert[] =
  10266. "GlobalSign Root CA\n"
  10267. "==================\n"
  10268. "-----BEGIN CERTIFICATE-----\n"
  10269. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  10270. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  10271. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  10272. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  10273. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  10274. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  10275. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  10276. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  10277. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  10278. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  10279. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  10280. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  10281. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  10282. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  10283. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  10284. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  10285. "-----END CERTIFICATE-----\n";
  10286. // clang-format on
  10287. SSLClient cli("google.com");
  10288. cli.load_ca_cert_store(cert, sizeof(cert));
  10289. const auto res = cli.Get("/");
  10290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10291. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10292. }
  10293. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  10294. SSLClient cli("www.youtube.com");
  10295. cli.set_ca_cert_path(CA_CERT_FILE);
  10296. cli.enable_server_certificate_verification(true);
  10297. cli.set_follow_location(true);
  10298. auto res = cli.Get("/");
  10299. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10300. ASSERT_EQ(StatusCode::OK_200, res->status);
  10301. }
  10302. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  10303. SSLClient cli("wWw.YouTube.Com");
  10304. cli.set_ca_cert_path(CA_CERT_FILE);
  10305. cli.enable_server_certificate_verification(true);
  10306. cli.enable_server_hostname_verification(true);
  10307. cli.set_follow_location(true);
  10308. auto res = cli.Get("/");
  10309. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10310. ASSERT_EQ(StatusCode::OK_200, res->status);
  10311. }
  10312. TEST(SSLClientTest, HostNameMatchCase_Online) {
  10313. SSLClient cli("gOoGlE.COm");
  10314. cli.enable_server_certificate_verification(true);
  10315. cli.enable_server_hostname_verification(true);
  10316. cli.set_follow_location(true);
  10317. auto res = cli.Get("/");
  10318. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10319. ASSERT_EQ(StatusCode::OK_200, res->status);
  10320. }
  10321. TEST(SSLClientTest, Issue2004_Online) {
  10322. Client client("https://google.com");
  10323. client.set_follow_location(true);
  10324. auto res = client.Get("/");
  10325. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10326. ASSERT_EQ(StatusCode::OK_200, res->status);
  10327. auto body = res->body;
  10328. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  10329. }
  10330. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  10331. // Create SSLClient with invalid cert/key to make is_valid() return false
  10332. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  10333. "nonexistent_key.pem");
  10334. // is_valid() should be false due to cert loading failure
  10335. ASSERT_FALSE(cli.is_valid());
  10336. auto res = cli.Get("/");
  10337. ASSERT_FALSE(res);
  10338. EXPECT_EQ(Error::SSLConnection, res.error());
  10339. }
  10340. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  10341. // Test for Issue #2251: SSL error not properly reported when client cert
  10342. // and key paths are swapped or mismatched
  10343. // This simulates the scenario where user accidentally swaps the cert and key
  10344. // files
  10345. // Using client cert file as private key and vice versa (completely wrong)
  10346. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  10347. // Should fail validation due to cert/key mismatch
  10348. ASSERT_FALSE(cli.is_valid());
  10349. // Attempt to make a request should fail with proper error
  10350. auto res = cli.Get("/");
  10351. ASSERT_FALSE(res);
  10352. EXPECT_EQ(Error::SSLConnection, res.error());
  10353. // SSL error should be recorded in the Result object (this is the key fix for
  10354. // Issue #2251)
  10355. auto backend_error = res.ssl_backend_error();
  10356. EXPECT_NE(0u, backend_error);
  10357. }
  10358. // Tests cert/key mismatch detection at the TLS context level
  10359. TEST(TlsApiTest, ClientCertKeyMismatch) {
  10360. // Test that using mismatched cert/key causes connection failure.
  10361. // We verify this at the SSLClient level rather than through internal
  10362. // TLS API functions.
  10363. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  10364. cli.enable_server_certificate_verification(false);
  10365. cli.set_connection_timeout(2);
  10366. // The mismatch should cause a connection or handshake error
  10367. auto res = cli.Get("/test");
  10368. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  10369. // Either way, the request should fail
  10370. EXPECT_FALSE(res);
  10371. }
  10372. #endif
  10373. #if 0
  10374. TEST(SSLClientTest, SetInterfaceWithINET6) {
  10375. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  10376. ASSERT_TRUE(cli != nullptr);
  10377. cli->set_address_family(AF_INET6);
  10378. cli->set_interface("en0");
  10379. auto res = cli->Get("/get");
  10380. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10381. ASSERT_EQ(StatusCode::OK_200, res->status);
  10382. }
  10383. #endif
  10384. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  10385. #ifdef CPPHTTPLIB_SSL_ENABLED
  10386. void ClientCertPresent(
  10387. const std::string &client_cert_file,
  10388. const std::string &client_private_key_file,
  10389. const std::string &client_encrypted_private_key_pass = std::string()) {
  10390. using namespace httplib::tls;
  10391. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  10392. CLIENT_CA_CERT_DIR);
  10393. ASSERT_TRUE(svr.is_valid());
  10394. svr.Get("/test", [&](const Request &req, Response &res) {
  10395. res.set_content("test", "text/plain");
  10396. auto cert = req.peer_cert();
  10397. ASSERT_TRUE(static_cast<bool>(cert));
  10398. std::string common_name = cert.subject_cn();
  10399. EXPECT_EQ("Common Name", common_name);
  10400. });
  10401. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10402. auto se = detail::scope_exit([&] {
  10403. svr.stop();
  10404. t.join();
  10405. ASSERT_FALSE(svr.is_running());
  10406. });
  10407. svr.wait_until_ready();
  10408. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  10409. client_encrypted_private_key_pass);
  10410. cli.enable_server_certificate_verification(false);
  10411. cli.set_connection_timeout(30);
  10412. auto res = cli.Get("/test");
  10413. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10414. ASSERT_EQ(StatusCode::OK_200, res->status);
  10415. }
  10416. TEST(SSLClientServerTest, ClientCertPresent) {
  10417. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10418. }
  10419. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  10420. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  10421. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  10422. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  10423. }
  10424. // PEM memory-based constructor tests (works with all TLS backends)
  10425. void PemMemoryClientCertPresent(
  10426. const std::string &client_cert_file,
  10427. const std::string &client_private_key_file,
  10428. const std::string &client_encrypted_private_key_pass = std::string()) {
  10429. // Read PEM files into memory
  10430. std::string server_cert_pem, server_key_pem;
  10431. std::string client_ca_pem;
  10432. std::string client_cert_pem, client_key_pem;
  10433. read_file(SERVER_CERT_FILE, server_cert_pem);
  10434. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  10435. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  10436. read_file(client_cert_file, client_cert_pem);
  10437. read_file(client_private_key_file, client_key_pem);
  10438. // Create server with PEM memory
  10439. SSLServer::PemMemory server_pem = {
  10440. server_cert_pem.c_str(),
  10441. server_cert_pem.size(),
  10442. server_key_pem.c_str(),
  10443. server_key_pem.size(),
  10444. client_ca_pem.c_str(),
  10445. client_ca_pem.size(),
  10446. nullptr // no password for server key
  10447. };
  10448. SSLServer svr(server_pem);
  10449. ASSERT_TRUE(svr.is_valid());
  10450. svr.Get("/test", [&](const Request &, Response &res) {
  10451. res.set_content("test", "text/plain");
  10452. });
  10453. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10454. auto se = detail::scope_exit([&] {
  10455. svr.stop();
  10456. t.join();
  10457. ASSERT_FALSE(svr.is_running());
  10458. });
  10459. svr.wait_until_ready();
  10460. // Create client with PEM memory
  10461. const char *password = client_encrypted_private_key_pass.empty()
  10462. ? nullptr
  10463. : client_encrypted_private_key_pass.c_str();
  10464. SSLClient::PemMemory client_pem = {
  10465. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  10466. client_key_pem.size(), password};
  10467. SSLClient cli(HOST, PORT, client_pem);
  10468. cli.enable_server_certificate_verification(false);
  10469. cli.set_connection_timeout(30);
  10470. auto res = cli.Get("/test");
  10471. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10472. ASSERT_EQ(StatusCode::OK_200, res->status);
  10473. }
  10474. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  10475. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10476. }
  10477. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  10478. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  10479. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  10480. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  10481. }
  10482. TEST(SSLClientServerTest, ClientCertMissing) {
  10483. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  10484. CLIENT_CA_CERT_DIR);
  10485. ASSERT_TRUE(svr.is_valid());
  10486. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  10487. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10488. auto se = detail::scope_exit([&] {
  10489. svr.stop();
  10490. t.join();
  10491. ASSERT_FALSE(svr.is_running());
  10492. });
  10493. svr.wait_until_ready();
  10494. SSLClient cli(HOST, PORT);
  10495. cli.set_connection_timeout(30);
  10496. auto res = cli.Get("/test");
  10497. ASSERT_TRUE(!res);
  10498. // When client cert is missing and server requires it, connection fails
  10499. // Error type depends on backend implementation
  10500. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  10501. res.error() == Error::SSLConnection);
  10502. // Verify backend error is captured
  10503. // Note: This test may have different error codes depending on the exact
  10504. // verification failure
  10505. EXPECT_NE(0UL, res.ssl_backend_error());
  10506. }
  10507. TEST(SSLClientServerTest, TrustDirOptional) {
  10508. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  10509. ASSERT_TRUE(svr.is_valid());
  10510. svr.Get("/test", [&](const Request &, Response &res) {
  10511. res.set_content("test", "text/plain");
  10512. });
  10513. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10514. auto se = detail::scope_exit([&] {
  10515. svr.stop();
  10516. t.join();
  10517. ASSERT_FALSE(svr.is_running());
  10518. });
  10519. svr.wait_until_ready();
  10520. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10521. cli.enable_server_certificate_verification(false);
  10522. cli.set_connection_timeout(30);
  10523. auto res = cli.Get("/test");
  10524. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10525. ASSERT_EQ(StatusCode::OK_200, res->status);
  10526. }
  10527. TEST(SSLClientServerTest, SSLConnectTimeout) {
  10528. class NoListenSSLServer : public SSLServer {
  10529. public:
  10530. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  10531. const char *client_ca_cert_file_path,
  10532. const char *client_ca_cert_dir_path = nullptr)
  10533. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  10534. client_ca_cert_dir_path),
  10535. stop_(false) {}
  10536. std::atomic_bool stop_;
  10537. private:
  10538. bool process_and_close_socket(socket_t /*sock*/) override {
  10539. // Don't create SSL context
  10540. while (!stop_.load()) {
  10541. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10542. }
  10543. return true;
  10544. }
  10545. };
  10546. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  10547. CLIENT_CA_CERT_FILE);
  10548. ASSERT_TRUE(svr.is_valid());
  10549. svr.Get("/test", [&](const Request &, Response &res) {
  10550. res.set_content("test", "text/plain");
  10551. });
  10552. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10553. auto se = detail::scope_exit([&] {
  10554. svr.stop_ = true;
  10555. svr.stop();
  10556. t.join();
  10557. ASSERT_FALSE(svr.is_running());
  10558. });
  10559. svr.wait_until_ready();
  10560. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10561. cli.enable_server_certificate_verification(false);
  10562. cli.set_connection_timeout(1);
  10563. auto res = cli.Get("/test");
  10564. ASSERT_TRUE(!res);
  10565. EXPECT_EQ(Error::SSLConnection, res.error());
  10566. // Timeout results in WantRead error code (maps to backend-specific value)
  10567. EXPECT_NE(0, res.ssl_error());
  10568. }
  10569. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  10570. // Test SSLServer with client certificate verification using the standard
  10571. // constructor (ContextSetupCallback is tested by backend-specific tests)
  10572. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  10573. CLIENT_CA_CERT_DIR);
  10574. ASSERT_TRUE(svr.is_valid());
  10575. svr.Get("/test", [&](const Request &req, Response &res) {
  10576. res.set_content("test", "text/plain");
  10577. auto cert = req.peer_cert();
  10578. ASSERT_TRUE(static_cast<bool>(cert));
  10579. auto common_name = cert.subject_cn();
  10580. EXPECT_EQ("Common Name", common_name);
  10581. });
  10582. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10583. auto se = detail::scope_exit([&] {
  10584. svr.stop();
  10585. t.join();
  10586. ASSERT_FALSE(svr.is_running());
  10587. });
  10588. svr.wait_until_ready();
  10589. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10590. cli.enable_server_certificate_verification(false);
  10591. cli.set_connection_timeout(30);
  10592. auto res = cli.Get("/test");
  10593. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10594. ASSERT_EQ(StatusCode::OK_200, res->status);
  10595. }
  10596. // Test verify_hostname for both OpenSSL and MbedTLS backends
  10597. // Verifies that wildcard matching and exact matching work consistently
  10598. TEST(SSLClientServerTest, TlsVerifyHostname) {
  10599. using namespace httplib::tls;
  10600. // We need a running server to test against
  10601. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10602. ASSERT_TRUE(svr.is_valid());
  10603. svr.Get("/test", [](const Request &, Response &res) {
  10604. res.set_content("ok", "text/plain");
  10605. });
  10606. thread t([&]() { svr.listen(HOST, PORT); });
  10607. auto se = detail::scope_exit([&] {
  10608. svr.stop();
  10609. t.join();
  10610. });
  10611. svr.wait_until_ready();
  10612. bool verify_callback_called = false;
  10613. bool verify_result_wrong = false;
  10614. SSLClient cli(HOST, PORT);
  10615. cli.enable_server_certificate_verification(true);
  10616. cli.set_ca_cert_path(CA_CERT_FILE);
  10617. cli.set_connection_timeout(5);
  10618. // Note: Test certificate has CN="Common Name", not "localhost"
  10619. bool verify_result_cn = false;
  10620. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10621. verify_callback_called = true;
  10622. if (!ctx.cert) return false;
  10623. // Test 1: "Common Name" should match (our test server cert CN)
  10624. verify_result_cn = ctx.check_hostname("Common Name");
  10625. // Test 2: wrong hostname should not match
  10626. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  10627. return true; // Accept for the purpose of this test
  10628. });
  10629. auto res = cli.Get("/test");
  10630. // The request may succeed or fail depending on cert configuration
  10631. // but the callback should have been called
  10632. ASSERT_TRUE(verify_callback_called)
  10633. << "Verify callback should have been called";
  10634. // CN="Common Name" should match our test certificate
  10635. //
  10636. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  10637. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  10638. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  10639. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  10640. // <openssl/base.h>, which is included transitively when
  10641. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  10642. #if defined(OPENSSL_IS_BORINGSSL)
  10643. EXPECT_FALSE(verify_result_cn)
  10644. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  10645. #else
  10646. EXPECT_TRUE(verify_result_cn)
  10647. << "verify_hostname should match 'Common Name' (certificate CN)";
  10648. #endif
  10649. // Wrong hostname should not match
  10650. EXPECT_FALSE(verify_result_wrong)
  10651. << "verify_hostname should not match 'wronghost.example.com'";
  10652. }
  10653. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  10654. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  10655. // X509_check_ip behavior and must hold for every backend.
  10656. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  10657. using namespace httplib::tls;
  10658. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  10659. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  10660. ASSERT_TRUE(svr.is_valid());
  10661. svr.Get("/test", [](const Request &, Response &res) {
  10662. res.set_content("ok", "text/plain");
  10663. });
  10664. thread t([&]() { svr.listen(HOST, PORT); });
  10665. auto se = detail::scope_exit([&] {
  10666. svr.stop();
  10667. t.join();
  10668. });
  10669. svr.wait_until_ready();
  10670. bool verify_callback_called = false;
  10671. bool ip_matched_via_cn = true;
  10672. SSLClient cli(HOST, PORT);
  10673. cli.enable_server_certificate_verification(true);
  10674. cli.set_ca_cert_path(CA_CERT_FILE);
  10675. cli.set_connection_timeout(5);
  10676. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10677. verify_callback_called = true;
  10678. if (!ctx.cert) return false;
  10679. // The IP appears only in the CN, so it must NOT be accepted.
  10680. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  10681. return true; // Accept for the purpose of this test
  10682. });
  10683. cli.Get("/test");
  10684. ASSERT_TRUE(verify_callback_called)
  10685. << "Verify callback should have been called";
  10686. EXPECT_FALSE(ip_matched_via_cn)
  10687. << "An IP host must not be authenticated via the certificate CN";
  10688. }
  10689. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  10690. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  10691. using namespace httplib::tls;
  10692. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  10693. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  10694. ASSERT_TRUE(svr.is_valid());
  10695. svr.Get("/test", [](const Request &, Response &res) {
  10696. res.set_content("ok", "text/plain");
  10697. });
  10698. thread t([&]() { svr.listen(HOST, PORT); });
  10699. auto se = detail::scope_exit([&] {
  10700. svr.stop();
  10701. t.join();
  10702. });
  10703. svr.wait_until_ready();
  10704. bool verify_callback_called = false;
  10705. bool san_matched = false;
  10706. bool wrong_ipv6_matched = true;
  10707. bool cn_ipv6_matched = true;
  10708. SSLClient cli(HOST, PORT);
  10709. cli.enable_server_certificate_verification(true);
  10710. cli.set_ca_cert_path(CA_CERT_FILE);
  10711. cli.set_connection_timeout(5);
  10712. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10713. verify_callback_called = true;
  10714. if (!ctx.cert) return false;
  10715. // Matches the IPv6 iPAddress SAN.
  10716. san_matched = ctx.check_hostname("2001:db8::1");
  10717. // A different IPv6 address must not match.
  10718. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  10719. // "::1" lives only in the CN, so it must not be accepted.
  10720. cn_ipv6_matched = ctx.check_hostname("::1");
  10721. return true; // Accept for the purpose of this test
  10722. });
  10723. cli.Get("/test");
  10724. ASSERT_TRUE(verify_callback_called)
  10725. << "Verify callback should have been called";
  10726. EXPECT_TRUE(san_matched)
  10727. << "verify_hostname should match an IPv6 iPAddress SAN";
  10728. EXPECT_FALSE(wrong_ipv6_matched)
  10729. << "verify_hostname should not match a non-matching IPv6 address";
  10730. EXPECT_FALSE(cn_ipv6_matched)
  10731. << "An IPv6 host must not be authenticated via the certificate CN";
  10732. }
  10733. #endif
  10734. // mbedTLS-specific callback constructor test
  10735. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  10736. #ifdef CPPHTTPLIB_SSL_ENABLED
  10737. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  10738. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  10739. ASSERT_TRUE(svr.is_valid());
  10740. // Set up a handler to verify client certificate is present
  10741. bool client_cert_verified = false;
  10742. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  10743. // Verify that client certificate was provided
  10744. client_cert_verified = true;
  10745. res.set_content("success", "text/plain");
  10746. });
  10747. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10748. auto se = detail::scope_exit([&] {
  10749. svr.stop();
  10750. t.join();
  10751. ASSERT_FALSE(svr.is_running());
  10752. });
  10753. svr.wait_until_ready();
  10754. // Client with certificate
  10755. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10756. cli.enable_server_certificate_verification(false);
  10757. cli.set_connection_timeout(30);
  10758. auto res = cli.Get("/test");
  10759. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10760. ASSERT_EQ(StatusCode::OK_200, res->status);
  10761. ASSERT_TRUE(client_cert_verified);
  10762. EXPECT_EQ("success", res->body);
  10763. }
  10764. #endif
  10765. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  10766. // backends
  10767. #ifdef CPPHTTPLIB_SSL_ENABLED
  10768. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  10769. using namespace httplib::tls;
  10770. // Test that when client CA cert file is provided,
  10771. // the server properly requests and validates client certificates
  10772. // Create a server with client authentication
  10773. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  10774. ASSERT_TRUE(svr.is_valid());
  10775. bool handler_called = false;
  10776. svr.Get("/test", [&](const Request &req, Response &res) {
  10777. handler_called = true;
  10778. // Verify that a client certificate was provided
  10779. auto cert = req.peer_cert();
  10780. ASSERT_TRUE(static_cast<bool>(cert));
  10781. // Get the issuer name
  10782. std::string issuer_str = cert.issuer_name();
  10783. ASSERT_FALSE(issuer_str.empty());
  10784. // The client certificate should be issued by our test CA
  10785. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  10786. res.set_content("authenticated", "text/plain");
  10787. });
  10788. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10789. auto se = detail::scope_exit([&] {
  10790. svr.stop();
  10791. t.join();
  10792. ASSERT_FALSE(svr.is_running());
  10793. });
  10794. svr.wait_until_ready();
  10795. // Connect with a client certificate issued by the CA
  10796. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10797. cli.enable_server_certificate_verification(false);
  10798. cli.set_connection_timeout(30);
  10799. auto res = cli.Get("/test");
  10800. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10801. ASSERT_EQ(StatusCode::OK_200, res->status);
  10802. ASSERT_TRUE(handler_called);
  10803. EXPECT_EQ("authenticated", res->body);
  10804. }
  10805. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  10806. using namespace httplib::tls;
  10807. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10808. ASSERT_TRUE(svr.is_valid());
  10809. svr.Get("/test", [](const Request &, Response &res) {
  10810. res.set_content("ok", "text/plain");
  10811. });
  10812. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10813. auto se = detail::scope_exit([&] {
  10814. svr.stop();
  10815. t.join();
  10816. });
  10817. svr.wait_until_ready();
  10818. SSLClient cli(HOST, PORT);
  10819. cli.enable_server_certificate_verification(false);
  10820. cli.set_connection_timeout(30);
  10821. bool cert_checked = false;
  10822. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10823. if (ctx.cert) {
  10824. auto sans = ctx.sans();
  10825. // Test certificate may or may not have SANs - just verify the API
  10826. // works If SANs exist, verify the types are valid
  10827. for (const auto &san : sans) {
  10828. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  10829. san.type == SanType::EMAIL || san.type == SanType::URI ||
  10830. san.type == SanType::OTHER);
  10831. EXPECT_FALSE(san.value.empty());
  10832. }
  10833. cert_checked = true;
  10834. }
  10835. return true;
  10836. });
  10837. auto res = cli.Get("/test");
  10838. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10839. EXPECT_TRUE(cert_checked);
  10840. }
  10841. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  10842. using namespace httplib::tls;
  10843. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10844. ASSERT_TRUE(svr.is_valid());
  10845. svr.Get("/test", [](const Request &, Response &res) {
  10846. res.set_content("ok", "text/plain");
  10847. });
  10848. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10849. auto se = detail::scope_exit([&] {
  10850. svr.stop();
  10851. t.join();
  10852. });
  10853. svr.wait_until_ready();
  10854. SSLClient cli(HOST, PORT);
  10855. cli.enable_server_certificate_verification(false);
  10856. cli.set_connection_timeout(30);
  10857. bool validity_checked = false;
  10858. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10859. if (ctx.cert) {
  10860. time_t not_before = 0, not_after = 0;
  10861. bool result = ctx.validity(not_before, not_after);
  10862. EXPECT_TRUE(result);
  10863. // Verify that not_before < now < not_after for a valid cert
  10864. time_t now = time(nullptr);
  10865. EXPECT_LT(not_before, now);
  10866. EXPECT_GT(not_after, now);
  10867. validity_checked = true;
  10868. }
  10869. return true;
  10870. });
  10871. auto res = cli.Get("/test");
  10872. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10873. EXPECT_TRUE(validity_checked);
  10874. }
  10875. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  10876. using namespace httplib::tls;
  10877. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10878. ASSERT_TRUE(svr.is_valid());
  10879. svr.Get("/test", [](const Request &, Response &res) {
  10880. res.set_content("ok", "text/plain");
  10881. });
  10882. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10883. auto se = detail::scope_exit([&] {
  10884. svr.stop();
  10885. t.join();
  10886. });
  10887. svr.wait_until_ready();
  10888. SSLClient cli(HOST, PORT);
  10889. cli.enable_server_certificate_verification(false);
  10890. cli.set_connection_timeout(30);
  10891. bool serial_checked = false;
  10892. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10893. if (ctx.cert) {
  10894. std::string serial = ctx.serial();
  10895. EXPECT_FALSE(serial.empty());
  10896. // Serial should be a hex string
  10897. for (char c : serial) {
  10898. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  10899. (c >= 'a' && c <= 'f'));
  10900. }
  10901. serial_checked = true;
  10902. }
  10903. return true;
  10904. });
  10905. auto res = cli.Get("/test");
  10906. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10907. EXPECT_TRUE(serial_checked);
  10908. }
  10909. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  10910. // Test 1: Valid CA file - no error should be recorded
  10911. {
  10912. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  10913. CLIENT_CA_CERT_FILE);
  10914. ASSERT_TRUE(svr.is_valid());
  10915. // With valid setup, last_ssl_error should be 0
  10916. EXPECT_EQ(0, svr.ssl_last_error());
  10917. }
  10918. // Test 2: Invalid CA file content
  10919. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  10920. {
  10921. // Create a temporary file with completely invalid content
  10922. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  10923. {
  10924. std::ofstream ofs(temp_invalid_ca);
  10925. ofs << "This is not a certificate file at all\n";
  10926. ofs << "Just plain text content\n";
  10927. }
  10928. // Create server with invalid CA file
  10929. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  10930. // Clean up temporary file
  10931. std::remove(temp_invalid_ca);
  10932. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  10933. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  10934. // Note: SSL_CTX_load_verify_locations typically fails first,
  10935. // but our error handling code path is still exercised
  10936. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  10937. }
  10938. }
  10939. TEST(VerifyCallbackTest, VerifyContextFields) {
  10940. using namespace httplib::tls;
  10941. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10942. ASSERT_TRUE(svr.is_valid());
  10943. svr.Get("/test", [](const Request &, Response &res) {
  10944. res.set_content("ok", "text/plain");
  10945. });
  10946. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10947. auto se = detail::scope_exit([&] {
  10948. svr.stop();
  10949. t.join();
  10950. });
  10951. svr.wait_until_ready();
  10952. SSLClient cli(HOST, PORT);
  10953. cli.enable_server_certificate_verification(false);
  10954. cli.set_connection_timeout(30);
  10955. int callback_count = 0;
  10956. bool saw_leaf_cert = false;
  10957. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10958. if (ctx.cert) {
  10959. callback_count++;
  10960. // We should see at least one certificate (the leaf)
  10961. std::string cn = ctx.subject_cn();
  10962. if (!cn.empty()) { saw_leaf_cert = true; }
  10963. // Verify context fields are populated
  10964. EXPECT_NE(ctx.session, nullptr);
  10965. EXPECT_GE(ctx.depth, 0);
  10966. }
  10967. return true;
  10968. });
  10969. auto res = cli.Get("/test");
  10970. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10971. EXPECT_GT(callback_count, 0);
  10972. EXPECT_TRUE(saw_leaf_cert);
  10973. }
  10974. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  10975. using httplib::tls::TlsError;
  10976. // Test that verify_error_to_string returns empty for success
  10977. std::string success_str = TlsError::verify_error_to_string(0);
  10978. EXPECT_TRUE(success_str.empty());
  10979. // Test that verify_error_to_string returns non-empty for error codes
  10980. // Using a common error code (certificate expired)
  10981. std::string error_str =
  10982. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  10983. EXPECT_FALSE(error_str.empty());
  10984. }
  10985. TEST(SessionVerifierTest, CertificateAccepted) {
  10986. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10987. ASSERT_TRUE(svr.is_valid());
  10988. svr.Get("/test", [](const Request &, Response &res) {
  10989. res.set_content("ok", "text/plain");
  10990. });
  10991. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10992. auto se = detail::scope_exit([&] {
  10993. svr.stop();
  10994. t.join();
  10995. });
  10996. svr.wait_until_ready();
  10997. SSLClient cli(HOST, PORT);
  10998. cli.enable_server_certificate_verification(false);
  10999. cli.set_connection_timeout(30);
  11000. bool callback_called = false;
  11001. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  11002. EXPECT_NE(session, nullptr);
  11003. callback_called = true;
  11004. return SSLVerifierResponse::CertificateAccepted;
  11005. });
  11006. auto res = cli.Get("/test");
  11007. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11008. EXPECT_EQ(200, res->status);
  11009. EXPECT_TRUE(callback_called);
  11010. }
  11011. TEST(SessionVerifierTest, CertificateRejected) {
  11012. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11013. ASSERT_TRUE(svr.is_valid());
  11014. svr.Get("/test", [](const Request &, Response &res) {
  11015. res.set_content("ok", "text/plain");
  11016. });
  11017. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11018. auto se = detail::scope_exit([&] {
  11019. svr.stop();
  11020. t.join();
  11021. });
  11022. svr.wait_until_ready();
  11023. SSLClient cli(HOST, PORT);
  11024. cli.enable_server_certificate_verification(false);
  11025. cli.set_connection_timeout(30);
  11026. bool callback_called = false;
  11027. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  11028. EXPECT_NE(session, nullptr);
  11029. callback_called = true;
  11030. return SSLVerifierResponse::CertificateRejected;
  11031. });
  11032. auto res = cli.Get("/test");
  11033. EXPECT_FALSE(res);
  11034. EXPECT_TRUE(callback_called);
  11035. }
  11036. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  11037. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11038. ASSERT_TRUE(svr.is_valid());
  11039. svr.Get("/test", [](const Request &, Response &res) {
  11040. res.set_content("ok", "text/plain");
  11041. });
  11042. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11043. auto se = detail::scope_exit([&] {
  11044. svr.stop();
  11045. t.join();
  11046. });
  11047. svr.wait_until_ready();
  11048. // NoDecisionMade with verification disabled should succeed (no default check)
  11049. SSLClient cli(HOST, PORT);
  11050. cli.enable_server_certificate_verification(false);
  11051. cli.set_connection_timeout(30);
  11052. bool callback_called = false;
  11053. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  11054. EXPECT_NE(session, nullptr);
  11055. callback_called = true;
  11056. return SSLVerifierResponse::NoDecisionMade;
  11057. });
  11058. auto res = cli.Get("/test");
  11059. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11060. EXPECT_EQ(200, res->status);
  11061. EXPECT_TRUE(callback_called);
  11062. }
  11063. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  11064. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11065. ASSERT_TRUE(svr.is_valid());
  11066. svr.Get("/test", [](const Request &, Response &res) {
  11067. res.set_content("ok", "text/plain");
  11068. });
  11069. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11070. auto se = detail::scope_exit([&] {
  11071. svr.stop();
  11072. t.join();
  11073. });
  11074. svr.wait_until_ready();
  11075. // NoDecisionMade with verification enabled should fail (self-signed cert).
  11076. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  11077. // so we only check that the request fails, not whether the callback was
  11078. // called.
  11079. SSLClient cli(HOST, PORT);
  11080. cli.enable_server_certificate_verification(true);
  11081. cli.set_connection_timeout(30);
  11082. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  11083. EXPECT_NE(session, nullptr);
  11084. return SSLVerifierResponse::NoDecisionMade;
  11085. });
  11086. auto res = cli.Get("/test");
  11087. EXPECT_FALSE(res);
  11088. }
  11089. TEST(SSLClientServerTest, ClientCAListFromPem) {
  11090. // Test SSL server using PemMemory constructor with client CA certificates
  11091. // Read PEM files
  11092. std::string server_cert_pem, server_key_pem, client_ca_pem;
  11093. read_file(SERVER_CERT_FILE, server_cert_pem);
  11094. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  11095. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  11096. // Create SSLServer with PemMemory constructor including client CA
  11097. SSLServer::PemMemory server_pem = {
  11098. server_cert_pem.c_str(),
  11099. server_cert_pem.size(),
  11100. server_key_pem.c_str(),
  11101. server_key_pem.size(),
  11102. client_ca_pem.c_str(),
  11103. client_ca_pem.size(),
  11104. nullptr // no password for server key
  11105. };
  11106. SSLServer svr(server_pem);
  11107. ASSERT_TRUE(svr.is_valid());
  11108. // No SSL error should be recorded for valid setup
  11109. EXPECT_EQ(0, svr.ssl_last_error());
  11110. // Set up server endpoints
  11111. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  11112. res.set_content("ok", "text/plain");
  11113. });
  11114. // Start server in a thread
  11115. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  11116. svr.wait_until_ready();
  11117. // Connect with client certificate (using constructor with paths)
  11118. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11119. cli.enable_server_certificate_verification(false);
  11120. auto res = cli.Get("/test-pem-ca");
  11121. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11122. EXPECT_EQ(200, res->status);
  11123. EXPECT_EQ("ok", res->body);
  11124. svr.stop();
  11125. server_thread.join();
  11126. }
  11127. #endif
  11128. #ifdef _WIN32
  11129. TEST(CleanupTest, WSACleanup) {
  11130. int ret = WSACleanup();
  11131. ASSERT_EQ(0, ret);
  11132. }
  11133. #endif
  11134. #ifndef CPPHTTPLIB_SSL_ENABLED
  11135. TEST(NoSSLSupport, SimpleInterface) {
  11136. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  11137. }
  11138. #endif
  11139. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  11140. TEST(InvalidScheme, SimpleInterface) {
  11141. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  11142. }
  11143. #endif
  11144. TEST(NoScheme, SimpleInterface) {
  11145. Client cli("yahoo.com:80");
  11146. ASSERT_TRUE(cli.is_valid());
  11147. }
  11148. TEST(SendAPI, SimpleInterface_Online) {
  11149. Client cli("http://yahoo.com");
  11150. Request req;
  11151. req.method = "GET";
  11152. req.path = "/";
  11153. auto res = cli.send(req);
  11154. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11155. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11156. }
  11157. TEST(SendAPI, WithParamsInRequest) {
  11158. Server svr;
  11159. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  11160. EXPECT_TRUE(req.has_param("test"));
  11161. EXPECT_EQ("test_value", req.get_param_value("test"));
  11162. });
  11163. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11164. auto se = detail::scope_exit([&] {
  11165. svr.stop();
  11166. t.join();
  11167. ASSERT_FALSE(svr.is_running());
  11168. });
  11169. svr.wait_until_ready();
  11170. Client cli(HOST, PORT);
  11171. {
  11172. Request req;
  11173. req.method = "GET";
  11174. req.path = "/";
  11175. req.params.emplace("test", "test_value");
  11176. auto res = cli.send(req);
  11177. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11178. }
  11179. {
  11180. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  11181. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11182. }
  11183. }
  11184. TEST(ClientImplMethods, GetSocketTest) {
  11185. httplib::Server svr;
  11186. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  11187. res.status = StatusCode::OK_200;
  11188. });
  11189. auto port = svr.bind_to_any_port("127.0.0.1");
  11190. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  11191. auto se = detail::scope_exit([&] {
  11192. svr.stop();
  11193. thread.join();
  11194. ASSERT_FALSE(svr.is_running());
  11195. });
  11196. svr.wait_until_ready();
  11197. {
  11198. httplib::Client cli("127.0.0.1", port);
  11199. cli.set_keep_alive(true);
  11200. // Use the behavior of cpp-httplib of opening the connection
  11201. // only when the first request happens. If that changes,
  11202. // this test would be obsolete.
  11203. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  11204. // This also implicitly tests the server. But other tests would fail much
  11205. // earlier than this one to be considered.
  11206. auto res = cli.Get("/");
  11207. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11208. EXPECT_EQ(StatusCode::OK_200, res->status);
  11209. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  11210. }
  11211. }
  11212. #ifdef CPPHTTPLIB_SSL_ENABLED
  11213. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  11214. Client cli("http://yahoo.com");
  11215. auto res = cli.Get("/");
  11216. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11217. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11218. cli.set_follow_location(true);
  11219. res = cli.Get("/");
  11220. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11221. EXPECT_EQ(StatusCode::OK_200, res->status);
  11222. EXPECT_EQ("https://www.yahoo.com/", res->location);
  11223. }
  11224. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  11225. Client cli("https://yahoo.com");
  11226. auto res = cli.Get("/");
  11227. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11228. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11229. cli.set_follow_location(true);
  11230. res = cli.Get("/");
  11231. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11232. EXPECT_EQ(StatusCode::OK_200, res->status);
  11233. EXPECT_EQ("https://www.yahoo.com/", res->location);
  11234. }
  11235. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  11236. Client cli("https://yahoo.com");
  11237. auto res = cli.Get("/");
  11238. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11239. ASSERT_FALSE(!res);
  11240. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11241. ASSERT_FALSE(res == nullptr);
  11242. ASSERT_TRUE(res != nullptr);
  11243. EXPECT_EQ(Error::Success, res.error());
  11244. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  11245. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  11246. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11247. cli.set_follow_location(true);
  11248. res = cli.Get("/");
  11249. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11250. EXPECT_EQ(Error::Success, res.error());
  11251. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  11252. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  11253. EXPECT_EQ(StatusCode::OK_200, res->status);
  11254. EXPECT_EQ("https://www.yahoo.com/", res->location);
  11255. }
  11256. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  11257. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  11258. Client cli("https://cdnjs.cloudflare.com");
  11259. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  11260. Headers{{"Accept-Encoding", "br"}});
  11261. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11262. EXPECT_EQ(StatusCode::OK_200, res->status);
  11263. EXPECT_EQ(287630U, res->body.size());
  11264. EXPECT_EQ("application/javascript; charset=utf-8",
  11265. res->get_header_value("Content-Type"));
  11266. }
  11267. #endif
  11268. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  11269. #undef REDIR_HOST // Silence compiler warning
  11270. #define REDIR_HOST "https://httpbingo.org"
  11271. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  11272. Client cli(REDIR_HOST);
  11273. cli.set_follow_location(true);
  11274. auto res =
  11275. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  11276. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11277. EXPECT_EQ(StatusCode::OK_200, res->status);
  11278. }
  11279. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  11280. Client cli(REDIR_HOST);
  11281. cli.set_follow_location(true);
  11282. Params params;
  11283. params.emplace("url", "http://example.com");
  11284. params.emplace("status_code", "302");
  11285. auto res = cli.Get(REDIR_PATH, params, Headers{});
  11286. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11287. EXPECT_EQ(StatusCode::OK_200, res->status);
  11288. }
  11289. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  11290. Client cli(REDIR_HOST);
  11291. cli.set_follow_location(true);
  11292. Params params;
  11293. params.emplace("url", "http://example.com");
  11294. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  11295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11296. EXPECT_EQ(StatusCode::OK_200, res->status);
  11297. }
  11298. TEST(HttpToHttpsRedirectTest, CertFile) {
  11299. auto ssl_port = PORT + 1;
  11300. Server svr;
  11301. ASSERT_TRUE(svr.is_valid());
  11302. svr.Get("/index", [&](const Request &, Response &res) {
  11303. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  11304. "/index");
  11305. svr.stop();
  11306. });
  11307. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11308. ASSERT_TRUE(ssl_svr.is_valid());
  11309. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  11310. res.set_content("test", "text/plain");
  11311. ssl_svr.stop();
  11312. });
  11313. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11314. thread t2 =
  11315. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  11316. auto se = detail::scope_exit([&] {
  11317. t2.join();
  11318. t.join();
  11319. ASSERT_FALSE(svr.is_running());
  11320. });
  11321. svr.wait_until_ready();
  11322. ssl_svr.wait_until_ready();
  11323. Client cli("127.0.0.1", PORT);
  11324. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  11325. cli.enable_server_certificate_verification(true);
  11326. cli.set_follow_location(true);
  11327. cli.set_connection_timeout(30);
  11328. auto res = cli.Get("/index");
  11329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11330. ASSERT_EQ(StatusCode::OK_200, res->status);
  11331. }
  11332. TEST(SSLClientRedirectTest, CertFile) {
  11333. auto ssl_port = PORT + 1;
  11334. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11335. ASSERT_TRUE(ssl_svr1.is_valid());
  11336. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  11337. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  11338. "/index");
  11339. ssl_svr1.stop();
  11340. });
  11341. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11342. ASSERT_TRUE(ssl_svr2.is_valid());
  11343. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  11344. res.set_content("test", "text/plain");
  11345. ssl_svr2.stop();
  11346. });
  11347. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  11348. thread t2 =
  11349. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  11350. auto se = detail::scope_exit([&] {
  11351. t2.join();
  11352. t.join();
  11353. ASSERT_FALSE(ssl_svr1.is_running());
  11354. });
  11355. ssl_svr1.wait_until_ready();
  11356. ssl_svr2.wait_until_ready();
  11357. SSLClient cli("127.0.0.1", PORT);
  11358. std::string cert;
  11359. read_file(SERVER_CERT2_FILE, cert);
  11360. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11361. cli.enable_server_certificate_verification(true);
  11362. cli.set_follow_location(true);
  11363. cli.set_connection_timeout(30);
  11364. auto res = cli.Get("/index");
  11365. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11366. ASSERT_EQ(StatusCode::OK_200, res->status);
  11367. }
  11368. #endif
  11369. #ifdef CPPHTTPLIB_SSL_ENABLED
  11370. // Test that set_ca_cert_store() skips system certs (consistent with
  11371. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  11372. // should be trusted - system certs should NOT be loaded.
  11373. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  11374. // Load a specific cert that is NOT a system CA cert
  11375. std::string cert;
  11376. read_file(SERVER_CERT2_FILE, cert);
  11377. SSLClient cli("google.com");
  11378. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11379. cli.enable_server_certificate_verification(true);
  11380. // This should FAIL because:
  11381. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  11382. // 2. System certs should NOT be loaded when custom store is set
  11383. // If system certs WERE loaded, this would succeed
  11384. auto res = cli.Get("/");
  11385. ASSERT_FALSE(res);
  11386. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11387. }
  11388. // Same as above, but through the native store handle path. Regression test:
  11389. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  11390. // merged system certs into the user-provided store.
  11391. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  11392. std::string cert;
  11393. read_file(SERVER_CERT2_FILE, cert);
  11394. SSLClient cli("google.com");
  11395. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  11396. cli.enable_server_certificate_verification(true);
  11397. auto res = cli.Get("/");
  11398. ASSERT_FALSE(res);
  11399. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11400. }
  11401. // A custom store set via the native handle must still verify a server whose
  11402. // cert it does contain.
  11403. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  11404. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11405. ASSERT_TRUE(svr.is_valid());
  11406. svr.Get("/test", [&](const Request &, Response &res) {
  11407. res.set_content("test", "text/plain");
  11408. });
  11409. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11410. auto se = detail::scope_exit([&] {
  11411. svr.stop();
  11412. t.join();
  11413. ASSERT_FALSE(svr.is_running());
  11414. });
  11415. svr.wait_until_ready();
  11416. SSLClient cli("127.0.0.1", PORT);
  11417. std::string cert;
  11418. read_file(SERVER_CERT2_FILE, cert);
  11419. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  11420. cli.enable_server_certificate_verification(true);
  11421. cli.set_connection_timeout(30);
  11422. auto res = cli.Get("/test");
  11423. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11424. ASSERT_EQ(StatusCode::OK_200, res->status);
  11425. }
  11426. // CA certs loaded through the universal Client must be transferred to the
  11427. // client created internally for following an HTTPS redirect. Regression test:
  11428. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  11429. // the CA data for redirect transfer.
  11430. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  11431. auto ssl_port = PORT + 1;
  11432. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11433. ASSERT_TRUE(ssl_svr1.is_valid());
  11434. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  11435. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  11436. "/index");
  11437. });
  11438. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11439. ASSERT_TRUE(ssl_svr2.is_valid());
  11440. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  11441. res.set_content("test", "text/plain");
  11442. });
  11443. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  11444. thread t2 =
  11445. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  11446. auto se = detail::scope_exit([&] {
  11447. ssl_svr2.stop();
  11448. ssl_svr1.stop();
  11449. t2.join();
  11450. t.join();
  11451. ASSERT_FALSE(ssl_svr1.is_running());
  11452. });
  11453. ssl_svr1.wait_until_ready();
  11454. ssl_svr2.wait_until_ready();
  11455. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  11456. std::string cert;
  11457. read_file(SERVER_CERT2_FILE, cert);
  11458. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11459. cli.enable_server_certificate_verification(true);
  11460. cli.set_follow_location(true);
  11461. cli.set_connection_timeout(30);
  11462. auto res = cli.Get("/index");
  11463. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11464. ASSERT_EQ(StatusCode::OK_200, res->status);
  11465. }
  11466. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  11467. // so a host signed by a system CA verifies even though a custom CA is set
  11468. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  11469. std::string cert;
  11470. read_file(SERVER_CERT2_FILE, cert);
  11471. SSLClient cli("google.com");
  11472. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11473. cli.enable_system_ca(true);
  11474. cli.enable_server_certificate_verification(true);
  11475. auto res = cli.Get("/");
  11476. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11477. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11478. }
  11479. // The custom CA remains effective when combined with the system CA
  11480. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  11481. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11482. ASSERT_TRUE(svr.is_valid());
  11483. svr.Get("/test", [&](const Request &, Response &res) {
  11484. res.set_content("test", "text/plain");
  11485. });
  11486. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11487. auto se = detail::scope_exit([&] {
  11488. svr.stop();
  11489. t.join();
  11490. ASSERT_FALSE(svr.is_running());
  11491. });
  11492. svr.wait_until_ready();
  11493. SSLClient cli("127.0.0.1", PORT);
  11494. std::string cert;
  11495. read_file(SERVER_CERT2_FILE, cert);
  11496. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11497. cli.enable_system_ca(true);
  11498. cli.enable_server_certificate_verification(true);
  11499. cli.set_connection_timeout(30);
  11500. auto res = cli.Get("/test");
  11501. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11502. ASSERT_EQ(StatusCode::OK_200, res->status);
  11503. }
  11504. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  11505. // skip chain verification entirely (only the certificate identity was
  11506. // checked), so a server presenting an untrusted certificate with a matching
  11507. // IP SAN was accepted. The chain must be validated for IP hosts too.
  11508. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  11509. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11510. ASSERT_TRUE(svr.is_valid());
  11511. svr.Get("/test", [&](const Request &, Response &res) {
  11512. res.set_content("test", "text/plain");
  11513. });
  11514. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11515. auto se = detail::scope_exit([&] {
  11516. svr.stop();
  11517. t.join();
  11518. ASSERT_FALSE(svr.is_running());
  11519. });
  11520. svr.wait_until_ready();
  11521. SSLClient cli("127.0.0.1", PORT);
  11522. std::string cert;
  11523. // A trusted CA that did not sign the server certificate. The server cert
  11524. // (cert2) carries the matching IP SAN, so only chain validation can reject
  11525. // this connection.
  11526. read_file(CLIENT_CA_CERT_FILE, cert);
  11527. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11528. cli.enable_server_certificate_verification(true);
  11529. cli.set_connection_timeout(30);
  11530. auto res = cli.Get("/test");
  11531. ASSERT_FALSE(res);
  11532. }
  11533. // enable_system_ca(false) prevents system CA loading entirely
  11534. TEST(SSLClientTest, DisableSystemCa_Online) {
  11535. SSLClient cli("google.com");
  11536. cli.enable_system_ca(false);
  11537. cli.enable_server_certificate_verification(true);
  11538. auto res = cli.Get("/");
  11539. ASSERT_FALSE(res);
  11540. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  11541. // itself when the CA chain is empty
  11542. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  11543. res.error() == Error::SSLConnection);
  11544. }
  11545. // The universal Client forwards enable_system_ca()
  11546. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  11547. std::string cert;
  11548. read_file(SERVER_CERT2_FILE, cert);
  11549. Client cli("https://google.com");
  11550. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11551. cli.enable_system_ca(true);
  11552. cli.enable_server_certificate_verification(true);
  11553. auto res = cli.Get("/");
  11554. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11555. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11556. }
  11557. // The system CA policy must carry over to the client created internally for
  11558. // following a cross-host HTTPS redirect
  11559. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  11560. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11561. ASSERT_TRUE(svr.is_valid());
  11562. svr.Get("/index", [&](const Request &, Response &res) {
  11563. res.set_redirect("https://www.google.com/");
  11564. });
  11565. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11566. auto se = detail::scope_exit([&] {
  11567. svr.stop();
  11568. t.join();
  11569. ASSERT_FALSE(svr.is_running());
  11570. });
  11571. svr.wait_until_ready();
  11572. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  11573. std::string cert;
  11574. read_file(SERVER_CERT2_FILE, cert);
  11575. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11576. cli.enable_system_ca(true);
  11577. cli.enable_server_certificate_verification(true);
  11578. cli.set_follow_location(true);
  11579. cli.set_connection_timeout(30);
  11580. // Receiving any response proves the redirect client completed the TLS
  11581. // handshake with a system-CA-signed host
  11582. auto res = cli.Get("/index");
  11583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11584. }
  11585. TEST(MultipartFormDataTest, LargeData) {
  11586. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11587. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  11588. const ContentReader &content_reader) {
  11589. if (req.is_multipart_form_data()) {
  11590. std::vector<FormData> items;
  11591. content_reader(
  11592. [&](const FormData &file) {
  11593. items.push_back(file);
  11594. return true;
  11595. },
  11596. [&](const char *data, size_t data_length) {
  11597. items.back().content.append(data, data_length);
  11598. return true;
  11599. });
  11600. EXPECT_TRUE(std::string(items[0].name) == "document");
  11601. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  11602. EXPECT_TRUE(items[0].filename == "2MB_data");
  11603. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  11604. EXPECT_TRUE(items[1].name == "hello");
  11605. EXPECT_TRUE(items[1].content == "world");
  11606. EXPECT_TRUE(items[1].filename == "");
  11607. EXPECT_TRUE(items[1].content_type == "");
  11608. } else {
  11609. std::string body;
  11610. content_reader([&](const char *data, size_t data_length) {
  11611. body.append(data, data_length);
  11612. return true;
  11613. });
  11614. }
  11615. });
  11616. auto port = svr.bind_to_any_port(HOST);
  11617. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11618. auto se = detail::scope_exit([&] {
  11619. svr.stop();
  11620. t.join();
  11621. ASSERT_FALSE(svr.is_running());
  11622. });
  11623. svr.wait_until_ready();
  11624. {
  11625. std::string data(1024 * 1024 * 2, '.');
  11626. std::stringstream buffer;
  11627. buffer << data;
  11628. SSLClient cli(HOST, port);
  11629. cli.enable_server_certificate_verification(false);
  11630. UploadFormDataItems items{
  11631. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11632. {"hello", "world", "", ""},
  11633. };
  11634. auto res = cli.Post("/post", items);
  11635. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11636. ASSERT_EQ(StatusCode::OK_200, res->status);
  11637. }
  11638. }
  11639. TEST(MultipartFormDataTest, DataProviderItems) {
  11640. std::random_device seed_gen;
  11641. std::mt19937 random(seed_gen());
  11642. std::string rand1;
  11643. rand1.resize(1000);
  11644. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  11645. std::string rand2;
  11646. rand2.resize(3000);
  11647. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  11648. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11649. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  11650. const ContentReader &content_reader) {
  11651. ASSERT_FALSE(req.is_multipart_form_data());
  11652. std::string body;
  11653. content_reader([&](const char *data, size_t data_length) {
  11654. body.append(data, data_length);
  11655. return true;
  11656. });
  11657. EXPECT_EQ(body, "");
  11658. });
  11659. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  11660. const ContentReader &content_reader) {
  11661. ASSERT_TRUE(req.is_multipart_form_data());
  11662. std::vector<FormData> items;
  11663. content_reader(
  11664. [&](const FormData &file) {
  11665. items.push_back(file);
  11666. return true;
  11667. },
  11668. [&](const char *data, size_t data_length) {
  11669. items.back().content.append(data, data_length);
  11670. return true;
  11671. });
  11672. ASSERT_TRUE(items.size() == 2);
  11673. EXPECT_EQ(std::string(items[0].name), "name1");
  11674. EXPECT_EQ(items[0].content, "Testing123");
  11675. EXPECT_EQ(items[0].filename, "filename1");
  11676. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  11677. EXPECT_EQ(items[1].name, "name2");
  11678. EXPECT_EQ(items[1].content, "Testing456");
  11679. EXPECT_EQ(items[1].filename, "");
  11680. EXPECT_EQ(items[1].content_type, "");
  11681. });
  11682. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  11683. const ContentReader &content_reader) {
  11684. ASSERT_TRUE(req.is_multipart_form_data());
  11685. std::vector<FormData> items;
  11686. content_reader(
  11687. [&](const FormData &file) {
  11688. items.push_back(file);
  11689. return true;
  11690. },
  11691. [&](const char *data, size_t data_length) {
  11692. items.back().content.append(data, data_length);
  11693. return true;
  11694. });
  11695. ASSERT_TRUE(items.size() == 2);
  11696. EXPECT_EQ(items[0].name, "name3");
  11697. EXPECT_EQ(items[0].content, rand1);
  11698. EXPECT_EQ(items[0].filename, "filename3");
  11699. EXPECT_EQ(items[0].content_type, "");
  11700. EXPECT_EQ(items[1].name, "name4");
  11701. EXPECT_EQ(items[1].content, rand2);
  11702. EXPECT_EQ(items[1].filename, "filename4");
  11703. EXPECT_EQ(items[1].content_type, "");
  11704. });
  11705. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  11706. const ContentReader &content_reader) {
  11707. ASSERT_TRUE(req.is_multipart_form_data());
  11708. std::vector<FormData> items;
  11709. content_reader(
  11710. [&](const FormData &file) {
  11711. items.push_back(file);
  11712. return true;
  11713. },
  11714. [&](const char *data, size_t data_length) {
  11715. items.back().content.append(data, data_length);
  11716. return true;
  11717. });
  11718. ASSERT_TRUE(items.size() == 4);
  11719. EXPECT_EQ(std::string(items[0].name), "name1");
  11720. EXPECT_EQ(items[0].content, "Testing123");
  11721. EXPECT_EQ(items[0].filename, "filename1");
  11722. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  11723. EXPECT_EQ(items[1].name, "name2");
  11724. EXPECT_EQ(items[1].content, "Testing456");
  11725. EXPECT_EQ(items[1].filename, "");
  11726. EXPECT_EQ(items[1].content_type, "");
  11727. EXPECT_EQ(items[2].name, "name3");
  11728. EXPECT_EQ(items[2].content, rand1);
  11729. EXPECT_EQ(items[2].filename, "filename3");
  11730. EXPECT_EQ(items[2].content_type, "");
  11731. EXPECT_EQ(items[3].name, "name4");
  11732. EXPECT_EQ(items[3].content, rand2);
  11733. EXPECT_EQ(items[3].filename, "filename4");
  11734. EXPECT_EQ(items[3].content_type, "");
  11735. });
  11736. auto port = svr.bind_to_any_port("localhost");
  11737. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11738. auto se = detail::scope_exit([&] {
  11739. svr.stop();
  11740. t.join();
  11741. ASSERT_FALSE(svr.is_running());
  11742. });
  11743. svr.wait_until_ready();
  11744. {
  11745. SSLClient cli("localhost", port);
  11746. cli.enable_server_certificate_verification(false);
  11747. UploadFormDataItems items{
  11748. {"name1", "Testing123", "filename1", "application/octet-stream"},
  11749. {"name2", "Testing456", "", ""}, // not a file
  11750. };
  11751. {
  11752. auto res = cli.Post("/post-none", {}, {}, {});
  11753. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11754. ASSERT_EQ(StatusCode::OK_200, res->status);
  11755. }
  11756. FormDataProviderItems providers;
  11757. {
  11758. auto res =
  11759. cli.Post("/post-items", {}, items, providers); // empty providers
  11760. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11761. ASSERT_EQ(StatusCode::OK_200, res->status);
  11762. }
  11763. providers.push_back({"name3",
  11764. [&](size_t offset, httplib::DataSink &sink) -> bool {
  11765. // test the offset is given correctly at each step
  11766. if (!offset)
  11767. sink.os.write(rand1.data(), 30);
  11768. else if (offset == 30)
  11769. sink.os.write(rand1.data() + 30, 300);
  11770. else if (offset == 330)
  11771. sink.os.write(rand1.data() + 330, 670);
  11772. else if (offset == rand1.size())
  11773. sink.done();
  11774. return true;
  11775. },
  11776. "filename3",
  11777. {}});
  11778. providers.push_back({"name4",
  11779. [&](size_t offset, httplib::DataSink &sink) -> bool {
  11780. // test the offset is given correctly at each step
  11781. if (!offset)
  11782. sink.os.write(rand2.data(), 2000);
  11783. else if (offset == 2000)
  11784. sink.os.write(rand2.data() + 2000, 1);
  11785. else if (offset == 2001)
  11786. sink.os.write(rand2.data() + 2001, 999);
  11787. else if (offset == rand2.size())
  11788. sink.done();
  11789. return true;
  11790. },
  11791. "filename4",
  11792. {}});
  11793. {
  11794. auto res = cli.Post("/post-providers", {}, {}, providers);
  11795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11796. ASSERT_EQ(StatusCode::OK_200, res->status);
  11797. }
  11798. {
  11799. auto res = cli.Post("/post-both", {}, items, providers);
  11800. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11801. ASSERT_EQ(StatusCode::OK_200, res->status);
  11802. }
  11803. }
  11804. }
  11805. TEST(MultipartFormDataTest, BadHeader) {
  11806. Server svr;
  11807. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  11808. res.set_content("ok", "text/plain");
  11809. });
  11810. thread t = thread([&] { svr.listen(HOST, PORT); });
  11811. auto se = detail::scope_exit([&] {
  11812. svr.stop();
  11813. t.join();
  11814. ASSERT_FALSE(svr.is_running());
  11815. });
  11816. svr.wait_until_ready();
  11817. const std::string body =
  11818. "This is the preamble. It is to be ignored, though it\r\n"
  11819. "is a handy place for composition agents to include an\r\n"
  11820. "explanatory note to non-MIME conformant readers.\r\n"
  11821. "\r\n"
  11822. "\r\n"
  11823. "--simple boundary\r\n"
  11824. "Content-Disposition: form-data; name=\"field1\"\r\n"
  11825. ": BAD...\r\n"
  11826. "\r\n"
  11827. "value1\r\n"
  11828. "--simple boundary\r\n"
  11829. "Content-Disposition: form-data; name=\"field2\"; "
  11830. "filename=\"example.txt\"\r\n"
  11831. "\r\n"
  11832. "value2\r\n"
  11833. "--simple boundary--\r\n"
  11834. "This is the epilogue. It is also to be ignored.\r\n";
  11835. std::string content_type =
  11836. R"(multipart/form-data; boundary="simple boundary")";
  11837. Client cli(HOST, PORT);
  11838. auto res = cli.Post("/post", body, content_type.c_str());
  11839. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11840. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  11841. }
  11842. TEST(MultipartFormDataTest, WithPreamble) {
  11843. Server svr;
  11844. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  11845. res.set_content("ok", "text/plain");
  11846. });
  11847. thread t = thread([&] { svr.listen(HOST, PORT); });
  11848. auto se = detail::scope_exit([&] {
  11849. svr.stop();
  11850. t.join();
  11851. ASSERT_FALSE(svr.is_running());
  11852. });
  11853. svr.wait_until_ready();
  11854. const std::string body =
  11855. "This is the preamble. It is to be ignored, though it\r\n"
  11856. "is a handy place for composition agents to include an\r\n"
  11857. "explanatory note to non-MIME conformant readers.\r\n"
  11858. "\r\n"
  11859. "\r\n"
  11860. "--simple boundary\r\n"
  11861. "Content-Disposition: form-data; name=\"field1\"\r\n"
  11862. "\r\n"
  11863. "value1\r\n"
  11864. "--simple boundary\r\n"
  11865. "Content-Disposition: form-data; name=\"field2\"; "
  11866. "filename=\"example.txt\"\r\n"
  11867. "\r\n"
  11868. "value2\r\n"
  11869. "--simple boundary--\r\n"
  11870. "This is the epilogue. It is also to be ignored.\r\n";
  11871. std::string content_type =
  11872. R"(multipart/form-data; boundary="simple boundary")";
  11873. Client cli(HOST, PORT);
  11874. auto res = cli.Post("/post", body, content_type.c_str());
  11875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11876. EXPECT_EQ(StatusCode::OK_200, res->status);
  11877. }
  11878. TEST(MultipartFormDataTest, PostCustomBoundary) {
  11879. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11880. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  11881. const ContentReader &content_reader) {
  11882. if (req.is_multipart_form_data()) {
  11883. std::vector<FormData> items;
  11884. content_reader(
  11885. [&](const FormData &file) {
  11886. items.push_back(file);
  11887. return true;
  11888. },
  11889. [&](const char *data, size_t data_length) {
  11890. items.back().content.append(data, data_length);
  11891. return true;
  11892. });
  11893. EXPECT_TRUE(std::string(items[0].name) == "document");
  11894. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  11895. EXPECT_TRUE(items[0].filename == "2MB_data");
  11896. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  11897. EXPECT_TRUE(items[1].name == "hello");
  11898. EXPECT_TRUE(items[1].content == "world");
  11899. EXPECT_TRUE(items[1].filename == "");
  11900. EXPECT_TRUE(items[1].content_type == "");
  11901. } else {
  11902. std::string body;
  11903. content_reader([&](const char *data, size_t data_length) {
  11904. body.append(data, data_length);
  11905. return true;
  11906. });
  11907. }
  11908. });
  11909. auto port = svr.bind_to_any_port("localhost");
  11910. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11911. auto se = detail::scope_exit([&] {
  11912. svr.stop();
  11913. t.join();
  11914. ASSERT_FALSE(svr.is_running());
  11915. });
  11916. svr.wait_until_ready();
  11917. {
  11918. std::string data(1024 * 1024 * 2, '.');
  11919. std::stringstream buffer;
  11920. buffer << data;
  11921. SSLClient cli("localhost", port);
  11922. cli.enable_server_certificate_verification(false);
  11923. UploadFormDataItems items{
  11924. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11925. {"hello", "world", "", ""},
  11926. };
  11927. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  11928. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11929. ASSERT_EQ(StatusCode::OK_200, res->status);
  11930. }
  11931. }
  11932. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  11933. std::string data(1024 * 1024 * 2, '&');
  11934. std::stringstream buffer;
  11935. buffer << data;
  11936. Client cli("https://localhost:8080");
  11937. UploadFormDataItems items{
  11938. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11939. {"hello", "world", "", ""},
  11940. };
  11941. for (const char &c : " \t\r\n") {
  11942. auto res =
  11943. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  11944. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  11945. ASSERT_FALSE(res);
  11946. }
  11947. }
  11948. TEST(MultipartFormDataTest, PutFormData) {
  11949. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11950. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  11951. const ContentReader &content_reader) {
  11952. if (req.is_multipart_form_data()) {
  11953. std::vector<FormData> items;
  11954. content_reader(
  11955. [&](const FormData &file) {
  11956. items.push_back(file);
  11957. return true;
  11958. },
  11959. [&](const char *data, size_t data_length) {
  11960. items.back().content.append(data, data_length);
  11961. return true;
  11962. });
  11963. EXPECT_TRUE(std::string(items[0].name) == "document");
  11964. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  11965. EXPECT_TRUE(items[0].filename == "2MB_data");
  11966. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  11967. EXPECT_TRUE(items[1].name == "hello");
  11968. EXPECT_TRUE(items[1].content == "world");
  11969. EXPECT_TRUE(items[1].filename == "");
  11970. EXPECT_TRUE(items[1].content_type == "");
  11971. } else {
  11972. std::string body;
  11973. content_reader([&](const char *data, size_t data_length) {
  11974. body.append(data, data_length);
  11975. return true;
  11976. });
  11977. }
  11978. });
  11979. auto port = svr.bind_to_any_port("localhost");
  11980. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11981. auto se = detail::scope_exit([&] {
  11982. svr.stop();
  11983. t.join();
  11984. ASSERT_FALSE(svr.is_running());
  11985. });
  11986. svr.wait_until_ready();
  11987. {
  11988. std::string data(1024 * 1024 * 2, '&');
  11989. std::stringstream buffer;
  11990. buffer << data;
  11991. SSLClient cli("localhost", port);
  11992. cli.enable_server_certificate_verification(false);
  11993. UploadFormDataItems items{
  11994. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11995. {"hello", "world", "", ""},
  11996. };
  11997. auto res = cli.Put("/put", items);
  11998. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11999. ASSERT_EQ(StatusCode::OK_200, res->status);
  12000. }
  12001. }
  12002. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  12003. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12004. svr.Put("/put_customboundary",
  12005. [&](const Request &req, const Response & /*res*/,
  12006. const ContentReader &content_reader) {
  12007. if (req.is_multipart_form_data()) {
  12008. std::vector<FormData> items;
  12009. content_reader(
  12010. [&](const FormData &file) {
  12011. items.push_back(file);
  12012. return true;
  12013. },
  12014. [&](const char *data, size_t data_length) {
  12015. items.back().content.append(data, data_length);
  12016. return true;
  12017. });
  12018. EXPECT_TRUE(std::string(items[0].name) == "document");
  12019. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  12020. EXPECT_TRUE(items[0].filename == "2MB_data");
  12021. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  12022. EXPECT_TRUE(items[1].name == "hello");
  12023. EXPECT_TRUE(items[1].content == "world");
  12024. EXPECT_TRUE(items[1].filename == "");
  12025. EXPECT_TRUE(items[1].content_type == "");
  12026. } else {
  12027. std::string body;
  12028. content_reader([&](const char *data, size_t data_length) {
  12029. body.append(data, data_length);
  12030. return true;
  12031. });
  12032. }
  12033. });
  12034. auto port = svr.bind_to_any_port("localhost");
  12035. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12036. auto se = detail::scope_exit([&] {
  12037. svr.stop();
  12038. t.join();
  12039. ASSERT_FALSE(svr.is_running());
  12040. });
  12041. svr.wait_until_ready();
  12042. {
  12043. std::string data(1024 * 1024 * 2, '&');
  12044. std::stringstream buffer;
  12045. buffer << data;
  12046. SSLClient cli("localhost", port);
  12047. cli.enable_server_certificate_verification(false);
  12048. UploadFormDataItems items{
  12049. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  12050. {"hello", "world", "", ""},
  12051. };
  12052. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  12053. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12054. ASSERT_EQ(StatusCode::OK_200, res->status);
  12055. }
  12056. }
  12057. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  12058. std::string data(1024 * 1024 * 2, '&');
  12059. std::stringstream buffer;
  12060. buffer << data;
  12061. Client cli("https://localhost:8080");
  12062. cli.enable_server_certificate_verification(false);
  12063. UploadFormDataItems items{
  12064. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  12065. {"hello", "world", "", ""},
  12066. };
  12067. for (const char &c : " \t\r\n") {
  12068. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  12069. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  12070. ASSERT_FALSE(res);
  12071. }
  12072. }
  12073. TEST(MultipartFormDataTest, AlternateFilename) {
  12074. auto handled = false;
  12075. Server svr;
  12076. svr.Post("/test", [&](const Request &req, Response &res) {
  12077. ASSERT_EQ(2u, req.form.files.size());
  12078. ASSERT_EQ(1u, req.form.fields.size());
  12079. // Test files
  12080. const auto &file1 = req.form.get_file("file1");
  12081. ASSERT_EQ("file1", file1.name);
  12082. ASSERT_EQ("A.txt", file1.filename);
  12083. ASSERT_EQ("text/plain", file1.content_type);
  12084. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  12085. const auto &file2 = req.form.get_file("file2");
  12086. ASSERT_EQ("file2", file2.name);
  12087. ASSERT_EQ("a.html", file2.filename);
  12088. ASSERT_EQ("text/html", file2.content_type);
  12089. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  12090. file2.content);
  12091. // Test text field
  12092. const auto &text = req.form.get_field("text");
  12093. ASSERT_EQ("text default", text);
  12094. res.set_content("ok", "text/plain");
  12095. handled = true;
  12096. });
  12097. thread t = thread([&] { svr.listen(HOST, PORT); });
  12098. auto se = detail::scope_exit([&] {
  12099. svr.stop();
  12100. t.join();
  12101. ASSERT_FALSE(svr.is_running());
  12102. ASSERT_TRUE(handled);
  12103. });
  12104. svr.wait_until_ready();
  12105. auto req = "POST /test HTTP/1.1\r\n"
  12106. "Content-Type: multipart/form-data;boundary=--------\r\n"
  12107. "Content-Length: 399\r\n"
  12108. "\r\n"
  12109. "----------\r\n"
  12110. "Content-Disposition: form-data; name=\"text\"\r\n"
  12111. "\r\n"
  12112. "text default\r\n"
  12113. "----------\r\n"
  12114. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  12115. "filename=\"a.txt\"; name=\"file1\"\r\n"
  12116. "Content-Type: text/plain\r\n"
  12117. "\r\n"
  12118. "Content of a.txt.\r\n"
  12119. "\r\n"
  12120. "----------\r\n"
  12121. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  12122. "\"a.html\"\r\n"
  12123. "Content-Type: text/html\r\n"
  12124. "\r\n"
  12125. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  12126. "\r\n"
  12127. "------------\r\n";
  12128. ASSERT_TRUE(send_request(1, req));
  12129. }
  12130. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  12131. auto handled = false;
  12132. Server svr;
  12133. svr.Post("/test", [&](const Request &req, Response &res) {
  12134. // Case-insensitive "utf-8''" prefix with a long value
  12135. const auto &file = req.form.get_file("file1");
  12136. ASSERT_EQ("file1", file.name);
  12137. // 8000 chars exercises both the Content-Disposition parser and the
  12138. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  12139. // Prior to the fix, std::regex_match on this header would cause O(N)
  12140. // stack recursion in libstdc++, leading to SIGSEGV.
  12141. std::string expected_filename(8000, 'A');
  12142. ASSERT_EQ(expected_filename, file.filename);
  12143. res.set_content("ok", "text/plain");
  12144. handled = true;
  12145. });
  12146. thread t = thread([&] { svr.listen(HOST, PORT); });
  12147. auto se = detail::scope_exit([&] {
  12148. svr.stop();
  12149. t.join();
  12150. ASSERT_FALSE(svr.is_running());
  12151. ASSERT_TRUE(handled);
  12152. });
  12153. svr.wait_until_ready();
  12154. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  12155. // Regression test for GHSA-qq6v-r583-3h69
  12156. std::string long_filename(8000, 'A');
  12157. std::string body = "----------\r\n"
  12158. "Content-Disposition: form-data; name=\"file1\"; "
  12159. "filename*=\"Utf-8''" +
  12160. long_filename +
  12161. "\"\r\n"
  12162. "\r\n"
  12163. "hello\r\n"
  12164. "------------\r\n";
  12165. auto req = "POST /test HTTP/1.1\r\n"
  12166. "Content-Type: multipart/form-data;boundary=--------\r\n"
  12167. "Content-Length: " +
  12168. std::to_string(body.size()) + "\r\n\r\n" + body;
  12169. ASSERT_TRUE(send_request(1, req));
  12170. }
  12171. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  12172. auto handled = false;
  12173. Server svr;
  12174. svr.Post("/test", [&](const Request &req, Response &) {
  12175. ASSERT_EQ(2u, req.form.fields.size());
  12176. const auto &text1 = req.form.get_field("text1");
  12177. ASSERT_EQ("text1", text1);
  12178. const auto &text2 = req.form.get_field("text2");
  12179. ASSERT_EQ("text2", text2);
  12180. handled = true;
  12181. });
  12182. thread t = thread([&] { svr.listen(HOST, PORT); });
  12183. auto se = detail::scope_exit([&] {
  12184. svr.stop();
  12185. t.join();
  12186. ASSERT_FALSE(svr.is_running());
  12187. ASSERT_TRUE(handled);
  12188. });
  12189. svr.wait_until_ready();
  12190. auto req = "POST /test HTTP/1.1\r\n"
  12191. "Content-Type: multipart/form-data;boundary=--------\r\n"
  12192. "Content-Length: 146\r\n"
  12193. "\r\n----------\r\n"
  12194. "Content-Disposition: form-data; name=\"text1\"\r\n"
  12195. "\r\n"
  12196. "text1"
  12197. "\r\n----------\r\n"
  12198. "Content-Disposition: form-data; name=\"text2\"\r\n"
  12199. "\r\n"
  12200. "text2"
  12201. "\r\n------------";
  12202. std::string response;
  12203. ASSERT_TRUE(send_request(1, req, &response));
  12204. ASSERT_EQ("200", response.substr(9, 3));
  12205. }
  12206. TEST(MultipartFormDataTest, ContentLength) {
  12207. auto handled = false;
  12208. Server svr;
  12209. svr.Post("/test", [&](const Request &req, Response &) {
  12210. ASSERT_EQ(2u, req.form.fields.size());
  12211. const auto &text1 = req.form.get_field("text1");
  12212. ASSERT_EQ("text1", text1);
  12213. const auto &text2 = req.form.get_field("text2");
  12214. ASSERT_EQ("text2", text2);
  12215. handled = true;
  12216. });
  12217. thread t = thread([&] { svr.listen(HOST, PORT); });
  12218. auto se = detail::scope_exit([&] {
  12219. svr.stop();
  12220. t.join();
  12221. ASSERT_FALSE(svr.is_running());
  12222. ASSERT_TRUE(handled);
  12223. });
  12224. svr.wait_until_ready();
  12225. auto req = "POST /test HTTP/1.1\r\n"
  12226. "Content-Type: multipart/form-data;boundary=--------\r\n"
  12227. "Content-Length: 167\r\n"
  12228. "\r\n----------\r\n"
  12229. "Content-Disposition: form-data; name=\"text1\"\r\n"
  12230. "Content-Length: 5\r\n"
  12231. "\r\n"
  12232. "text1"
  12233. "\r\n----------\r\n"
  12234. "Content-Disposition: form-data; name=\"text2\"\r\n"
  12235. "\r\n"
  12236. "text2"
  12237. "\r\n------------\r\n";
  12238. std::string response;
  12239. ASSERT_TRUE(send_request(1, req, &response));
  12240. ASSERT_EQ("200", response.substr(9, 3));
  12241. }
  12242. TEST(MultipartFormDataTest, AccessPartHeaders) {
  12243. auto handled = false;
  12244. Server svr;
  12245. svr.Post("/test", [&](const Request &req, Response &) {
  12246. ASSERT_EQ(2u, req.form.fields.size());
  12247. const auto &text1 = req.form.get_field("text1");
  12248. ASSERT_EQ("text1", text1);
  12249. // TODO: Add header access for text fields if needed
  12250. const auto &text2 = req.form.get_field("text2");
  12251. ASSERT_EQ("text2", text2);
  12252. // TODO: Header access for text fields needs to be implemented
  12253. // auto &headers = it->second.headers;
  12254. // ASSERT_EQ(3U, headers.size());
  12255. // auto custom_header = headers.find("x-whatever");
  12256. // ASSERT_TRUE(custom_header != headers.end());
  12257. // ASSERT_NE("customvalue", custom_header->second);
  12258. // ASSERT_EQ("CustomValue", custom_header->second);
  12259. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  12260. handled = true;
  12261. });
  12262. thread t = thread([&] { svr.listen(HOST, PORT); });
  12263. auto se = detail::scope_exit([&] {
  12264. svr.stop();
  12265. t.join();
  12266. ASSERT_FALSE(svr.is_running());
  12267. ASSERT_TRUE(handled);
  12268. });
  12269. svr.wait_until_ready();
  12270. auto req = "POST /test HTTP/1.1\r\n"
  12271. "Content-Type: multipart/form-data;boundary=--------\r\n"
  12272. "Content-Length: 232\r\n"
  12273. "\r\n----------\r\n"
  12274. "Content-Disposition: form-data; name=\"text1\"\r\n"
  12275. "Content-Length: 5\r\n"
  12276. "X-Test: 1\r\n"
  12277. "\r\n"
  12278. "text1"
  12279. "\r\n----------\r\n"
  12280. "Content-Disposition: form-data; name=\"text2\"\r\n"
  12281. "Content-Type: text/plain\r\n"
  12282. "X-Whatever: CustomValue\r\n"
  12283. "\r\n"
  12284. "text2"
  12285. "\r\n------------\r\n"
  12286. "That should be disregarded. Not even read";
  12287. std::string response;
  12288. ASSERT_TRUE(send_request(1, req, &response));
  12289. ASSERT_EQ("200", response.substr(9, 3));
  12290. }
  12291. TEST(MultipartFormDataTest, LargeHeader) {
  12292. auto handled = false;
  12293. Server svr;
  12294. svr.Post("/test", [&](const Request &req, Response &) {
  12295. ASSERT_EQ(1u, req.form.fields.size());
  12296. const auto &text = req.form.get_field("name1");
  12297. ASSERT_EQ("text1", text);
  12298. handled = true;
  12299. });
  12300. thread t = thread([&] { svr.listen(HOST, PORT); });
  12301. auto se = detail::scope_exit([&] {
  12302. svr.stop();
  12303. t.join();
  12304. ASSERT_FALSE(svr.is_running());
  12305. ASSERT_TRUE(handled);
  12306. });
  12307. svr.wait_until_ready();
  12308. auto boundary = std::string("cpp-httplib-multipart-data");
  12309. std::string content = "--" + boundary +
  12310. "\r\n"
  12311. "Content-Disposition: form-data; name=\"name1\"\r\n"
  12312. "\r\n"
  12313. "text1\r\n"
  12314. "--" +
  12315. boundary + "--\r\n";
  12316. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  12317. "Content-Type: multipart/form-data;boundary=" +
  12318. boundary +
  12319. "\r\n"
  12320. "Content-Length: " +
  12321. std::to_string(content.size()) +
  12322. "\r\n"
  12323. "Dummy-Header: ";
  12324. std::string header_suffix = "\r\n"
  12325. "\r\n";
  12326. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  12327. size_t header_dummy_size =
  12328. read_buff_size -
  12329. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  12330. auto header_dummy = std::string(header_dummy_size, '@');
  12331. auto req = header_prefix + header_dummy + header_suffix + content;
  12332. std::string response;
  12333. ASSERT_TRUE(send_request(1, req, &response));
  12334. ASSERT_EQ("200", response.substr(9, 3));
  12335. }
  12336. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  12337. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  12338. // (not chunked Transfer-Encoding) after the streaming refactor.
  12339. auto handled = false;
  12340. Server svr;
  12341. svr.Post("/upload", [&](const Request &req, Response &res) {
  12342. auto cl_it = req.headers.find("Content-Length");
  12343. EXPECT_TRUE(cl_it != req.headers.end());
  12344. auto te_it = req.headers.find("Transfer-Encoding");
  12345. EXPECT_TRUE(te_it == req.headers.end());
  12346. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  12347. res.set_content("ok", "text/plain");
  12348. handled = true;
  12349. });
  12350. auto port = svr.bind_to_any_port(HOST);
  12351. auto t = thread([&] { svr.listen_after_bind(); });
  12352. auto se = detail::scope_exit([&] {
  12353. svr.stop();
  12354. t.join();
  12355. ASSERT_FALSE(svr.is_running());
  12356. ASSERT_TRUE(handled);
  12357. });
  12358. svr.wait_until_ready();
  12359. UploadFormDataItems items = {
  12360. {"field1", "hello", "", "text/plain"},
  12361. {"file1", "world", "test.txt", "application/octet-stream"},
  12362. };
  12363. Client cli(HOST, port);
  12364. auto res = cli.Post("/upload", {}, items);
  12365. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12366. EXPECT_EQ(StatusCode::OK_200, res->status);
  12367. }
  12368. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  12369. // Verify that make_multipart_content_provider coalesces many small segments
  12370. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  12371. constexpr size_t kItemCount = 1000;
  12372. UploadFormDataItems items;
  12373. items.reserve(kItemCount);
  12374. for (size_t i = 0; i < kItemCount; i++) {
  12375. items.push_back(
  12376. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  12377. }
  12378. const std::string boundary = "----test-boundary";
  12379. auto content_length = detail::get_multipart_content_length(items, boundary);
  12380. auto provider = detail::make_multipart_content_provider(items, boundary);
  12381. // Drive the provider the same way write_content_with_progress does
  12382. size_t write_count = 0;
  12383. size_t total_bytes = 0;
  12384. DataSink sink;
  12385. size_t offset = 0;
  12386. sink.write = [&](const char *d, size_t l) -> bool {
  12387. (void)d;
  12388. write_count++;
  12389. total_bytes += l;
  12390. offset += l;
  12391. return true;
  12392. };
  12393. sink.is_writable = []() -> bool { return true; };
  12394. while (offset < content_length) {
  12395. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  12396. }
  12397. EXPECT_EQ(content_length, total_bytes);
  12398. // The total number of segments is 3 * kItemCount + 1 = 3001.
  12399. // With buffering into 64KB blocks, write_count should be much smaller.
  12400. auto segment_count = 3 * kItemCount + 1;
  12401. EXPECT_LT(write_count, segment_count / 10);
  12402. }
  12403. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  12404. // Integration test: send many UploadFormDataItems and verify the server
  12405. // receives all of them correctly (#2410).
  12406. constexpr size_t kItemCount = 500;
  12407. auto handled = false;
  12408. Server svr;
  12409. svr.Post("/upload", [&](const Request &req, Response &res) {
  12410. EXPECT_EQ(kItemCount, req.form.fields.size());
  12411. for (size_t i = 0; i < kItemCount; i++) {
  12412. auto key = "field" + std::to_string(i);
  12413. auto val = "value" + std::to_string(i);
  12414. auto it = req.form.fields.find(key);
  12415. if (it != req.form.fields.end()) {
  12416. EXPECT_EQ(val, it->second.content);
  12417. } else {
  12418. ADD_FAILURE() << "Missing field: " << key;
  12419. }
  12420. }
  12421. res.set_content("ok", "text/plain");
  12422. handled = true;
  12423. });
  12424. auto port = svr.bind_to_any_port(HOST);
  12425. auto t = thread([&] { svr.listen_after_bind(); });
  12426. auto se = detail::scope_exit([&] {
  12427. svr.stop();
  12428. t.join();
  12429. ASSERT_FALSE(svr.is_running());
  12430. ASSERT_TRUE(handled);
  12431. });
  12432. svr.wait_until_ready();
  12433. UploadFormDataItems items;
  12434. items.reserve(kItemCount);
  12435. for (size_t i = 0; i < kItemCount; i++) {
  12436. items.push_back(
  12437. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  12438. }
  12439. Client cli(HOST, port);
  12440. auto res = cli.Post("/upload", items);
  12441. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12442. EXPECT_EQ(StatusCode::OK_200, res->status);
  12443. }
  12444. TEST(MultipartFormDataTest, MakeFileProvider) {
  12445. // Verify make_file_provider sends a file's contents correctly.
  12446. const std::string file_content(4096, 'Z');
  12447. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  12448. {
  12449. std::ofstream ofs(tmp_path, std::ios::binary);
  12450. ofs.write(file_content.data(),
  12451. static_cast<std::streamsize>(file_content.size()));
  12452. }
  12453. auto handled = false;
  12454. Server svr;
  12455. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  12456. const ContentReader &content_reader) {
  12457. ASSERT_TRUE(req.is_multipart_form_data());
  12458. std::vector<FormData> items;
  12459. content_reader(
  12460. [&](const FormData &file) {
  12461. items.push_back(file);
  12462. return true;
  12463. },
  12464. [&](const char *data, size_t data_length) {
  12465. items.back().content.append(data, data_length);
  12466. return true;
  12467. });
  12468. ASSERT_EQ(1u, items.size());
  12469. EXPECT_EQ("myfile", items[0].name);
  12470. EXPECT_EQ("data.bin", items[0].filename);
  12471. EXPECT_EQ("application/octet-stream", items[0].content_type);
  12472. EXPECT_EQ(file_content, items[0].content);
  12473. handled = true;
  12474. });
  12475. auto port = svr.bind_to_any_port(HOST);
  12476. auto t = thread([&] { svr.listen_after_bind(); });
  12477. auto se = detail::scope_exit([&] {
  12478. svr.stop();
  12479. t.join();
  12480. ASSERT_FALSE(svr.is_running());
  12481. ASSERT_TRUE(handled);
  12482. std::remove(tmp_path.c_str());
  12483. });
  12484. svr.wait_until_ready();
  12485. FormDataProviderItems providers;
  12486. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  12487. "application/octet-stream"));
  12488. Client cli(HOST, port);
  12489. auto res = cli.Post("/upload", {}, {}, providers);
  12490. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12491. EXPECT_EQ(StatusCode::OK_200, res->status);
  12492. }
  12493. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  12494. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  12495. // (100) headers is rejected with a 400 Bad Request response.
  12496. Server svr;
  12497. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  12498. res.set_content("ok", "text/plain");
  12499. });
  12500. thread t = thread([&] { svr.listen(HOST, PORT); });
  12501. auto se = detail::scope_exit([&] {
  12502. svr.stop();
  12503. t.join();
  12504. ASSERT_FALSE(svr.is_running());
  12505. });
  12506. svr.wait_until_ready();
  12507. // Build a multipart part with 101 custom headers (exceeding
  12508. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  12509. std::stringstream body;
  12510. body << "--simpleboundary\r\n"
  12511. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  12512. for (int i = 0; i < 101; i++) {
  12513. body << "X-Custom-Header-" << i << ": value\r\n";
  12514. }
  12515. body << "\r\n"
  12516. << "value1\r\n"
  12517. << "--simpleboundary--\r\n";
  12518. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  12519. Client cli(HOST, PORT);
  12520. auto res = cli.Post("/post", body.str(), content_type.c_str());
  12521. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12522. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  12523. }
  12524. TEST(MakeFileBodyTest, Basic) {
  12525. const std::string file_content(4096, 'Z');
  12526. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  12527. {
  12528. std::ofstream ofs(tmp_path, std::ios::binary);
  12529. ofs.write(file_content.data(),
  12530. static_cast<std::streamsize>(file_content.size()));
  12531. }
  12532. auto handled = false;
  12533. Server svr;
  12534. svr.Post("/upload", [&](const Request &req, Response &res) {
  12535. EXPECT_EQ(file_content, req.body);
  12536. handled = true;
  12537. res.status = StatusCode::OK_200;
  12538. });
  12539. auto port = svr.bind_to_any_port(HOST);
  12540. auto t = thread([&] { svr.listen_after_bind(); });
  12541. auto se = detail::scope_exit([&] {
  12542. svr.stop();
  12543. t.join();
  12544. ASSERT_FALSE(svr.is_running());
  12545. ASSERT_TRUE(handled);
  12546. std::remove(tmp_path.c_str());
  12547. });
  12548. svr.wait_until_ready();
  12549. auto fb = make_file_body(tmp_path);
  12550. ASSERT_GT(fb.first, 0u);
  12551. Client cli(HOST, port);
  12552. auto res =
  12553. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  12554. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12555. EXPECT_EQ(StatusCode::OK_200, res->status);
  12556. }
  12557. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  12558. static constexpr unsigned int number_of_tasks{1000000};
  12559. std::atomic_uint count{0};
  12560. std::unique_ptr<TaskQueue> task_queue{
  12561. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  12562. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  12563. auto queued = task_queue->enqueue(
  12564. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  12565. EXPECT_TRUE(queued);
  12566. }
  12567. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  12568. task_queue->shutdown();
  12569. #else
  12570. EXPECT_NO_THROW(task_queue->shutdown());
  12571. #endif
  12572. EXPECT_EQ(number_of_tasks, count.load());
  12573. }
  12574. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  12575. static constexpr unsigned int number_of_tasks{1000000};
  12576. static constexpr unsigned int qlimit{2};
  12577. unsigned int queued_count{0};
  12578. std::atomic_uint count{0};
  12579. std::unique_ptr<TaskQueue> task_queue{
  12580. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  12581. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  12582. if (task_queue->enqueue(
  12583. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  12584. queued_count++;
  12585. }
  12586. }
  12587. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  12588. task_queue->shutdown();
  12589. #else
  12590. EXPECT_NO_THROW(task_queue->shutdown());
  12591. #endif
  12592. EXPECT_EQ(queued_count, count.load());
  12593. EXPECT_TRUE(queued_count <= number_of_tasks);
  12594. EXPECT_TRUE(queued_count >= qlimit);
  12595. }
  12596. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  12597. // Use a short idle timeout so a dynamic thread spawns, times out and
  12598. // exits during the test, and the pool keeps working afterwards.
  12599. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  12600. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  12601. /*idle_timeout_sec=*/1}};
  12602. std::atomic_uint count{0};
  12603. std::condition_variable cv;
  12604. std::mutex mtx;
  12605. bool release = false;
  12606. // Block the base thread so the second task spawns a dynamic thread.
  12607. EXPECT_TRUE(task_queue->enqueue([&] {
  12608. std::unique_lock<std::mutex> lock(mtx);
  12609. while (!release) {
  12610. cv.wait(lock);
  12611. }
  12612. count++;
  12613. }));
  12614. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  12615. // Let the dynamic thread finish its task and exceed the idle timeout.
  12616. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  12617. {
  12618. std::unique_lock<std::mutex> lock(mtx);
  12619. release = true;
  12620. }
  12621. cv.notify_all();
  12622. // The pool must still accept and run tasks after the dynamic thread exited.
  12623. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  12624. task_queue->shutdown();
  12625. EXPECT_EQ(3u, count.load());
  12626. }
  12627. TEST(TaskQueueTest, MaxQueuedRequests) {
  12628. static constexpr unsigned int qlimit{3};
  12629. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  12630. std::condition_variable sem_cv;
  12631. std::mutex sem_mtx;
  12632. int credits = 0;
  12633. bool queued;
  12634. /* Fill up the queue with tasks that will block until we give them credits to
  12635. * complete. */
  12636. for (unsigned int n = 0; n <= qlimit;) {
  12637. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  12638. std::unique_lock<std::mutex> lock(sem_mtx);
  12639. while (credits <= 0) {
  12640. sem_cv.wait(lock);
  12641. }
  12642. /* Consume the credit and signal the test code if they are all gone. */
  12643. if (--credits == 0) { sem_cv.notify_one(); }
  12644. });
  12645. if (n < qlimit) {
  12646. /* The first qlimit enqueues must succeed. */
  12647. EXPECT_TRUE(queued);
  12648. } else {
  12649. /* The last one will succeed only when the worker thread
  12650. * starts and dequeues the first blocking task. Although
  12651. * not necessary for the correctness of this test, we sleep for
  12652. * a short while to avoid busy waiting. */
  12653. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12654. }
  12655. if (queued) { n++; }
  12656. }
  12657. /* Further enqueues must fail since the queue is full. */
  12658. for (auto i = 0; i < 4; i++) {
  12659. queued = task_queue->enqueue([] {});
  12660. EXPECT_FALSE(queued);
  12661. }
  12662. /* Give the credits to allow the previous tasks to complete. */
  12663. {
  12664. std::unique_lock<std::mutex> lock(sem_mtx);
  12665. credits += qlimit + 1;
  12666. }
  12667. sem_cv.notify_all();
  12668. /* Wait for all the credits to be consumed. */
  12669. {
  12670. std::unique_lock<std::mutex> lock(sem_mtx);
  12671. while (credits > 0) {
  12672. sem_cv.wait(lock);
  12673. }
  12674. }
  12675. /* Check that we are able again to enqueue at least qlimit tasks. */
  12676. for (unsigned int i = 0; i < qlimit; i++) {
  12677. queued = task_queue->enqueue([] {});
  12678. EXPECT_TRUE(queued);
  12679. }
  12680. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  12681. task_queue->shutdown();
  12682. #else
  12683. EXPECT_NO_THROW(task_queue->shutdown());
  12684. #endif
  12685. }
  12686. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  12687. Server svr;
  12688. svr.Get("/", [](const Request & /*req*/, Response &res) {
  12689. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  12690. });
  12691. svr.Get("/hello", [](const Request &req, Response &res) {
  12692. res.set_content(req.get_param_value("key"), "text/plain");
  12693. });
  12694. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12695. auto se = detail::scope_exit([&] {
  12696. svr.stop();
  12697. thread.join();
  12698. ASSERT_FALSE(svr.is_running());
  12699. });
  12700. svr.wait_until_ready();
  12701. {
  12702. Client cli(HOST, PORT);
  12703. cli.set_follow_location(true);
  12704. auto res = cli.Get("/");
  12705. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12706. EXPECT_EQ(StatusCode::OK_200, res->status);
  12707. EXPECT_EQ("val&key2=val2", res->body);
  12708. }
  12709. }
  12710. #endif
  12711. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  12712. Server svr;
  12713. svr.Get("/", [](const Request & /*req*/, Response &res) {
  12714. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  12715. });
  12716. svr.Get("/hello", [](const Request &req, Response &res) {
  12717. res.set_content(req.get_param_value("key"), "text/plain");
  12718. });
  12719. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12720. auto se = detail::scope_exit([&] {
  12721. svr.stop();
  12722. thread.join();
  12723. ASSERT_FALSE(svr.is_running());
  12724. });
  12725. svr.wait_until_ready();
  12726. {
  12727. Client cli(HOST, PORT);
  12728. cli.set_follow_location(true);
  12729. auto res = cli.Get("/");
  12730. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12731. EXPECT_EQ(StatusCode::OK_200, res->status);
  12732. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  12733. }
  12734. }
  12735. TEST(RedirectTest, RedirectWithPlusInPath) {
  12736. Server svr;
  12737. svr.Get("/", [](const Request & /*req*/, Response &res) {
  12738. res.set_redirect("/a+b");
  12739. });
  12740. // Route pattern uses regex; escape + as \\+
  12741. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  12742. res.set_content(req.path, "text/plain");
  12743. });
  12744. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12745. auto se = detail::scope_exit([&] {
  12746. svr.stop();
  12747. thread.join();
  12748. ASSERT_FALSE(svr.is_running());
  12749. });
  12750. svr.wait_until_ready();
  12751. {
  12752. Client cli(HOST, PORT);
  12753. cli.set_follow_location(true);
  12754. auto res = cli.Get("/");
  12755. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12756. EXPECT_EQ(StatusCode::OK_200, res->status);
  12757. EXPECT_EQ("/a+b", res->body);
  12758. }
  12759. }
  12760. #ifdef CPPHTTPLIB_SSL_ENABLED
  12761. TEST(RedirectTest, Issue2185_Online) {
  12762. SSLClient client("github.com");
  12763. client.set_follow_location(true);
  12764. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  12765. "Coollab-Windows.zip");
  12766. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12767. EXPECT_EQ(StatusCode::OK_200, res->status);
  12768. EXPECT_EQ(9920427U, res->body.size());
  12769. }
  12770. #endif
  12771. TEST(VulnerabilityTest, CRLFInjection) {
  12772. Server svr;
  12773. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  12774. res.set_content("Hello 1", "text/plain");
  12775. });
  12776. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  12777. res.set_content("Hello 2", "text/plain");
  12778. });
  12779. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  12780. res.set_content("Hello 3", "text/plain");
  12781. });
  12782. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  12783. res.set_content("Hello 4", "text/plain");
  12784. });
  12785. svr.set_logger([](const Request &req, const Response & /*res*/) {
  12786. for (const auto &x : req.headers) {
  12787. auto key = x.first;
  12788. EXPECT_STRNE("evil", key.c_str());
  12789. }
  12790. });
  12791. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12792. auto se = detail::scope_exit([&] {
  12793. svr.stop();
  12794. thread.join();
  12795. ASSERT_FALSE(svr.is_running());
  12796. });
  12797. svr.wait_until_ready();
  12798. {
  12799. Client cli(HOST, PORT);
  12800. cli.Post("/test1", "A=B",
  12801. "application/x-www-form-urlencoded\r\nevil: hello1");
  12802. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  12803. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  12804. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  12805. }
  12806. }
  12807. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  12808. auto server_thread = std::thread([] {
  12809. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12810. default_socket_options(srv);
  12811. sockaddr_in addr{};
  12812. addr.sin_family = AF_INET;
  12813. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  12814. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12815. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12816. ::listen(srv, 1);
  12817. sockaddr_in cli_addr{};
  12818. socklen_t cli_len = sizeof(cli_addr);
  12819. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12820. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  12821. std::string buf_all;
  12822. char buf[2048];
  12823. ssize_t n;
  12824. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  12825. buf_all.append(buf, static_cast<size_t>(n));
  12826. size_t pos;
  12827. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  12828. auto request_block = buf_all.substr(0, pos + 4); // include separator
  12829. auto e = request_block.find("\r\n");
  12830. if (e != std::string::npos) {
  12831. auto request_line = request_block.substr(0, e);
  12832. std::string msg =
  12833. "CRLF injection detected in request line: '" + request_line + "'";
  12834. EXPECT_FALSE(true) << msg;
  12835. }
  12836. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  12837. ::send(cli,
  12838. #ifdef _WIN32
  12839. static_cast<const char *>(resp.c_str()),
  12840. static_cast<int>(resp.size()),
  12841. #else
  12842. resp.c_str(), resp.size(),
  12843. #endif
  12844. 0);
  12845. buf_all.erase(0, pos + 4);
  12846. }
  12847. }
  12848. detail::close_socket(cli);
  12849. detail::close_socket(srv);
  12850. });
  12851. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12852. auto cli = Client("127.0.0.1", PORT + 1);
  12853. auto headers = Headers{
  12854. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  12855. {"Connection", "keep-alive"}};
  12856. auto res = cli.Get("/hi", headers);
  12857. EXPECT_FALSE(res);
  12858. EXPECT_EQ(Error::InvalidHeaders, res.error());
  12859. server_thread.join();
  12860. }
  12861. TEST(PathParamsTest, StaticMatch) {
  12862. const auto pattern = "/users/all";
  12863. detail::PathParamsMatcher matcher(pattern);
  12864. Request request;
  12865. request.path = "/users/all";
  12866. ASSERT_TRUE(matcher.match(request));
  12867. std::unordered_map<std::string, std::string> expected_params = {};
  12868. EXPECT_EQ(request.path_params, expected_params);
  12869. }
  12870. TEST(PathParamsTest, StaticMismatch) {
  12871. const auto pattern = "/users/all";
  12872. detail::PathParamsMatcher matcher(pattern);
  12873. Request request;
  12874. request.path = "/users/1";
  12875. ASSERT_FALSE(matcher.match(request));
  12876. }
  12877. TEST(PathParamsTest, SingleParamInTheMiddle) {
  12878. const auto pattern = "/users/:id/subscriptions";
  12879. detail::PathParamsMatcher matcher(pattern);
  12880. Request request;
  12881. request.path = "/users/42/subscriptions";
  12882. ASSERT_TRUE(matcher.match(request));
  12883. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  12884. EXPECT_EQ(request.path_params, expected_params);
  12885. }
  12886. TEST(PathParamsTest, SingleParamInTheEnd) {
  12887. const auto pattern = "/users/:id";
  12888. detail::PathParamsMatcher matcher(pattern);
  12889. Request request;
  12890. request.path = "/users/24";
  12891. ASSERT_TRUE(matcher.match(request));
  12892. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  12893. EXPECT_EQ(request.path_params, expected_params);
  12894. }
  12895. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  12896. const auto pattern = "/users/:id/";
  12897. detail::PathParamsMatcher matcher(pattern);
  12898. Request request;
  12899. request.path = "/users/42/";
  12900. ASSERT_TRUE(matcher.match(request));
  12901. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  12902. EXPECT_EQ(request.path_params, expected_params);
  12903. }
  12904. TEST(PathParamsTest, EmptyParam) {
  12905. const auto pattern = "/users/:id/";
  12906. detail::PathParamsMatcher matcher(pattern);
  12907. Request request;
  12908. request.path = "/users//";
  12909. ASSERT_TRUE(matcher.match(request));
  12910. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  12911. EXPECT_EQ(request.path_params, expected_params);
  12912. }
  12913. TEST(PathParamsTest, FragmentMismatch) {
  12914. const auto pattern = "/users/:id/";
  12915. detail::PathParamsMatcher matcher(pattern);
  12916. Request request;
  12917. request.path = "/admins/24/";
  12918. ASSERT_FALSE(matcher.match(request));
  12919. }
  12920. TEST(PathParamsTest, ExtraFragments) {
  12921. const auto pattern = "/users/:id";
  12922. detail::PathParamsMatcher matcher(pattern);
  12923. Request request;
  12924. request.path = "/users/42/subscriptions";
  12925. ASSERT_FALSE(matcher.match(request));
  12926. }
  12927. TEST(PathParamsTest, MissingTrailingParam) {
  12928. const auto pattern = "/users/:id";
  12929. detail::PathParamsMatcher matcher(pattern);
  12930. Request request;
  12931. request.path = "/users";
  12932. ASSERT_FALSE(matcher.match(request));
  12933. }
  12934. TEST(PathParamsTest, MissingParamInTheMiddle) {
  12935. const auto pattern = "/users/:id/subscriptions";
  12936. detail::PathParamsMatcher matcher(pattern);
  12937. Request request;
  12938. request.path = "/users/subscriptions";
  12939. ASSERT_FALSE(matcher.match(request));
  12940. }
  12941. TEST(PathParamsTest, MultipleParams) {
  12942. const auto pattern = "/users/:userid/subscriptions/:subid";
  12943. detail::PathParamsMatcher matcher(pattern);
  12944. Request request;
  12945. request.path = "/users/42/subscriptions/2";
  12946. ASSERT_TRUE(matcher.match(request));
  12947. std::unordered_map<std::string, std::string> expected_params = {
  12948. {"userid", "42"}, {"subid", "2"}};
  12949. EXPECT_EQ(request.path_params, expected_params);
  12950. }
  12951. TEST(PathParamsTest, SequenceOfParams) {
  12952. const auto pattern = "/values/:x/:y/:z";
  12953. detail::PathParamsMatcher matcher(pattern);
  12954. Request request;
  12955. request.path = "/values/1/2/3";
  12956. ASSERT_TRUE(matcher.match(request));
  12957. std::unordered_map<std::string, std::string> expected_params = {
  12958. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  12959. EXPECT_EQ(request.path_params, expected_params);
  12960. }
  12961. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  12962. const auto pattern = "/prefix:suffix";
  12963. detail::PathParamsMatcher matcher(pattern);
  12964. Request request;
  12965. request.path = "/prefix:suffix";
  12966. ASSERT_TRUE(matcher.match(request));
  12967. const std::unordered_map<std::string, std::string> expected_params = {};
  12968. EXPECT_EQ(request.path_params, expected_params);
  12969. }
  12970. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  12971. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  12972. // calling thread's stack on a long enough path for a quantified pattern;
  12973. // RegexMatcher must refuse to run regex matching on paths beyond
  12974. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  12975. detail::RegexMatcher matcher("/files/(.*)");
  12976. Request within_limit;
  12977. within_limit.path = "/files/" + std::string(10, 'A');
  12978. EXPECT_TRUE(matcher.match(within_limit));
  12979. Request over_limit;
  12980. over_limit.path =
  12981. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  12982. EXPECT_FALSE(matcher.match(over_limit));
  12983. }
  12984. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  12985. Server svr;
  12986. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  12987. res.set_content("ok", "text/plain");
  12988. });
  12989. auto port = svr.bind_to_any_port(HOST);
  12990. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  12991. auto se = detail::scope_exit([&] {
  12992. svr.stop();
  12993. thread.join();
  12994. ASSERT_FALSE(svr.is_running());
  12995. });
  12996. svr.wait_until_ready();
  12997. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  12998. // request URI limit; this used to be able to crash the process.
  12999. std::string path =
  13000. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  13001. std::string req = "GET " + path +
  13002. " HTTP/1.1\r\n"
  13003. "Host: " +
  13004. std::string(HOST) + ":" + std::to_string(port) +
  13005. "\r\n"
  13006. "Connection: close\r\n"
  13007. "\r\n";
  13008. std::string response;
  13009. ASSERT_TRUE(send_request(5, req, &response, port));
  13010. EXPECT_NE(std::string::npos, response.find("404"));
  13011. }
  13012. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  13013. Server svr;
  13014. auto handler = [](const Request & /*req*/, Response &res) {
  13015. res.set_content("hit", "text/plain");
  13016. };
  13017. // No regex metacharacter, so this one is compared literally
  13018. svr.Get("/literal/route", handler);
  13019. // '.' is a regex metacharacter, so this one must keep regex semantics
  13020. svr.Get("/a.c", handler);
  13021. auto port = svr.bind_to_any_port(HOST);
  13022. std::thread t([&]() { svr.listen_after_bind(); });
  13023. auto se = detail::scope_exit([&] {
  13024. svr.stop();
  13025. t.join();
  13026. ASSERT_FALSE(svr.is_running());
  13027. });
  13028. svr.wait_until_ready();
  13029. Client cli(HOST, port);
  13030. struct {
  13031. const char *path;
  13032. int status;
  13033. } cases[] = {
  13034. {"/literal/route", StatusCode::OK_200},
  13035. {"/literal/routes", StatusCode::NotFound_404},
  13036. {"/literal/rout", StatusCode::NotFound_404},
  13037. {"/abc", StatusCode::OK_200},
  13038. {"/a.c", StatusCode::OK_200},
  13039. };
  13040. for (const auto &x : cases) {
  13041. auto res = cli.Get(x.path);
  13042. ASSERT_TRUE(res) << x.path;
  13043. EXPECT_EQ(x.status, res->status) << x.path;
  13044. }
  13045. }
  13046. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  13047. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  13048. // from exhausting the stack, so it must only constrain routes that actually
  13049. // run a regular expression. A literal route is matched by comparison and
  13050. // stays usable at any length.
  13051. Server svr;
  13052. const std::string pattern =
  13053. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  13054. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  13055. res.set_content("hit", "text/plain");
  13056. });
  13057. auto port = svr.bind_to_any_port(HOST);
  13058. std::thread t([&]() { svr.listen_after_bind(); });
  13059. auto se = detail::scope_exit([&] {
  13060. svr.stop();
  13061. t.join();
  13062. ASSERT_FALSE(svr.is_running());
  13063. });
  13064. svr.wait_until_ready();
  13065. Client cli(HOST, port);
  13066. auto res = cli.Get(pattern);
  13067. ASSERT_TRUE(res);
  13068. EXPECT_EQ(StatusCode::OK_200, res->status);
  13069. }
  13070. TEST(ParseUrlTest, VariousPatterns) {
  13071. {
  13072. detail::UrlComponents uc;
  13073. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  13074. EXPECT_EQ("http", uc.scheme);
  13075. EXPECT_EQ("example.com", uc.host);
  13076. EXPECT_EQ("8080", uc.port);
  13077. EXPECT_EQ("/path", uc.path);
  13078. EXPECT_EQ("?q=1", uc.query);
  13079. }
  13080. {
  13081. detail::UrlComponents uc;
  13082. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  13083. EXPECT_EQ("https", uc.scheme);
  13084. EXPECT_EQ("example.com", uc.host);
  13085. EXPECT_TRUE(uc.port.empty());
  13086. EXPECT_EQ("/path", uc.path);
  13087. }
  13088. {
  13089. detail::UrlComponents uc;
  13090. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  13091. EXPECT_EQ("::1", uc.host);
  13092. EXPECT_EQ("8080", uc.port);
  13093. EXPECT_EQ("/path", uc.path);
  13094. }
  13095. {
  13096. detail::UrlComponents uc;
  13097. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  13098. }
  13099. {
  13100. // Bytes after the IPv6 literal must be a delimiter, not folded into
  13101. // the path while the connection still targets the bracketed host.
  13102. detail::UrlComponents uc;
  13103. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  13104. }
  13105. {
  13106. detail::UrlComponents uc;
  13107. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  13108. }
  13109. {
  13110. detail::UrlComponents uc;
  13111. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  13112. EXPECT_EQ("::1", uc.host);
  13113. EXPECT_TRUE(uc.port.empty());
  13114. EXPECT_EQ("/path", uc.path);
  13115. }
  13116. {
  13117. detail::UrlComponents uc;
  13118. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  13119. EXPECT_TRUE(uc.scheme.empty());
  13120. EXPECT_EQ("example.com", uc.host);
  13121. EXPECT_EQ("/path", uc.path);
  13122. EXPECT_EQ("?q=1", uc.query);
  13123. }
  13124. {
  13125. detail::UrlComponents uc;
  13126. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  13127. EXPECT_TRUE(uc.host.empty());
  13128. EXPECT_EQ("/path", uc.path);
  13129. EXPECT_EQ("?q=1", uc.query);
  13130. }
  13131. {
  13132. detail::UrlComponents uc;
  13133. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  13134. EXPECT_EQ("example.com", uc.host);
  13135. EXPECT_EQ("8080", uc.port);
  13136. }
  13137. {
  13138. // Unix socket path — must not be parsed as host
  13139. detail::UrlComponents uc;
  13140. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  13141. EXPECT_TRUE(uc.host.empty());
  13142. }
  13143. {
  13144. detail::UrlComponents uc;
  13145. ASSERT_TRUE(detail::parse_url("", uc));
  13146. EXPECT_TRUE(uc.host.empty());
  13147. EXPECT_TRUE(uc.path.empty());
  13148. }
  13149. {
  13150. detail::UrlComponents uc;
  13151. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  13152. }
  13153. {
  13154. detail::UrlComponents uc;
  13155. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  13156. }
  13157. {
  13158. // Accepted by parse_url; callers restrict to http/https
  13159. detail::UrlComponents uc;
  13160. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  13161. EXPECT_EQ("ftp", uc.scheme);
  13162. }
  13163. {
  13164. detail::UrlComponents uc;
  13165. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  13166. }
  13167. {
  13168. detail::UrlComponents uc;
  13169. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  13170. }
  13171. }
  13172. TEST(ParseUrlTest, FragmentHandling) {
  13173. {
  13174. detail::UrlComponents uc;
  13175. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  13176. EXPECT_EQ("/path", uc.path);
  13177. EXPECT_TRUE(uc.query.empty());
  13178. }
  13179. {
  13180. detail::UrlComponents uc;
  13181. ASSERT_TRUE(detail::parse_url("#frag", uc));
  13182. EXPECT_TRUE(uc.path.empty());
  13183. EXPECT_TRUE(uc.query.empty());
  13184. }
  13185. }
  13186. TEST(ParseUrlTest, UserinfoHandling) {
  13187. // Userinfo with @ but no colon — host includes @
  13188. detail::UrlComponents uc;
  13189. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  13190. EXPECT_EQ("user@host.com", uc.host);
  13191. EXPECT_EQ("/path", uc.path);
  13192. }
  13193. TEST(ParseUrlTest, IPv6EdgeCases) {
  13194. {
  13195. detail::UrlComponents uc;
  13196. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  13197. EXPECT_TRUE(uc.scheme.empty());
  13198. EXPECT_EQ("::1", uc.host);
  13199. EXPECT_EQ("8080", uc.port);
  13200. }
  13201. {
  13202. // Zone ID '%25' is not in [a-fA-F0-9:]
  13203. detail::UrlComponents uc;
  13204. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  13205. }
  13206. }
  13207. TEST(ParseUrlTest, SchemeEdgeCases) {
  13208. {
  13209. detail::UrlComponents uc;
  13210. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  13211. }
  13212. {
  13213. detail::UrlComponents uc;
  13214. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  13215. }
  13216. {
  13217. detail::UrlComponents uc;
  13218. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  13219. }
  13220. }
  13221. TEST(ParseUrlTest, PortEdgeCases) {
  13222. {
  13223. detail::UrlComponents uc;
  13224. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  13225. EXPECT_TRUE(uc.port.empty());
  13226. EXPECT_EQ("/path", uc.path);
  13227. }
  13228. {
  13229. // parse_url accepts any port string; validation is done by parse_port
  13230. detail::UrlComponents uc;
  13231. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  13232. EXPECT_EQ("abc", uc.port);
  13233. }
  13234. }
  13235. TEST(ParseUrlTest, WebSocketPatterns) {
  13236. {
  13237. detail::UrlComponents uc;
  13238. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  13239. EXPECT_EQ("ws", uc.scheme);
  13240. EXPECT_EQ("echo.example.com", uc.host);
  13241. EXPECT_EQ("8080", uc.port);
  13242. EXPECT_EQ("/ws", uc.path);
  13243. }
  13244. {
  13245. detail::UrlComponents uc;
  13246. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  13247. EXPECT_EQ("wss", uc.scheme);
  13248. EXPECT_EQ("echo.example.com", uc.host);
  13249. EXPECT_TRUE(uc.port.empty());
  13250. EXPECT_EQ("/ws", uc.path);
  13251. }
  13252. }
  13253. TEST(ParseUrlTest, QueryOnly) {
  13254. detail::UrlComponents uc;
  13255. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  13256. EXPECT_TRUE(uc.host.empty());
  13257. EXPECT_TRUE(uc.path.empty());
  13258. EXPECT_EQ("?q=1&r=2", uc.query);
  13259. }
  13260. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  13261. detail::UrlComponents uc;
  13262. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  13263. EXPECT_TRUE(uc.scheme.empty());
  13264. EXPECT_EQ("example.com", uc.host);
  13265. EXPECT_EQ("443", uc.port);
  13266. EXPECT_EQ("/path", uc.path);
  13267. }
  13268. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  13269. // If ipv6 regex working, regex match codepath is taken.
  13270. // else port will default to 80 in Client impl
  13271. int clientImplMagicPort = 80;
  13272. int port = 4321;
  13273. // above ports must be different to avoid false negative
  13274. EXPECT_NE(clientImplMagicPort, port);
  13275. std::string ipV6TestURL = "http://[ff06::c3]";
  13276. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  13277. CLIENT_PRIVATE_KEY_FILE);
  13278. EXPECT_EQ(cli.port(), port);
  13279. }
  13280. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  13281. auto file_path = "./www/dir/index.html";
  13282. auto dir_path = "./www/dir";
  13283. detail::FileStat stat_file(file_path);
  13284. EXPECT_TRUE(stat_file.is_file());
  13285. EXPECT_FALSE(stat_file.is_dir());
  13286. detail::FileStat stat_dir(dir_path);
  13287. EXPECT_FALSE(stat_dir.is_file());
  13288. EXPECT_TRUE(stat_dir.is_dir());
  13289. }
  13290. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  13291. // IPv4 with default HTTP port (80)
  13292. EXPECT_EQ("example.com",
  13293. detail::make_host_and_port_string("example.com", 80, false));
  13294. // IPv4 with default HTTPS port (443)
  13295. EXPECT_EQ("example.com",
  13296. detail::make_host_and_port_string("example.com", 443, true));
  13297. // IPv4 with non-default HTTP port
  13298. EXPECT_EQ("example.com:8080",
  13299. detail::make_host_and_port_string("example.com", 8080, false));
  13300. // IPv4 with non-default HTTPS port
  13301. EXPECT_EQ("example.com:8443",
  13302. detail::make_host_and_port_string("example.com", 8443, true));
  13303. // IPv6 with default HTTP port (80)
  13304. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  13305. // IPv6 with default HTTPS port (443)
  13306. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  13307. // IPv6 with non-default HTTP port
  13308. EXPECT_EQ("[::1]:8080",
  13309. detail::make_host_and_port_string("::1", 8080, false));
  13310. // IPv6 with non-default HTTPS port
  13311. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  13312. // IPv6 full address with default port
  13313. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  13314. detail::make_host_and_port_string(
  13315. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  13316. // IPv6 full address with non-default port
  13317. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  13318. detail::make_host_and_port_string(
  13319. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  13320. // IPv6 localhost with non-default port
  13321. EXPECT_EQ("[::1]:3000",
  13322. detail::make_host_and_port_string("::1", 3000, false));
  13323. // IPv6 with zone ID (link-local address) with default port
  13324. EXPECT_EQ("[fe80::1%eth0]",
  13325. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  13326. // IPv6 with zone ID (link-local address) with non-default port
  13327. EXPECT_EQ("[fe80::1%eth0]:8080",
  13328. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  13329. // Edge case: Port 443 with is_ssl=false (should add port)
  13330. EXPECT_EQ("example.com:443",
  13331. detail::make_host_and_port_string("example.com", 443, false));
  13332. // Edge case: Port 80 with is_ssl=true (should add port)
  13333. EXPECT_EQ("example.com:80",
  13334. detail::make_host_and_port_string("example.com", 80, true));
  13335. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  13336. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  13337. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  13338. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  13339. // Security fix: Already bracketed IPv6 should not get double brackets
  13340. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  13341. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  13342. EXPECT_EQ("[::1]:8080",
  13343. detail::make_host_and_port_string("[::1]", 8080, false));
  13344. EXPECT_EQ("[2001:db8::1]:8080",
  13345. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  13346. EXPECT_EQ("[fe80::1%eth0]",
  13347. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  13348. EXPECT_EQ("[fe80::1%eth0]:8080",
  13349. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  13350. // Edge case: Empty host (should return as-is)
  13351. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  13352. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  13353. // This is a known limitation but shouldn't crash
  13354. EXPECT_EQ("[host:name]",
  13355. detail::make_host_and_port_string("host:name", 80, false));
  13356. // Port number edge cases (no validation, but should not crash)
  13357. EXPECT_EQ("example.com:0",
  13358. detail::make_host_and_port_string("example.com", 0, false));
  13359. EXPECT_EQ("example.com:-1",
  13360. detail::make_host_and_port_string("example.com", -1, false));
  13361. EXPECT_EQ("example.com:65535",
  13362. detail::make_host_and_port_string("example.com", 65535, false));
  13363. EXPECT_EQ("example.com:65536",
  13364. detail::make_host_and_port_string("example.com", 65536, false));
  13365. }
  13366. #ifdef CPPHTTPLIB_SSL_ENABLED
  13367. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  13368. httplib::SSLClient cli("roblox.com", 443);
  13369. cli.set_follow_location(true);
  13370. auto res = cli.Get("/");
  13371. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13372. EXPECT_EQ(StatusCode::OK_200, res->status);
  13373. }
  13374. #endif
  13375. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  13376. Server svr;
  13377. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  13378. EXPECT_EQ(res.status, 400);
  13379. });
  13380. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13381. auto se = detail::scope_exit([&] {
  13382. svr.stop();
  13383. thread.join();
  13384. ASSERT_FALSE(svr.is_running());
  13385. });
  13386. svr.wait_until_ready();
  13387. Client cli(HOST, PORT);
  13388. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  13389. }
  13390. TEST(InvalidHeaderCharsTest, is_field_name) {
  13391. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  13392. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  13393. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  13394. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  13395. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  13396. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  13397. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  13398. EXPECT_FALSE(detail::fields::is_field_name(""));
  13399. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  13400. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  13401. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  13402. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  13403. }
  13404. TEST(InvalidHeaderCharsTest, is_field_value) {
  13405. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  13406. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  13407. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  13408. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  13409. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  13410. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  13411. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  13412. EXPECT_TRUE(detail::fields::is_field_value(""));
  13413. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  13414. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  13415. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  13416. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  13417. EXPECT_TRUE(detail::fields::is_field_value("0"));
  13418. }
  13419. TEST(InvalidHeaderCharsTest, OnServer) {
  13420. Server svr;
  13421. svr.Get("/test_name", [&](const Request &req, Response &res) {
  13422. std::string header = "Not Set";
  13423. if (req.has_param("header")) { header = req.get_param_value("header"); }
  13424. res.set_header(header, "value");
  13425. res.set_content("Page Content Page Content", "text/plain");
  13426. });
  13427. svr.Get("/test_value", [&](const Request &req, Response &res) {
  13428. std::string header = "Not Set";
  13429. if (req.has_param("header")) { header = req.get_param_value("header"); }
  13430. res.set_header("X-Test", header);
  13431. res.set_content("Page Content Page Content", "text/plain");
  13432. });
  13433. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13434. auto se = detail::scope_exit([&] {
  13435. svr.stop();
  13436. thread.join();
  13437. ASSERT_FALSE(svr.is_running());
  13438. });
  13439. svr.wait_until_ready();
  13440. Client cli(HOST, PORT);
  13441. {
  13442. auto res = cli.Get(
  13443. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  13444. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13445. EXPECT_EQ("Page Content Page Content", res->body);
  13446. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  13447. }
  13448. {
  13449. auto res = cli.Get(
  13450. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  13451. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13452. EXPECT_EQ("Page Content Page Content", res->body);
  13453. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  13454. }
  13455. }
  13456. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  13457. auto handled = false;
  13458. Server svr;
  13459. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  13460. thread t = thread([&] { svr.listen(HOST, PORT); });
  13461. auto se = detail::scope_exit([&] {
  13462. svr.stop();
  13463. t.join();
  13464. ASSERT_FALSE(svr.is_running());
  13465. ASSERT_FALSE(handled);
  13466. });
  13467. svr.wait_until_ready();
  13468. auto req = "POST /test HTTP/1.1\r\n"
  13469. "Content-Length: x\r\n"
  13470. "\r\n";
  13471. std::string response;
  13472. ASSERT_TRUE(send_request(1, req, &response));
  13473. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  13474. response.substr(0, response.find("\r\n")));
  13475. }
  13476. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  13477. // case-insensitive, and a server that receives a 100-continue expectation in
  13478. // an HTTP/1.0 request MUST ignore it.
  13479. static void probe_expect(int port, const std::string &req, bool *got_100) {
  13480. std::string response;
  13481. ASSERT_TRUE(send_request(1, req, &response, port));
  13482. *got_100 = response.find("100 Continue") != std::string::npos;
  13483. }
  13484. class ExpectTokenTest : public ::testing::Test {
  13485. protected:
  13486. void SetUp() override {
  13487. svr_.Post("/p", [](const Request &, Response &res) {
  13488. res.set_content("ok", "text/plain");
  13489. });
  13490. port_ = svr_.bind_to_any_port(HOST);
  13491. thread_ = thread([&]() { svr_.listen_after_bind(); });
  13492. svr_.wait_until_ready();
  13493. }
  13494. void TearDown() override {
  13495. svr_.stop();
  13496. if (thread_.joinable()) { thread_.join(); }
  13497. }
  13498. std::string request(const char *version, const char *expect_value) const {
  13499. return std::string("POST /p ") + version +
  13500. "\r\n"
  13501. "Host: localhost\r\n"
  13502. "Content-Length: 2\r\n"
  13503. "Connection: close\r\n"
  13504. "Expect: " +
  13505. expect_value +
  13506. "\r\n"
  13507. "\r\n"
  13508. "hi";
  13509. }
  13510. Server svr_;
  13511. int port_ = 0;
  13512. thread thread_;
  13513. };
  13514. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  13515. bool got_100 = false;
  13516. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  13517. EXPECT_TRUE(got_100);
  13518. }
  13519. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  13520. bool got_100 = true;
  13521. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  13522. EXPECT_FALSE(got_100);
  13523. }
  13524. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  13525. bool got_100 = false;
  13526. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  13527. EXPECT_TRUE(got_100);
  13528. }
  13529. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  13530. bool got_100 = false;
  13531. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  13532. EXPECT_TRUE(got_100);
  13533. }
  13534. #ifndef _WIN32
  13535. TEST(Expect100ContinueTest, ServerClosesConnection) {
  13536. static constexpr char reject[] = "Unauthorized";
  13537. static constexpr char accept[] = "Upload accepted";
  13538. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  13539. Server svr;
  13540. svr.set_expect_100_continue_handler(
  13541. [](const Request & /*req*/, Response &res) {
  13542. res.status = StatusCode::Unauthorized_401;
  13543. res.set_content(reject, "text/plain");
  13544. return res.status;
  13545. });
  13546. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  13547. res.set_content(accept, "text/plain");
  13548. });
  13549. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13550. auto se = detail::scope_exit([&] {
  13551. svr.stop();
  13552. thread.join();
  13553. ASSERT_FALSE(svr.is_running());
  13554. });
  13555. svr.wait_until_ready();
  13556. {
  13557. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  13558. curl_easy_init(), &curl_easy_cleanup};
  13559. ASSERT_NE(curl, nullptr);
  13560. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  13561. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  13562. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  13563. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  13564. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  13565. &curl_slist_free_all};
  13566. ASSERT_NE(list, nullptr);
  13567. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  13568. struct read_data {
  13569. size_t read_size;
  13570. size_t total_size;
  13571. } data = {0, total_size};
  13572. using read_callback_t =
  13573. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  13574. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  13575. void *userdata) -> size_t {
  13576. read_data *d = (read_data *)userdata;
  13577. if (!userdata || d->read_size >= d->total_size) { return 0; }
  13578. std::fill_n(ptr, size * nmemb, 'A');
  13579. d->read_size += size * nmemb;
  13580. return size * nmemb;
  13581. };
  13582. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  13583. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  13584. std::vector<char> buffer;
  13585. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  13586. using write_callback_t =
  13587. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  13588. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  13589. void *userdata) -> size_t {
  13590. std::vector<char> *buf = (std::vector<char> *)userdata;
  13591. buf->reserve(buf->size() + size * nmemb + 1);
  13592. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  13593. return size * nmemb;
  13594. };
  13595. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  13596. {
  13597. const auto res = curl_easy_perform(curl.get());
  13598. ASSERT_EQ(res, CURLE_OK);
  13599. }
  13600. {
  13601. auto response_code = long{};
  13602. const auto res =
  13603. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  13604. ASSERT_EQ(res, CURLE_OK);
  13605. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  13606. }
  13607. {
  13608. auto dl = curl_off_t{};
  13609. const auto res =
  13610. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  13611. ASSERT_EQ(res, CURLE_OK);
  13612. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  13613. }
  13614. {
  13615. buffer.push_back('\0');
  13616. ASSERT_STRCASEEQ(buffer.data(), reject);
  13617. }
  13618. }
  13619. }
  13620. #endif
  13621. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  13622. // Regression test for #2458.
  13623. //
  13624. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  13625. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  13626. // ticket can make the client socket spuriously readable during the
  13627. // 100-continue wait. If the readiness is mistaken for an incoming response,
  13628. // the client withholds the body and then blocks reading a response that never
  13629. // comes, failing with `Failed to read connection`.
  13630. //
  13631. // A correct client (like curl) sends the body once no `100 Continue` arrives
  13632. // within the timeout. This raw OpenSSL server deliberately never sends
  13633. // `100 Continue`; the client must still deliver the body and receive 200.
  13634. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  13635. signal(SIGPIPE, SIG_IGN);
  13636. const auto port = PORT + 4;
  13637. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13638. ASSERT_NE(srv, INVALID_SOCKET);
  13639. int opt = 1;
  13640. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  13641. sockaddr_in addr{};
  13642. addr.sin_family = AF_INET;
  13643. addr.sin_port = htons(static_cast<uint16_t>(port));
  13644. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13645. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  13646. ASSERT_EQ(0, ::listen(srv, 1));
  13647. std::atomic<size_t> server_body_bytes{0};
  13648. auto server_thread = std::thread([&] {
  13649. sockaddr_in cli_addr{};
  13650. socklen_t cli_len = sizeof(cli_addr);
  13651. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13652. if (cli == INVALID_SOCKET) { return; }
  13653. // Bound the lifetime of the server side so a buggy client (which never
  13654. // sends the body) cannot make this thread block forever on join.
  13655. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  13656. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  13657. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  13658. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  13659. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  13660. SSL *ssl = SSL_new(ctx);
  13661. SSL_set_fd(ssl, static_cast<int>(cli));
  13662. if (SSL_accept(ssl) > 0) {
  13663. // Read the request headers. Reading here also flushes the TLS 1.3
  13664. // session tickets to the client. Deliberately do NOT send
  13665. // `100 Continue`.
  13666. std::string buf;
  13667. char tmp[1024];
  13668. while (buf.find("\r\n\r\n") == std::string::npos) {
  13669. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  13670. if (n <= 0) { break; }
  13671. buf.append(tmp, static_cast<size_t>(n));
  13672. }
  13673. // A correct client sends the body now; count what arrives.
  13674. auto pos = buf.find("\r\n\r\n");
  13675. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  13676. while (body < 4096) {
  13677. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  13678. if (n <= 0) { break; }
  13679. body += static_cast<size_t>(n);
  13680. }
  13681. server_body_bytes = body;
  13682. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  13683. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  13684. SSL_shutdown(ssl);
  13685. }
  13686. SSL_free(ssl);
  13687. detail::close_socket(cli);
  13688. SSL_CTX_free(ctx);
  13689. });
  13690. auto se = detail::scope_exit([&] {
  13691. server_thread.join();
  13692. detail::close_socket(srv);
  13693. });
  13694. SSLClient cli("127.0.0.1", port);
  13695. cli.enable_server_certificate_verification(false);
  13696. cli.set_connection_timeout(5, 0);
  13697. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  13698. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  13699. std::string body(4096, 'A');
  13700. auto res = cli.Put("/api/test", body, "application/json");
  13701. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  13702. EXPECT_EQ(StatusCode::OK_200, res->status);
  13703. EXPECT_EQ(body.size(), server_body_bytes.load());
  13704. }
  13705. #endif
  13706. template <typename S, typename C>
  13707. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  13708. svr.Get("/stream", [&](const Request &, Response &res) {
  13709. auto data = new std::string("01234567890123456789");
  13710. res.set_content_provider(
  13711. data->size(), "text/plain",
  13712. [&, data](size_t offset, size_t length, DataSink &sink) {
  13713. const size_t DATA_CHUNK_SIZE = 4;
  13714. const auto &d = *data;
  13715. std::this_thread::sleep_for(std::chrono::seconds(1));
  13716. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  13717. return true;
  13718. },
  13719. [data](bool success) {
  13720. EXPECT_FALSE(success);
  13721. delete data;
  13722. });
  13723. });
  13724. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  13725. auto i = new size_t(0);
  13726. res.set_content_provider(
  13727. "text/plain",
  13728. [i](size_t, DataSink &sink) {
  13729. if (*i < 5) {
  13730. std::this_thread::sleep_for(std::chrono::seconds(1));
  13731. sink.write("abcd", 4);
  13732. (*i)++;
  13733. } else {
  13734. sink.done();
  13735. }
  13736. return true;
  13737. },
  13738. [i](bool success) {
  13739. EXPECT_FALSE(success);
  13740. delete i;
  13741. });
  13742. });
  13743. svr.Get("/chunked", [&](const Request &, Response &res) {
  13744. auto i = new size_t(0);
  13745. res.set_chunked_content_provider(
  13746. "text/plain",
  13747. [i](size_t, DataSink &sink) {
  13748. if (*i < 5) {
  13749. std::this_thread::sleep_for(std::chrono::seconds(1));
  13750. sink.os << "abcd";
  13751. (*i)++;
  13752. } else {
  13753. sink.done();
  13754. }
  13755. return true;
  13756. },
  13757. [i](bool success) {
  13758. EXPECT_FALSE(success);
  13759. delete i;
  13760. });
  13761. });
  13762. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  13763. auto se = detail::scope_exit([&] {
  13764. svr.stop();
  13765. listen_thread.join();
  13766. ASSERT_FALSE(svr.is_running());
  13767. });
  13768. svr.wait_until_ready();
  13769. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  13770. {
  13771. auto start = std::chrono::steady_clock::now();
  13772. auto res = cli.Get("/stream");
  13773. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  13774. std::chrono::steady_clock::now() - start)
  13775. .count();
  13776. ASSERT_FALSE(res);
  13777. EXPECT_EQ(Error::Read, res.error());
  13778. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  13779. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  13780. }
  13781. {
  13782. auto start = std::chrono::steady_clock::now();
  13783. auto res = cli.Get("/stream_without_length");
  13784. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  13785. std::chrono::steady_clock::now() - start)
  13786. .count();
  13787. ASSERT_FALSE(res);
  13788. EXPECT_EQ(Error::Read, res.error());
  13789. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  13790. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  13791. }
  13792. {
  13793. auto start = std::chrono::steady_clock::now();
  13794. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  13795. EXPECT_EQ("abcd", string(data, data_length));
  13796. return true;
  13797. });
  13798. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  13799. std::chrono::steady_clock::now() - start)
  13800. .count();
  13801. ASSERT_FALSE(res);
  13802. EXPECT_EQ(Error::Read, res.error());
  13803. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  13804. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  13805. }
  13806. }
  13807. TEST(MaxTimeoutTest, ContentStream) {
  13808. time_t timeout = 2000;
  13809. time_t threshold = 200;
  13810. Server svr;
  13811. Client cli("localhost", PORT);
  13812. max_timeout_test(svr, cli, timeout, threshold);
  13813. }
  13814. #ifdef CPPHTTPLIB_SSL_ENABLED
  13815. TEST(MaxTimeoutTest, ContentStreamSSL) {
  13816. time_t timeout = 2000;
  13817. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  13818. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13819. SSLClient cli("localhost", PORT);
  13820. cli.enable_server_certificate_verification(false);
  13821. max_timeout_test(svr, cli, timeout, threshold);
  13822. }
  13823. #endif
  13824. class EventDispatcher {
  13825. public:
  13826. EventDispatcher() {}
  13827. bool wait_event(DataSink *sink) {
  13828. unique_lock<mutex> lk(m_);
  13829. int id = id_;
  13830. // Wait with timeout to prevent hanging if client disconnects
  13831. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  13832. [&] { return cid_ == id; })) {
  13833. return false; // Timeout occurred
  13834. }
  13835. sink->write(message_.data(), message_.size());
  13836. return true;
  13837. }
  13838. void send_event(const string &message) {
  13839. lock_guard<mutex> lk(m_);
  13840. cid_ = id_++;
  13841. message_ = message;
  13842. cv_.notify_all();
  13843. }
  13844. private:
  13845. mutex m_;
  13846. condition_variable cv_;
  13847. atomic_int id_{0};
  13848. atomic_int cid_{-1};
  13849. string message_;
  13850. };
  13851. TEST(ClientInThreadTest, Issue2068) {
  13852. EventDispatcher ed;
  13853. Server svr;
  13854. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  13855. res.set_chunked_content_provider("text/event-stream",
  13856. [&](size_t /*offset*/, DataSink &sink) {
  13857. return ed.wait_event(&sink);
  13858. });
  13859. });
  13860. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  13861. svr.wait_until_ready();
  13862. thread event_thread([&] {
  13863. int id = 0;
  13864. while (svr.is_running()) {
  13865. this_thread::sleep_for(chrono::milliseconds(500));
  13866. std::stringstream ss;
  13867. ss << "data: " << id << "\n\n";
  13868. ed.send_event(ss.str());
  13869. id++;
  13870. }
  13871. });
  13872. auto se = detail::scope_exit([&] {
  13873. svr.stop();
  13874. listen_thread.join();
  13875. event_thread.join();
  13876. ASSERT_FALSE(svr.is_running());
  13877. });
  13878. {
  13879. auto client = detail::make_unique<Client>(HOST, PORT);
  13880. client->set_read_timeout(std::chrono::minutes(10));
  13881. std::atomic<bool> stop{false};
  13882. std::thread t([&] {
  13883. client->Get("/event1",
  13884. [&](const char *, size_t) -> bool { return !stop; });
  13885. });
  13886. std::this_thread::sleep_for(std::chrono::seconds(2));
  13887. stop = true;
  13888. client->stop();
  13889. t.join();
  13890. // Reset client after thread has finished
  13891. client.reset();
  13892. }
  13893. }
  13894. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  13895. auto handled = false;
  13896. Server svr;
  13897. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  13898. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13899. auto se = detail::scope_exit([&] {
  13900. svr.stop();
  13901. t.join();
  13902. ASSERT_FALSE(svr.is_running());
  13903. ASSERT_FALSE(handled);
  13904. });
  13905. svr.wait_until_ready();
  13906. // Two Content-Length headers with different values — must be rejected
  13907. auto req = "POST /test HTTP/1.1\r\n"
  13908. "Content-Length: 5\r\n"
  13909. "Content-Length: 10\r\n"
  13910. "\r\n"
  13911. "hello";
  13912. std::string response;
  13913. ASSERT_TRUE(send_request(1, req, &response));
  13914. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  13915. response.substr(0, response.find("\r\n")));
  13916. }
  13917. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  13918. auto handled = false;
  13919. Server svr;
  13920. svr.Post("/test", [&](const Request &, Response &res) {
  13921. handled = true;
  13922. res.set_content("ok", "text/plain");
  13923. });
  13924. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13925. auto se = detail::scope_exit([&] {
  13926. svr.stop();
  13927. t.join();
  13928. ASSERT_FALSE(svr.is_running());
  13929. ASSERT_TRUE(handled);
  13930. });
  13931. svr.wait_until_ready();
  13932. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  13933. auto req = "POST /test HTTP/1.1\r\n"
  13934. "Content-Length: 5\r\n"
  13935. "Content-Length: 5\r\n"
  13936. "\r\n"
  13937. "hello";
  13938. std::string response;
  13939. ASSERT_TRUE(send_request(1, req, &response));
  13940. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  13941. }
  13942. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  13943. Server svr;
  13944. svr.Get("/", [](const Request &req, Response &res) {
  13945. EXPECT_EQ(2U, req.trailers.size());
  13946. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  13947. // Denied
  13948. EXPECT_FALSE(req.has_trailer("Content-Length"));
  13949. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  13950. // Accepted
  13951. EXPECT_TRUE(req.has_trailer("X-Hello"));
  13952. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  13953. EXPECT_TRUE(req.has_trailer("X-World"));
  13954. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  13955. res.set_content("ok", "text/plain");
  13956. });
  13957. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13958. auto se = detail::scope_exit([&] {
  13959. svr.stop();
  13960. t.join();
  13961. ASSERT_FALSE(svr.is_running());
  13962. });
  13963. svr.wait_until_ready();
  13964. const std::string req = "GET / HTTP/1.1\r\n"
  13965. "Transfer-Encoding: chunked\r\n"
  13966. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  13967. "\r\n"
  13968. "0\r\n"
  13969. "Content-Length: 10\r\n"
  13970. "Host: internal.local\r\n"
  13971. "Content-Type: malicious/content\r\n"
  13972. "Cookie: any\r\n"
  13973. "Set-Cookie: any\r\n"
  13974. "X-Forwarded-For: attacker.com\r\n"
  13975. "X-Real-Ip: 1.1.1.1\r\n"
  13976. "X-Hello: hello\r\n"
  13977. "X-World: world\r\n"
  13978. "\r\n";
  13979. std::string res;
  13980. ASSERT_TRUE(send_request(1, req, &res));
  13981. }
  13982. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  13983. // several field lines, and the combined value is what has to be parsed. A
  13984. // Trailer field split across lines therefore declares every name it lists;
  13985. // reading only the first line silently drops the trailers the later lines
  13986. // declare. The prohibited-trailer filter still applies to every line.
  13987. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  13988. Server svr;
  13989. size_t observed_trailer_count = 0;
  13990. std::string observed_hello;
  13991. std::string observed_world;
  13992. bool observed_content_length = true;
  13993. svr.Get("/", [&](const Request &req, Response &res) {
  13994. observed_trailer_count = req.trailers.size();
  13995. observed_hello = req.get_trailer_value("X-Hello");
  13996. observed_world = req.get_trailer_value("X-World");
  13997. observed_content_length = req.has_trailer("Content-Length");
  13998. res.set_content("ok", "text/plain");
  13999. });
  14000. auto port = svr.bind_to_any_port(HOST);
  14001. thread t = thread([&]() { svr.listen_after_bind(); });
  14002. auto se = detail::scope_exit([&] {
  14003. svr.stop();
  14004. t.join();
  14005. ASSERT_FALSE(svr.is_running());
  14006. });
  14007. svr.wait_until_ready();
  14008. const std::string req = "GET / HTTP/1.1\r\n"
  14009. "Transfer-Encoding: chunked\r\n"
  14010. "Trailer: X-Hello\r\n"
  14011. "Trailer: X-World, Content-Length\r\n"
  14012. "\r\n"
  14013. "0\r\n"
  14014. "X-Hello: hello\r\n"
  14015. "X-World: world\r\n"
  14016. "Content-Length: 10\r\n"
  14017. "\r\n";
  14018. std::string res;
  14019. ASSERT_TRUE(send_request(1, req, &res, port));
  14020. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  14021. // Accepted: both field lines contribute to the declared set
  14022. EXPECT_EQ(2U, observed_trailer_count);
  14023. EXPECT_EQ(observed_hello, "hello");
  14024. EXPECT_EQ(observed_world, "world");
  14025. // Denied: a prohibited name stays prohibited on a later field line
  14026. EXPECT_FALSE(observed_content_length);
  14027. }
  14028. // A direct client that is not listed in trusted_proxies must not be able to
  14029. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  14030. // the peer address on the actual TCP connection determines whether the
  14031. // header is honored.
  14032. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  14033. Server svr;
  14034. // Deliberately does NOT include the loopback address the test client
  14035. // actually connects from, so the direct connection is not a trusted proxy.
  14036. svr.set_trusted_proxies({"203.0.113.66"});
  14037. std::string observed_remote_addr;
  14038. svr.Get("/ip", [&](const Request &req, Response &res) {
  14039. observed_remote_addr = req.remote_addr;
  14040. res.set_content("ok", "text/plain");
  14041. });
  14042. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14043. auto se = detail::scope_exit([&] {
  14044. svr.stop();
  14045. t.join();
  14046. ASSERT_FALSE(svr.is_running());
  14047. });
  14048. svr.wait_until_ready();
  14049. Client cli(HOST, PORT);
  14050. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  14051. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14052. EXPECT_EQ(StatusCode::OK_200, res->status);
  14053. // The connecting peer is not a trusted proxy, so the spoofed header must be
  14054. // ignored entirely and the real connection-level address retained.
  14055. EXPECT_TRUE(observed_remote_addr == "::1" ||
  14056. observed_remote_addr == "127.0.0.1");
  14057. }
  14058. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  14059. Server svr;
  14060. std::string observed_remote_addr;
  14061. std::string observed_xff;
  14062. svr.Get("/ip", [&](const Request &req, Response &res) {
  14063. observed_remote_addr = req.remote_addr;
  14064. observed_xff = req.get_header_value("X-Forwarded-For");
  14065. res.set_content("ok", "text/plain");
  14066. });
  14067. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14068. auto se = detail::scope_exit([&] {
  14069. svr.stop();
  14070. t.join();
  14071. ASSERT_FALSE(svr.is_running());
  14072. });
  14073. svr.wait_until_ready();
  14074. Client cli(HOST, PORT);
  14075. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  14076. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14077. EXPECT_EQ(StatusCode::OK_200, res->status);
  14078. EXPECT_EQ(observed_xff, "203.0.113.66");
  14079. EXPECT_TRUE(observed_remote_addr == "::1" ||
  14080. observed_remote_addr == "127.0.0.1");
  14081. }
  14082. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  14083. Server svr;
  14084. svr.set_trusted_proxies({"203.0.113.66"});
  14085. std::string observed_remote_addr;
  14086. std::string observed_xff;
  14087. svr.Get("/ip", [&](const Request &req, Response &res) {
  14088. observed_remote_addr = req.remote_addr;
  14089. observed_xff = req.get_header_value("X-Forwarded-For");
  14090. res.set_content("ok", "text/plain");
  14091. });
  14092. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14093. auto se = detail::scope_exit([&] {
  14094. svr.stop();
  14095. t.join();
  14096. ASSERT_FALSE(svr.is_running());
  14097. });
  14098. svr.wait_until_ready();
  14099. Client cli(HOST, PORT);
  14100. auto res = cli.Get("/ip");
  14101. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14102. EXPECT_EQ(StatusCode::OK_200, res->status);
  14103. EXPECT_EQ(observed_xff, "");
  14104. EXPECT_TRUE(observed_remote_addr == "::1" ||
  14105. observed_remote_addr == "127.0.0.1");
  14106. }
  14107. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  14108. Server svr;
  14109. // Include the loopback address the test client actually connects from, so
  14110. // the direct connection itself is recognized as the trusted proxy hop.
  14111. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  14112. std::string observed_remote_addr;
  14113. std::string observed_xff;
  14114. svr.Get("/ip", [&](const Request &req, Response &res) {
  14115. observed_remote_addr = req.remote_addr;
  14116. observed_xff = req.get_header_value("X-Forwarded-For");
  14117. res.set_content("ok", "text/plain");
  14118. });
  14119. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14120. auto se = detail::scope_exit([&] {
  14121. svr.stop();
  14122. t.join();
  14123. ASSERT_FALSE(svr.is_running());
  14124. });
  14125. svr.wait_until_ready();
  14126. Client cli(HOST, PORT);
  14127. auto res = cli.Get(
  14128. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  14129. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14130. EXPECT_EQ(StatusCode::OK_200, res->status);
  14131. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  14132. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  14133. }
  14134. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  14135. Server svr;
  14136. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  14137. std::string observed_remote_addr;
  14138. std::string observed_xff;
  14139. svr.Get("/ip", [&](const Request &req, Response &res) {
  14140. observed_remote_addr = req.remote_addr;
  14141. observed_xff = req.get_header_value("X-Forwarded-For");
  14142. res.set_content("ok", "text/plain");
  14143. });
  14144. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14145. auto se = detail::scope_exit([&] {
  14146. svr.stop();
  14147. t.join();
  14148. ASSERT_FALSE(svr.is_running());
  14149. });
  14150. svr.wait_until_ready();
  14151. Client cli(HOST, PORT);
  14152. auto res = cli.Get(
  14153. "/ip",
  14154. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  14155. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14156. EXPECT_EQ(StatusCode::OK_200, res->status);
  14157. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  14158. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  14159. }
  14160. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  14161. Server svr;
  14162. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  14163. std::string observed_remote_addr;
  14164. std::string observed_xff;
  14165. svr.Get("/ip", [&](const Request &req, Response &res) {
  14166. observed_remote_addr = req.remote_addr;
  14167. observed_xff = req.get_header_value("X-Forwarded-For");
  14168. res.set_content("ok", "text/plain");
  14169. });
  14170. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14171. auto se = detail::scope_exit([&] {
  14172. svr.stop();
  14173. t.join();
  14174. ASSERT_FALSE(svr.is_running());
  14175. });
  14176. svr.wait_until_ready();
  14177. Client cli(HOST, PORT);
  14178. auto res = cli.Get(
  14179. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  14180. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14181. EXPECT_EQ(StatusCode::OK_200, res->status);
  14182. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  14183. // by the closest hop) is used. The leftmost entry is fully client-controlled
  14184. // and must not be selected.
  14185. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  14186. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  14187. }
  14188. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  14189. Server svr;
  14190. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  14191. std::string observed_remote_addr;
  14192. svr.Get("/ip", [&](const Request &req, Response &res) {
  14193. observed_remote_addr = req.remote_addr;
  14194. res.set_content("ok", "text/plain");
  14195. });
  14196. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14197. auto se = detail::scope_exit([&] {
  14198. svr.stop();
  14199. t.join();
  14200. ASSERT_FALSE(svr.is_running());
  14201. });
  14202. svr.wait_until_ready();
  14203. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  14204. // a forged address and the trusted proxy's own address; the forged value must
  14205. // not win over the address the trusted proxy actually recorded.
  14206. Client cli(HOST, PORT);
  14207. auto res = cli.Get(
  14208. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  14209. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14210. EXPECT_EQ(StatusCode::OK_200, res->status);
  14211. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  14212. }
  14213. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  14214. Server svr;
  14215. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  14216. std::string observed_remote_addr;
  14217. std::string observed_xff;
  14218. svr.Get("/ip", [&](const Request &req, Response &res) {
  14219. observed_remote_addr = req.remote_addr;
  14220. observed_xff = req.get_header_value("X-Forwarded-For");
  14221. res.set_content("ok", "text/plain");
  14222. });
  14223. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14224. auto se = detail::scope_exit([&] {
  14225. svr.stop();
  14226. t.join();
  14227. ASSERT_FALSE(svr.is_running());
  14228. });
  14229. svr.wait_until_ready();
  14230. Client cli(HOST, PORT);
  14231. auto res = cli.Get(
  14232. "/ip",
  14233. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  14234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14235. EXPECT_EQ(StatusCode::OK_200, res->status);
  14236. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  14237. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  14238. }
  14239. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  14240. Server svr;
  14241. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  14242. std::string observed_remote_addr;
  14243. std::string observed_xff;
  14244. svr.Get("/ip", [&](const Request &req, Response &res) {
  14245. observed_remote_addr = req.remote_addr;
  14246. observed_xff = req.get_header_value("X-Forwarded-For");
  14247. res.set_content("ok", "text/plain");
  14248. });
  14249. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14250. auto se = detail::scope_exit([&] {
  14251. svr.stop();
  14252. t.join();
  14253. ASSERT_FALSE(svr.is_running());
  14254. });
  14255. svr.wait_until_ready();
  14256. std::string raw_req =
  14257. "GET /ip HTTP/1.1\r\n"
  14258. "Host: localhost\r\n"
  14259. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  14260. "Connection: close\r\n"
  14261. "\r\n";
  14262. std::string out;
  14263. ASSERT_TRUE(send_request(5, raw_req, &out));
  14264. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  14265. // Header parser trims surrounding whitespace of the header value
  14266. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  14267. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  14268. }
  14269. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  14270. // one comma-joined value, in the order received. Proxies such as HAProxy append
  14271. // their own X-Forwarded-For as a separate field line rather than extending the
  14272. // one the client sent, so every occurrence has to be taken into account.
  14273. // Reading only the first one hands back the address the client chose.
  14274. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  14275. Server svr;
  14276. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  14277. std::string observed_remote_addr;
  14278. size_t observed_xff_count = 0;
  14279. svr.Get("/ip", [&](const Request &req, Response &res) {
  14280. observed_remote_addr = req.remote_addr;
  14281. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  14282. res.set_content("ok", "text/plain");
  14283. });
  14284. auto port = svr.bind_to_any_port(HOST);
  14285. thread t = thread([&]() { svr.listen_after_bind(); });
  14286. auto se = detail::scope_exit([&] {
  14287. svr.stop();
  14288. t.join();
  14289. ASSERT_FALSE(svr.is_running());
  14290. });
  14291. svr.wait_until_ready();
  14292. // The client supplies the first field line; the trusted proxy appends the
  14293. // address it observed as a second one.
  14294. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  14295. "Host: localhost\r\n"
  14296. "X-Forwarded-For: 1.2.3.4\r\n"
  14297. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  14298. "Connection: close\r\n"
  14299. "\r\n";
  14300. std::string out;
  14301. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  14302. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  14303. EXPECT_EQ(observed_xff_count, 2U);
  14304. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  14305. // The same chain spread over one field line per hop derives the same client
  14306. // address, i.e. the split and the comma-joined representations agree.
  14307. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  14308. "Host: localhost\r\n"
  14309. "X-Forwarded-For: 1.2.3.4\r\n"
  14310. "X-Forwarded-For: 198.51.100.23\r\n"
  14311. "X-Forwarded-For: 192.0.2.45\r\n"
  14312. "Connection: close\r\n"
  14313. "\r\n";
  14314. out.clear();
  14315. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  14316. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  14317. EXPECT_EQ(observed_xff_count, 3U);
  14318. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  14319. }
  14320. // An X-Forwarded-For header whose value parses to zero IP segments must not
  14321. // crash the server (it used to call front() on an empty vector inside
  14322. // get_client_ip). The connection-level remote address must be retained instead.
  14323. static void run_malformed_xff_test(const std::string &xff_value) {
  14324. Server svr;
  14325. svr.set_trusted_proxies({"192.0.2.45"});
  14326. std::string observed_remote_addr;
  14327. svr.Get("/ip", [&](const Request &req, Response &res) {
  14328. observed_remote_addr = req.remote_addr;
  14329. res.set_content("ok", "text/plain");
  14330. });
  14331. int port = 0;
  14332. thread t = thread([&]() {
  14333. port = svr.bind_to_any_port(HOST);
  14334. svr.listen_after_bind();
  14335. });
  14336. auto se = detail::scope_exit([&] {
  14337. svr.stop();
  14338. t.join();
  14339. ASSERT_FALSE(svr.is_running());
  14340. });
  14341. svr.wait_until_ready();
  14342. Client cli(HOST, port);
  14343. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  14344. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14345. EXPECT_EQ(StatusCode::OK_200, res->status);
  14346. EXPECT_TRUE(observed_remote_addr == "::1" ||
  14347. observed_remote_addr == "127.0.0.1");
  14348. }
  14349. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  14350. run_malformed_xff_test("");
  14351. }
  14352. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  14353. run_malformed_xff_test(",");
  14354. }
  14355. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  14356. run_malformed_xff_test(", , ,");
  14357. }
  14358. // The same rule applies to Accept: a request whose acceptable types are spread
  14359. // over several field lines must be negotiated against all of them.
  14360. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  14361. // case-insensitive connection options. Comparing the whole field value against
  14362. // one option misses a client that sends several of them, and misses every
  14363. // casing but the one written in the comparison.
  14364. //
  14365. // Sends req, reads the response, then reuses the same socket for a second
  14366. // request to find out whether the server kept the connection.
  14367. static void probe_connection_reuse(int port, const std::string &req,
  14368. bool *announced_close, bool *reusable) {
  14369. auto error = Error::Success;
  14370. auto sock = detail::create_client_socket(
  14371. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  14372. /*connection_timeout_sec=*/5, 0,
  14373. /*read_timeout_sec=*/1, 0,
  14374. /*write_timeout_sec=*/5, 0, std::string(), error);
  14375. ASSERT_NE(sock, INVALID_SOCKET);
  14376. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  14377. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  14378. "Host: localhost\r\n"
  14379. "Connection: close\r\n"
  14380. "\r\n";
  14381. std::string first_response;
  14382. std::string second_response;
  14383. detail::process_client_socket(
  14384. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  14385. [&](Stream &strm) {
  14386. if (strm.write(req.data(), req.size()) !=
  14387. static_cast<ssize_t>(req.size())) {
  14388. return false;
  14389. }
  14390. char buf[512];
  14391. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  14392. // Headers plus the two-byte body of the handler below
  14393. while (reader.getline()) {
  14394. first_response += reader.ptr();
  14395. if (first_response.find("ok") != std::string::npos) { break; }
  14396. }
  14397. if (strm.write(second.data(), second.size()) !=
  14398. static_cast<ssize_t>(second.size())) {
  14399. return true;
  14400. }
  14401. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  14402. while (reader2.getline()) {
  14403. second_response += reader2.ptr();
  14404. if (second_response.find("ok") != std::string::npos) { break; }
  14405. }
  14406. return true;
  14407. });
  14408. *announced_close =
  14409. first_response.find("Connection: close") != std::string::npos;
  14410. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  14411. }
  14412. class ConnectionTokenTest : public ::testing::Test {
  14413. protected:
  14414. void SetUp() override {
  14415. svr_.Get("/keepalive", [](const Request &, Response &res) {
  14416. res.set_content("ok", "text/plain");
  14417. });
  14418. port_ = svr_.bind_to_any_port(HOST);
  14419. thread_ = thread([&]() { svr_.listen_after_bind(); });
  14420. svr_.wait_until_ready();
  14421. }
  14422. void TearDown() override {
  14423. svr_.stop();
  14424. if (thread_.joinable()) { thread_.join(); }
  14425. }
  14426. Server svr_;
  14427. int port_ = 0;
  14428. thread thread_;
  14429. };
  14430. // "close" alongside another option still closes the connection, and the
  14431. // response says so rather than leaving the peer to discover it.
  14432. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  14433. bool announced_close = false;
  14434. bool reusable = true;
  14435. probe_connection_reuse(port_,
  14436. "GET /keepalive HTTP/1.1\r\n"
  14437. "Host: localhost\r\n"
  14438. "Connection: keep-alive, close\r\n"
  14439. "\r\n",
  14440. &announced_close, &reusable);
  14441. EXPECT_TRUE(announced_close);
  14442. EXPECT_FALSE(reusable);
  14443. }
  14444. // "close" split over two field lines is the same list, so it is honored too.
  14445. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  14446. bool announced_close = false;
  14447. bool reusable = true;
  14448. probe_connection_reuse(port_,
  14449. "GET /keepalive HTTP/1.1\r\n"
  14450. "Host: localhost\r\n"
  14451. "Connection: keep-alive\r\n"
  14452. "Connection: close\r\n"
  14453. "\r\n",
  14454. &announced_close, &reusable);
  14455. EXPECT_TRUE(announced_close);
  14456. EXPECT_FALSE(reusable);
  14457. }
  14458. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  14459. // keep-alive in the spelling everyone actually sends keeps its connection.
  14460. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  14461. bool announced_close = false;
  14462. bool reusable = false;
  14463. probe_connection_reuse(port_,
  14464. "GET /keepalive HTTP/1.0\r\n"
  14465. "Host: localhost\r\n"
  14466. "Connection: keep-alive\r\n"
  14467. "\r\n",
  14468. &announced_close, &reusable);
  14469. EXPECT_FALSE(announced_close);
  14470. EXPECT_TRUE(reusable);
  14471. }
  14472. // A token the value merely contains is not the token itself.
  14473. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  14474. bool announced_close = false;
  14475. bool reusable = false;
  14476. probe_connection_reuse(port_,
  14477. "GET /keepalive HTTP/1.1\r\n"
  14478. "Host: localhost\r\n"
  14479. "Connection: notclose\r\n"
  14480. "\r\n",
  14481. &announced_close, &reusable);
  14482. EXPECT_FALSE(announced_close);
  14483. EXPECT_TRUE(reusable);
  14484. }
  14485. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  14486. Server svr;
  14487. std::vector<std::string> observed_types;
  14488. svr.Get("/", [&](const Request &req, Response &res) {
  14489. observed_types = req.accept_content_types;
  14490. res.set_content("ok", "text/plain");
  14491. });
  14492. auto port = svr.bind_to_any_port(HOST);
  14493. thread t = thread([&]() { svr.listen_after_bind(); });
  14494. auto se = detail::scope_exit([&] {
  14495. svr.stop();
  14496. t.join();
  14497. ASSERT_FALSE(svr.is_running());
  14498. });
  14499. svr.wait_until_ready();
  14500. Client cli(HOST, port);
  14501. Headers headers;
  14502. headers.emplace("Accept", "text/plain;q=0.5");
  14503. headers.emplace("Accept", "application/json");
  14504. auto res = cli.Get("/", headers);
  14505. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14506. EXPECT_EQ(StatusCode::OK_200, res->status);
  14507. // Sorted by q-value, so the second field line's type comes first
  14508. ASSERT_EQ(2U, observed_types.size());
  14509. EXPECT_EQ("application/json", observed_types[0]);
  14510. EXPECT_EQ("text/plain", observed_types[1]);
  14511. }
  14512. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  14513. // empty field line must not contribute a bare comma to the combined value.
  14514. // parse_accept_header() rejects a leading comma outright, so a stray one would
  14515. // turn a legal request into 400 Bad Request.
  14516. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  14517. Server svr;
  14518. std::vector<std::string> observed_types;
  14519. svr.Get("/", [&](const Request &req, Response &res) {
  14520. observed_types = req.accept_content_types;
  14521. res.set_content("ok", "text/plain");
  14522. });
  14523. auto port = svr.bind_to_any_port(HOST);
  14524. thread t = thread([&]() { svr.listen_after_bind(); });
  14525. auto se = detail::scope_exit([&] {
  14526. svr.stop();
  14527. t.join();
  14528. ASSERT_FALSE(svr.is_running());
  14529. });
  14530. svr.wait_until_ready();
  14531. // Empty first field line, then a real one
  14532. std::string raw_req = "GET / HTTP/1.1\r\n"
  14533. "Host: localhost\r\n"
  14534. "Accept:\r\n"
  14535. "Accept: application/json\r\n"
  14536. "Connection: close\r\n"
  14537. "\r\n";
  14538. std::string out;
  14539. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  14540. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  14541. ASSERT_EQ(1U, observed_types.size());
  14542. EXPECT_EQ("application/json", observed_types[0]);
  14543. }
  14544. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  14545. // An encoding offered on a later Accept-Encoding field line is still offered.
  14546. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  14547. Server svr;
  14548. svr.Get("/", [](const Request & /*req*/, Response &res) {
  14549. res.set_content(std::string(1024, 'x'), "text/plain");
  14550. });
  14551. auto port = svr.bind_to_any_port(HOST);
  14552. thread t = thread([&]() { svr.listen_after_bind(); });
  14553. auto se = detail::scope_exit([&] {
  14554. svr.stop();
  14555. t.join();
  14556. ASSERT_FALSE(svr.is_running());
  14557. });
  14558. svr.wait_until_ready();
  14559. Client cli(HOST, port);
  14560. cli.set_decompress(false);
  14561. Headers headers;
  14562. headers.emplace("Accept-Encoding", "identity");
  14563. headers.emplace("Accept-Encoding", "gzip");
  14564. auto res = cli.Get("/", headers);
  14565. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14566. EXPECT_EQ(StatusCode::OK_200, res->status);
  14567. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  14568. }
  14569. #endif
  14570. #ifndef _WIN32
  14571. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  14572. Server svr;
  14573. svr.Post("/post", [&](const Request &req, Response &res) {
  14574. res.set_content(req.body, "text/plain");
  14575. });
  14576. svr.Put("/put", [&](const Request &req, Response &res) {
  14577. res.set_content(req.body, "text/plain");
  14578. });
  14579. svr.Patch("/patch", [&](const Request &req, Response &res) {
  14580. res.set_content(req.body, "text/plain");
  14581. });
  14582. svr.Delete("/delete", [&](const Request &req, Response &res) {
  14583. res.set_content(req.body, "text/plain");
  14584. });
  14585. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14586. auto se = detail::scope_exit([&] {
  14587. svr.stop();
  14588. t.join();
  14589. ASSERT_FALSE(svr.is_running());
  14590. });
  14591. svr.wait_until_ready();
  14592. std::string resp;
  14593. // POST without Content-Length
  14594. ASSERT_TRUE(send_request(5,
  14595. "POST /post HTTP/1.1\r\n"
  14596. "Host: localhost\r\n"
  14597. "Connection: close\r\n"
  14598. "\r\n",
  14599. &resp));
  14600. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  14601. // PUT without Content-Length
  14602. resp.clear();
  14603. ASSERT_TRUE(send_request(5,
  14604. "PUT /put HTTP/1.1\r\n"
  14605. "Host: localhost\r\n"
  14606. "Connection: close\r\n"
  14607. "\r\n",
  14608. &resp));
  14609. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  14610. // PATCH without Content-Length
  14611. resp.clear();
  14612. ASSERT_TRUE(send_request(5,
  14613. "PATCH /patch HTTP/1.1\r\n"
  14614. "Host: localhost\r\n"
  14615. "Connection: close\r\n"
  14616. "\r\n",
  14617. &resp));
  14618. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  14619. // DELETE without Content-Length
  14620. resp.clear();
  14621. ASSERT_TRUE(send_request(5,
  14622. "DELETE /delete HTTP/1.1\r\n"
  14623. "Host: localhost\r\n"
  14624. "Connection: close\r\n"
  14625. "\r\n",
  14626. &resp));
  14627. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  14628. }
  14629. #endif
  14630. //==============================================================================
  14631. // open_stream() Tests
  14632. //==============================================================================
  14633. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  14634. std::string result;
  14635. char buf[8192];
  14636. ssize_t n;
  14637. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  14638. result.append(buf, static_cast<size_t>(n));
  14639. }
  14640. return result;
  14641. }
  14642. // Mock stream for unit tests
  14643. class MockStream : public Stream {
  14644. public:
  14645. std::string data;
  14646. size_t pos = 0;
  14647. ssize_t error_after = -1; // -1 = no error
  14648. explicit MockStream(const std::string &d, ssize_t err = -1)
  14649. : data(d), error_after(err) {}
  14650. bool is_readable() const override { return true; }
  14651. bool wait_readable() const override { return true; }
  14652. bool wait_writable() const override { return true; }
  14653. ssize_t read(char *ptr, size_t size) override {
  14654. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  14655. if (pos >= data.size()) return 0;
  14656. size_t limit =
  14657. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  14658. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  14659. std::memcpy(ptr, data.data() + pos, to_read);
  14660. pos += to_read;
  14661. return static_cast<ssize_t>(to_read);
  14662. }
  14663. ssize_t write(const char *, size_t) override { return -1; }
  14664. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  14665. ip = "127.0.0.1";
  14666. port = 0;
  14667. }
  14668. void get_local_ip_and_port(std::string &ip, int &port) const override {
  14669. ip = "127.0.0.1";
  14670. port = 0;
  14671. }
  14672. socket_t socket() const override { return INVALID_SOCKET; }
  14673. time_t duration() const override { return 0; }
  14674. };
  14675. TEST(StreamHandleTest, Basic) {
  14676. ClientImpl::StreamHandle handle;
  14677. EXPECT_FALSE(handle.is_valid());
  14678. handle.response = detail::make_unique<Response>();
  14679. handle.error = Error::Connection;
  14680. EXPECT_FALSE(handle.is_valid());
  14681. handle.error = Error::Success;
  14682. EXPECT_TRUE(handle.is_valid());
  14683. }
  14684. TEST(BodyReaderTest, Basic) {
  14685. MockStream stream("Hello, World!");
  14686. detail::BodyReader reader;
  14687. reader.stream = &stream;
  14688. reader.content_length = 13;
  14689. char buf[32];
  14690. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  14691. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  14692. EXPECT_TRUE(reader.eof);
  14693. }
  14694. TEST(BodyReaderTest, NoStream) {
  14695. detail::BodyReader reader;
  14696. char buf[32];
  14697. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  14698. EXPECT_EQ(Error::Connection, reader.last_error);
  14699. }
  14700. TEST(BodyReaderTest, Error) {
  14701. MockStream stream("Hello, World!", 5);
  14702. detail::BodyReader reader;
  14703. reader.stream = &stream;
  14704. reader.content_length = 13;
  14705. char buf[32];
  14706. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  14707. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  14708. EXPECT_EQ(Error::Read, reader.last_error);
  14709. }
  14710. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  14711. // Mock-based StreamHandle tests relying on private internals are removed.
  14712. class OpenStreamTest : public ::testing::Test {
  14713. protected:
  14714. void SetUp() override {
  14715. svr_.Get("/hello", [](const Request &, Response &res) {
  14716. res.set_content("Hello World!", "text/plain");
  14717. });
  14718. svr_.Get("/large", [](const Request &, Response &res) {
  14719. res.set_content(std::string(10000, 'X'), "text/plain");
  14720. });
  14721. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  14722. res.set_content("Hello World!", "image/jpeg");
  14723. res.set_header("Content-Encoding", "UTF-8");
  14724. });
  14725. svr_.Get("/chunked", [](const Request &, Response &res) {
  14726. res.set_chunked_content_provider("text/plain",
  14727. [](size_t offset, DataSink &sink) {
  14728. if (offset < 15) {
  14729. sink.write("chunk", 5);
  14730. return true;
  14731. }
  14732. sink.done();
  14733. return true;
  14734. });
  14735. });
  14736. svr_.Get("/compressible", [](const Request &, Response &res) {
  14737. res.set_chunked_content_provider("text/plain", [](size_t offset,
  14738. DataSink &sink) {
  14739. if (offset < 100 * 1024) {
  14740. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  14741. sink.write(chunk.data(), chunk.size());
  14742. return true;
  14743. }
  14744. sink.done();
  14745. return true;
  14746. });
  14747. });
  14748. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  14749. [](const Request & /*req*/, Response &res) {
  14750. auto i = new int(0);
  14751. res.set_header("Trailer", "Content-Length, X-Allowed");
  14752. res.set_chunked_content_provider(
  14753. "text/plain",
  14754. [i](size_t /*offset*/, DataSink &sink) {
  14755. switch (*i) {
  14756. case 0: sink.os << "123"; break;
  14757. case 1: sink.os << "456"; break;
  14758. case 2: sink.os << "789"; break;
  14759. case 3: {
  14760. sink.done_with_trailer(
  14761. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  14762. } break;
  14763. }
  14764. (*i)++;
  14765. return true;
  14766. },
  14767. [i](bool success) {
  14768. EXPECT_TRUE(success);
  14769. delete i;
  14770. });
  14771. });
  14772. // Echo headers endpoint for header-related tests
  14773. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  14774. std::string body;
  14775. for (const auto &h : req.headers) {
  14776. body.append(h.first);
  14777. body.push_back(':');
  14778. body.append(h.second);
  14779. body.push_back('\n');
  14780. }
  14781. res.set_content(body, "text/plain");
  14782. });
  14783. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  14784. std::string body;
  14785. for (const auto &h : req.headers) {
  14786. body.append(h.first);
  14787. body.push_back(':');
  14788. body.append(h.second);
  14789. body.push_back('\n');
  14790. }
  14791. res.set_content(body, "text/plain");
  14792. });
  14793. port_ = svr_.bind_to_any_port("127.0.0.1");
  14794. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  14795. svr_.wait_until_ready();
  14796. }
  14797. void TearDown() override {
  14798. svr_.stop();
  14799. if (thread_.joinable()) thread_.join();
  14800. }
  14801. Server svr_;
  14802. std::thread thread_;
  14803. int port_ = 0;
  14804. };
  14805. TEST_F(OpenStreamTest, Basic) {
  14806. Client cli("127.0.0.1", port_);
  14807. auto handle = cli.open_stream("GET", "/hello");
  14808. EXPECT_TRUE(handle.is_valid());
  14809. EXPECT_EQ("Hello World!", read_all(handle));
  14810. }
  14811. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  14812. Client cli("127.0.0.1", port_);
  14813. auto handle = cli.open_stream("GET", "/unknown-encoding");
  14814. ASSERT_TRUE(handle.is_valid());
  14815. EXPECT_EQ("Hello World!", read_all(handle));
  14816. }
  14817. TEST_F(OpenStreamTest, SmallBuffer) {
  14818. Client cli("127.0.0.1", port_);
  14819. auto handle = cli.open_stream("GET", "/hello");
  14820. std::string result;
  14821. char buf[4];
  14822. ssize_t n;
  14823. while ((n = handle.read(buf, sizeof(buf))) > 0)
  14824. result.append(buf, static_cast<size_t>(n));
  14825. EXPECT_EQ("Hello World!", result);
  14826. }
  14827. TEST_F(OpenStreamTest, DefaultHeaders) {
  14828. Client cli("127.0.0.1", port_);
  14829. // open_stream GET should include Host, User-Agent and Accept-Encoding
  14830. {
  14831. auto handle = cli.open_stream("GET", "/echo-headers");
  14832. ASSERT_TRUE(handle.is_valid());
  14833. auto body = read_all(handle);
  14834. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  14835. std::string::npos);
  14836. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  14837. std::string::npos);
  14838. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  14839. }
  14840. // open_stream POST with body and no explicit content_type should NOT add
  14841. // text/plain Content-Type (behavior differs from non-streaming path), but
  14842. // should include Content-Length
  14843. {
  14844. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  14845. ASSERT_TRUE(handle.is_valid());
  14846. auto body = read_all(handle);
  14847. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  14848. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  14849. }
  14850. // open_stream POST with explicit Content-Type should preserve it
  14851. {
  14852. auto handle = cli.open_stream("POST", "/echo-headers", {},
  14853. {{"Content-Type", "application/custom"}},
  14854. "{}", "application/custom");
  14855. ASSERT_TRUE(handle.is_valid());
  14856. auto body = read_all(handle);
  14857. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  14858. }
  14859. // User-specified User-Agent must not be overwritten for stream API
  14860. {
  14861. auto handle = cli.open_stream("GET", "/echo-headers", {},
  14862. {{"User-Agent", "MyAgent/1.2"}});
  14863. ASSERT_TRUE(handle.is_valid());
  14864. auto body = read_all(handle);
  14865. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  14866. }
  14867. }
  14868. TEST_F(OpenStreamTest, Large) {
  14869. Client cli("127.0.0.1", port_);
  14870. auto handle = cli.open_stream("GET", "/large");
  14871. EXPECT_EQ(10000u, read_all(handle).size());
  14872. }
  14873. TEST_F(OpenStreamTest, ConnectionError) {
  14874. Client cli("127.0.0.1", 9999);
  14875. auto handle = cli.open_stream("GET", "/hello");
  14876. EXPECT_FALSE(handle.is_valid());
  14877. }
  14878. TEST_F(OpenStreamTest, Chunked) {
  14879. Client cli("127.0.0.1", port_);
  14880. auto handle = cli.open_stream("GET", "/chunked");
  14881. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  14882. "Transfer-Encoding") == "chunked");
  14883. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  14884. }
  14885. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  14886. Client cli("127.0.0.1", port_);
  14887. auto handle =
  14888. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  14889. ASSERT_TRUE(handle.is_valid());
  14890. // Consume body to allow trailers to be received/parsed
  14891. auto body = read_all(handle);
  14892. // Explicitly parse trailers (ensure trailers are available for assertion)
  14893. handle.parse_trailers_if_needed();
  14894. EXPECT_EQ(std::string("123456789"), body);
  14895. // The response should include a Trailer header declaring both names
  14896. ASSERT_TRUE(handle.response);
  14897. EXPECT_TRUE(handle.response->has_header("Trailer"));
  14898. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  14899. handle.response->get_header_value("Trailer"));
  14900. // Prohibited trailer must not be present
  14901. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  14902. // Allowed trailer should be present
  14903. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  14904. EXPECT_EQ(std::string("yes"),
  14905. handle.response->get_trailer_value("X-Allowed"));
  14906. // Verify trailers are NOT present as regular headers
  14907. EXPECT_EQ(std::string(""),
  14908. handle.response->get_header_value("Content-Length"));
  14909. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  14910. }
  14911. static std::thread serve_single_response(std::promise<int> &port_promise,
  14912. const std::string &response) {
  14913. return std::thread([&port_promise, response] {
  14914. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  14915. default_socket_options(srv);
  14916. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  14917. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  14918. sockaddr_in addr{};
  14919. addr.sin_family = AF_INET;
  14920. addr.sin_port = htons(0); // Let OS assign a free port
  14921. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  14922. int opt = 1;
  14923. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  14924. #ifdef _WIN32
  14925. reinterpret_cast<const char *>(&opt),
  14926. #else
  14927. &opt,
  14928. #endif
  14929. sizeof(opt));
  14930. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  14931. ::listen(srv, 1) != 0) {
  14932. port_promise.set_value(-1);
  14933. detail::close_socket(srv);
  14934. return;
  14935. }
  14936. socklen_t addr_len = sizeof(addr);
  14937. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  14938. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  14939. sockaddr_in cli_addr{};
  14940. socklen_t cli_len = sizeof(cli_addr);
  14941. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  14942. if (cli != INVALID_SOCKET) {
  14943. // Read the complete HTTP request (until the blank line that terminates
  14944. // headers) before sending the response. If the server closes the socket
  14945. // while the client's request data is still unread in the kernel receive
  14946. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  14947. // connection on both sides: it discards the client's receive buffer
  14948. // (which already holds our response) and causes any in-progress write on
  14949. // the client to fail with ECONNRESET. Reading all request data first
  14950. // ensures close() emits a graceful FIN.
  14951. {
  14952. char rbuf[256];
  14953. std::string req;
  14954. while (req.find("\r\n\r\n") == std::string::npos) {
  14955. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  14956. if (n <= 0) { break; }
  14957. req.append(rbuf, static_cast<size_t>(n));
  14958. }
  14959. }
  14960. ::send(cli,
  14961. #ifdef _WIN32
  14962. static_cast<const char *>(response.c_str()),
  14963. static_cast<int>(response.size()),
  14964. #else
  14965. response.c_str(), response.size(),
  14966. #endif
  14967. 0);
  14968. detail::close_socket(cli);
  14969. }
  14970. detail::close_socket(srv);
  14971. });
  14972. }
  14973. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  14974. #ifndef _WIN32
  14975. signal(SIGPIPE, SIG_IGN);
  14976. #endif
  14977. std::promise<int> port_promise;
  14978. auto port_future = port_promise.get_future();
  14979. auto server_thread =
  14980. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  14981. "Content-Type: text/plain\r\n"
  14982. "Content-Length: not-a-number\r\n"
  14983. "Connection: close\r\n"
  14984. "\r\n"
  14985. "hello");
  14986. auto port = port_future.get();
  14987. ASSERT_GT(port, 0);
  14988. Client cli("127.0.0.1", port);
  14989. auto handle = cli.open_stream("GET", "/");
  14990. EXPECT_FALSE(handle.is_valid());
  14991. server_thread.join();
  14992. }
  14993. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  14994. #ifndef _WIN32
  14995. signal(SIGPIPE, SIG_IGN);
  14996. #endif
  14997. std::promise<int> port_promise;
  14998. auto port_future = port_promise.get_future();
  14999. auto server_thread = serve_single_response(
  15000. port_promise, "HTTP/1.1 200 OK\r\n"
  15001. "Content-Type: text/plain\r\n"
  15002. "Content-Length: 99999999999999999999999999\r\n"
  15003. "Connection: close\r\n"
  15004. "\r\n"
  15005. "hello");
  15006. auto port = port_future.get();
  15007. ASSERT_GT(port, 0);
  15008. // Historically std::stoull would throw std::out_of_range here and crash
  15009. // the process, then parsing silently clamped to a bogus framing length and
  15010. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  15011. // so the stream fails to open, matching the not-a-number case above. The
  15012. // process still must NOT terminate.
  15013. Client cli("127.0.0.1", port);
  15014. auto handle = cli.open_stream("GET", "/");
  15015. EXPECT_FALSE(handle.is_valid());
  15016. server_thread.join();
  15017. }
  15018. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  15019. TEST_F(OpenStreamTest, Gzip) {
  15020. Client cli("127.0.0.1", port_);
  15021. auto handle = cli.open_stream("GET", "/compressible", {},
  15022. {{"Accept-Encoding", "gzip"}});
  15023. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  15024. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  15025. }
  15026. #endif
  15027. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  15028. TEST_F(OpenStreamTest, Brotli) {
  15029. Client cli("127.0.0.1", port_);
  15030. auto handle =
  15031. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  15032. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  15033. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  15034. }
  15035. #endif
  15036. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  15037. TEST_F(OpenStreamTest, Zstd) {
  15038. Client cli("127.0.0.1", port_);
  15039. auto handle = cli.open_stream("GET", "/compressible", {},
  15040. {{"Accept-Encoding", "zstd"}});
  15041. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  15042. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  15043. }
  15044. #endif
  15045. #ifdef CPPHTTPLIB_SSL_ENABLED
  15046. class SSLOpenStreamTest : public ::testing::Test {
  15047. protected:
  15048. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  15049. void SetUp() override {
  15050. svr_.Get("/hello", [](const Request &, Response &res) {
  15051. res.set_content("Hello SSL World!", "text/plain");
  15052. });
  15053. svr_.Get("/chunked", [](const Request &, Response &res) {
  15054. res.set_chunked_content_provider("text/plain",
  15055. [](size_t offset, DataSink &sink) {
  15056. if (offset < 15) {
  15057. sink.write("chunk", 5);
  15058. return true;
  15059. }
  15060. sink.done();
  15061. return true;
  15062. });
  15063. });
  15064. svr_.Post("/echo", [](const Request &req, Response &res) {
  15065. res.set_content(req.body, req.get_header_value("Content-Type"));
  15066. });
  15067. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  15068. std::string body = req.body;
  15069. res.set_chunked_content_provider(
  15070. "text/plain", [body](size_t offset, DataSink &sink) {
  15071. if (offset < body.size()) {
  15072. sink.write(body.data() + offset, body.size() - offset);
  15073. }
  15074. sink.done();
  15075. return true;
  15076. });
  15077. });
  15078. port_ = svr_.bind_to_any_port("127.0.0.1");
  15079. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  15080. svr_.wait_until_ready();
  15081. }
  15082. void TearDown() override {
  15083. svr_.stop();
  15084. if (thread_.joinable()) thread_.join();
  15085. }
  15086. SSLServer svr_;
  15087. std::thread thread_;
  15088. int port_ = 0;
  15089. };
  15090. TEST_F(SSLOpenStreamTest, Basic) {
  15091. SSLClient cli("127.0.0.1", port_);
  15092. cli.enable_server_certificate_verification(false);
  15093. auto handle = cli.open_stream("GET", "/hello");
  15094. ASSERT_TRUE(handle.is_valid());
  15095. EXPECT_EQ("Hello SSL World!", read_all(handle));
  15096. }
  15097. TEST_F(SSLOpenStreamTest, Chunked) {
  15098. SSLClient cli("127.0.0.1", port_);
  15099. cli.enable_server_certificate_verification(false);
  15100. auto handle = cli.open_stream("GET", "/chunked");
  15101. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  15102. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  15103. "Transfer-Encoding") == "chunked");
  15104. auto body = read_all(handle);
  15105. EXPECT_EQ("chunkchunkchunk", body);
  15106. }
  15107. TEST_F(SSLOpenStreamTest, Post) {
  15108. SSLClient cli("127.0.0.1", port_);
  15109. cli.enable_server_certificate_verification(false);
  15110. auto handle =
  15111. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  15112. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  15113. EXPECT_EQ(200, handle.response->status);
  15114. auto body = read_all(handle);
  15115. EXPECT_EQ("Hello SSL POST", body);
  15116. }
  15117. TEST_F(SSLOpenStreamTest, PostChunked) {
  15118. SSLClient cli("127.0.0.1", port_);
  15119. cli.enable_server_certificate_verification(false);
  15120. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  15121. "Chunked SSL Data", "text/plain");
  15122. ASSERT_TRUE(handle.is_valid());
  15123. EXPECT_EQ(200, handle.response->status);
  15124. auto body = read_all(handle);
  15125. EXPECT_EQ("Chunked SSL Data", body);
  15126. }
  15127. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  15128. // Content-Length is terminated by the server closing the connection. When the
  15129. // SSL peer sends a close_notify after the body, the client must treat it as a
  15130. // clean EOF and return a successful response rather than an error.
  15131. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  15132. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15133. ASSERT_TRUE(svr.is_valid());
  15134. svr.set_keep_alive_max_count(1);
  15135. const std::string expected_body = "Hello from connection-close response!";
  15136. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  15137. res.set_content_provider("text/plain",
  15138. [&](size_t offset, DataSink &sink) -> bool {
  15139. if (offset < expected_body.size()) {
  15140. sink.write(expected_body.data() + offset,
  15141. expected_body.size() - offset);
  15142. }
  15143. sink.done();
  15144. return true;
  15145. });
  15146. });
  15147. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  15148. auto se = detail::scope_exit([&] {
  15149. svr.stop();
  15150. listen_thread.join();
  15151. ASSERT_FALSE(svr.is_running());
  15152. });
  15153. svr.wait_until_ready();
  15154. SSLClient cli(HOST, PORT);
  15155. cli.enable_server_certificate_verification(false);
  15156. auto res = cli.Get("/no-content-length");
  15157. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  15158. EXPECT_EQ(StatusCode::OK_200, res->status);
  15159. EXPECT_EQ(expected_body, res->body);
  15160. }
  15161. #endif // CPPHTTPLIB_SSL_ENABLED
  15162. //==============================================================================
  15163. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  15164. // results for various scenarios.
  15165. //==============================================================================
  15166. TEST(ParityTest, GetVsOpenStream) {
  15167. Server svr;
  15168. const std::string path = "/parity";
  15169. const std::string content = "Parity test content: hello world";
  15170. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  15171. res.set_content(content, "text/plain");
  15172. });
  15173. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15174. auto se = detail::scope_exit([&] {
  15175. svr.stop();
  15176. t.join();
  15177. ASSERT_FALSE(svr.is_running());
  15178. });
  15179. svr.wait_until_ready();
  15180. Client cli(HOST, PORT);
  15181. // Non-stream path
  15182. auto r1 = cli.Get(path);
  15183. ASSERT_TRUE(r1);
  15184. EXPECT_EQ(StatusCode::OK_200, r1->status);
  15185. // Stream path
  15186. auto h = cli.open_stream("GET", path);
  15187. ASSERT_TRUE(h.is_valid());
  15188. EXPECT_EQ(r1->body, read_all(h));
  15189. }
  15190. // Helper to compress data with provided compressor type T
  15191. template <typename Compressor>
  15192. static std::string compress_payload_for_parity(const std::string &in) {
  15193. std::string out;
  15194. Compressor compressor;
  15195. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  15196. [&](const char *data, size_t n) {
  15197. out.append(data, n);
  15198. return true;
  15199. });
  15200. EXPECT_TRUE(ok);
  15201. return out;
  15202. }
  15203. // Helper function for compression parity tests
  15204. template <typename Compressor>
  15205. static void test_compression_parity(const std::string &original,
  15206. const std::string &path,
  15207. const std::string &encoding) {
  15208. const std::string compressed =
  15209. compress_payload_for_parity<Compressor>(original);
  15210. Server svr;
  15211. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  15212. res.set_content(compressed, "application/octet-stream");
  15213. res.set_header("Content-Encoding", encoding);
  15214. });
  15215. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  15216. auto se = detail::scope_exit([&] {
  15217. svr.stop();
  15218. t.join();
  15219. ASSERT_FALSE(svr.is_running());
  15220. });
  15221. svr.wait_until_ready();
  15222. Client cli(HOST, PORT);
  15223. // Non-streaming
  15224. {
  15225. auto res = cli.Get(path);
  15226. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15227. EXPECT_EQ(StatusCode::OK_200, res->status);
  15228. EXPECT_EQ(original, res->body);
  15229. }
  15230. // Streaming
  15231. {
  15232. auto h = cli.open_stream("GET", path);
  15233. ASSERT_TRUE(h.is_valid());
  15234. EXPECT_EQ(original, read_all(h));
  15235. }
  15236. }
  15237. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  15238. TEST(ParityTest, Gzip) {
  15239. test_compression_parity<detail::gzip_compressor>(
  15240. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  15241. }
  15242. #endif
  15243. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  15244. TEST(ParityTest, Brotli) {
  15245. test_compression_parity<detail::brotli_compressor>(
  15246. "Hello, brotli parity test payload", "/parity-br", "br");
  15247. }
  15248. #endif
  15249. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  15250. TEST(ParityTest, Zstd) {
  15251. test_compression_parity<detail::zstd_compressor>(
  15252. "Zstandard parity test payload", "/parity-zstd", "zstd");
  15253. }
  15254. #endif
  15255. //==============================================================================
  15256. // New Stream API Tests
  15257. //==============================================================================
  15258. inline std::string read_body(httplib::stream::Result &result) {
  15259. std::string body;
  15260. while (result.next()) {
  15261. body.append(result.data(), result.size());
  15262. }
  15263. return body;
  15264. }
  15265. TEST(ClientConnectionTest, Basic) {
  15266. httplib::ClientConnection conn;
  15267. EXPECT_FALSE(conn.is_open());
  15268. conn.sock = 1;
  15269. EXPECT_TRUE(conn.is_open());
  15270. httplib::ClientConnection conn2(std::move(conn));
  15271. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  15272. conn2.sock = INVALID_SOCKET;
  15273. }
  15274. // Unified test server for all stream::* tests
  15275. class StreamApiTest : public ::testing::Test {
  15276. protected:
  15277. void SetUp() override {
  15278. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  15279. res.set_content("Hello World!", "text/plain");
  15280. });
  15281. svr_.Get("/echo-params",
  15282. [](const httplib::Request &req, httplib::Response &res) {
  15283. std::string r;
  15284. for (const auto &p : req.params) {
  15285. if (!r.empty()) r += "&";
  15286. r += p.first + "=" + p.second;
  15287. }
  15288. res.set_content(r, "text/plain");
  15289. });
  15290. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  15291. res.set_content(req.body, req.get_header_value("Content-Type"));
  15292. });
  15293. svr_.Post("/echo-headers",
  15294. [](const httplib::Request &req, httplib::Response &res) {
  15295. std::string r;
  15296. for (const auto &h : req.headers)
  15297. r += h.first + ": " + h.second + "\n";
  15298. res.set_content(r, "text/plain");
  15299. });
  15300. svr_.Post("/echo-params",
  15301. [](const httplib::Request &req, httplib::Response &res) {
  15302. std::string r = "params:";
  15303. for (const auto &p : req.params)
  15304. r += p.first + "=" + p.second + ";";
  15305. res.set_content(r + " body:" + req.body, "text/plain");
  15306. });
  15307. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  15308. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  15309. });
  15310. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  15311. res.set_content("PUT:" + req.body, "text/plain");
  15312. });
  15313. svr_.Patch("/echo",
  15314. [](const httplib::Request &req, httplib::Response &res) {
  15315. res.set_content("PATCH:" + req.body, "text/plain");
  15316. });
  15317. svr_.Delete(
  15318. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  15319. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  15320. "text/plain");
  15321. });
  15322. svr_.Get("/head-test",
  15323. [](const httplib::Request &, httplib::Response &res) {
  15324. res.set_content("body for HEAD", "text/plain");
  15325. });
  15326. svr_.Options("/options",
  15327. [](const httplib::Request &, httplib::Response &res) {
  15328. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  15329. });
  15330. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  15331. svr_.wait_until_ready();
  15332. }
  15333. void TearDown() override {
  15334. svr_.stop();
  15335. if (thread_.joinable()) thread_.join();
  15336. }
  15337. httplib::Server svr_;
  15338. std::thread thread_;
  15339. };
  15340. // stream::Get tests
  15341. TEST_F(StreamApiTest, GetBasic) {
  15342. httplib::Client cli(HOST, PORT);
  15343. auto result = httplib::stream::Get(cli, "/hello");
  15344. ASSERT_TRUE(result.is_valid());
  15345. EXPECT_EQ(200, result.status());
  15346. EXPECT_EQ("Hello World!", read_body(result));
  15347. }
  15348. TEST_F(StreamApiTest, GetWithParams) {
  15349. httplib::Client cli(HOST, PORT);
  15350. httplib::Params params{{"foo", "bar"}};
  15351. auto result = httplib::stream::Get(cli, "/echo-params", params);
  15352. ASSERT_TRUE(result.is_valid());
  15353. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  15354. }
  15355. TEST_F(StreamApiTest, GetConnectionError) {
  15356. httplib::Client cli(HOST, 9999);
  15357. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  15358. }
  15359. TEST_F(StreamApiTest, Get404) {
  15360. httplib::Client cli(HOST, PORT);
  15361. auto result = httplib::stream::Get(cli, "/nonexistent");
  15362. EXPECT_TRUE(result.is_valid());
  15363. EXPECT_EQ(404, result.status());
  15364. }
  15365. // stream::Post tests
  15366. TEST_F(StreamApiTest, PostBasic) {
  15367. httplib::Client cli(HOST, PORT);
  15368. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  15369. "application/json");
  15370. ASSERT_TRUE(result.is_valid());
  15371. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  15372. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  15373. }
  15374. TEST_F(StreamApiTest, PostWithHeaders) {
  15375. httplib::Client cli(HOST, PORT);
  15376. httplib::Headers headers{{"X-Custom", "value"}};
  15377. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  15378. "text/plain");
  15379. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  15380. }
  15381. TEST_F(StreamApiTest, PostWithParams) {
  15382. httplib::Client cli(HOST, PORT);
  15383. httplib::Params params{{"k", "v"}};
  15384. auto result =
  15385. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  15386. auto body = read_body(result);
  15387. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  15388. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  15389. }
  15390. TEST_F(StreamApiTest, PostLarge) {
  15391. httplib::Client cli(HOST, PORT);
  15392. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  15393. size_t total = 0;
  15394. while (result.next()) {
  15395. total += result.size();
  15396. }
  15397. EXPECT_EQ(100u * 1024u, total);
  15398. }
  15399. // stream::Put/Patch tests
  15400. TEST_F(StreamApiTest, PutAndPatch) {
  15401. httplib::Client cli(HOST, PORT);
  15402. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  15403. EXPECT_EQ("PUT:test", read_body(put));
  15404. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  15405. EXPECT_EQ("PATCH:test", read_body(patch));
  15406. }
  15407. // stream::Delete tests
  15408. TEST_F(StreamApiTest, Delete) {
  15409. httplib::Client cli(HOST, PORT);
  15410. auto del1 = httplib::stream::Delete(cli, "/resource");
  15411. EXPECT_EQ("Deleted", read_body(del1));
  15412. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  15413. EXPECT_EQ("Deleted:data", read_body(del2));
  15414. }
  15415. // stream::Head/Options tests
  15416. TEST_F(StreamApiTest, HeadAndOptions) {
  15417. httplib::Client cli(HOST, PORT);
  15418. auto head = httplib::stream::Head(cli, "/head-test");
  15419. EXPECT_TRUE(head.is_valid());
  15420. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  15421. auto opts = httplib::stream::Options(cli, "/options");
  15422. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  15423. }
  15424. // SSL stream::* tests
  15425. #ifdef CPPHTTPLIB_SSL_ENABLED
  15426. class SSLStreamApiTest : public ::testing::Test {
  15427. protected:
  15428. void SetUp() override {
  15429. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  15430. res.set_content("Hello SSL!", "text/plain");
  15431. });
  15432. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  15433. res.set_content(req.body, "text/plain");
  15434. });
  15435. port_ = svr_.bind_to_any_port("127.0.0.1");
  15436. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  15437. svr_.wait_until_ready();
  15438. }
  15439. void TearDown() override {
  15440. svr_.stop();
  15441. if (thread_.joinable()) thread_.join();
  15442. }
  15443. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  15444. std::thread thread_;
  15445. int port_ = 0;
  15446. };
  15447. TEST_F(SSLStreamApiTest, GetAndPost) {
  15448. httplib::SSLClient cli("127.0.0.1", port_);
  15449. cli.enable_server_certificate_verification(false);
  15450. auto get = httplib::stream::Get(cli, "/hello");
  15451. EXPECT_EQ("Hello SSL!", read_body(get));
  15452. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  15453. EXPECT_EQ("test", read_body(post));
  15454. }
  15455. #endif
  15456. // Tests for Error::Timeout and Error::ConnectionClosed error types
  15457. // These errors are set in SocketStream/SSLSocketStream and propagated through
  15458. // BodyReader
  15459. TEST(ErrorHandlingTest, StreamReadTimeout) {
  15460. // Test that read timeout during streaming is detected
  15461. // Use a large content-length response where server delays mid-stream
  15462. Server svr;
  15463. svr.Get("/slow-stream", [](const Request &, Response &res) {
  15464. // Send a large response with delay in the middle
  15465. res.set_content_provider(
  15466. 1000, // content_length
  15467. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  15468. if (offset < 100) {
  15469. // Send first 100 bytes immediately
  15470. std::string data(100, 'A');
  15471. sink.write(data.c_str(), data.size());
  15472. return true;
  15473. }
  15474. // Then delay longer than client timeout
  15475. std::this_thread::sleep_for(std::chrono::seconds(3));
  15476. std::string data(900, 'B');
  15477. sink.write(data.c_str(), data.size());
  15478. return true;
  15479. });
  15480. });
  15481. auto port = 8091;
  15482. std::thread t([&]() { svr.listen("localhost", port); });
  15483. svr.wait_until_ready();
  15484. Client cli("localhost", port);
  15485. cli.set_read_timeout(1, 0); // 1 second timeout
  15486. auto handle = cli.open_stream("GET", "/slow-stream");
  15487. ASSERT_TRUE(handle.is_valid());
  15488. char buf[256];
  15489. ssize_t total = 0;
  15490. ssize_t n;
  15491. bool got_error = false;
  15492. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  15493. total += n;
  15494. }
  15495. if (n < 0) {
  15496. got_error = true;
  15497. // Should be timeout or read error
  15498. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  15499. handle.get_read_error() == Error::Read)
  15500. << "Actual error: " << to_string(handle.get_read_error());
  15501. }
  15502. // Either we got an error, or we got less data than expected
  15503. EXPECT_TRUE(got_error || total < 1000)
  15504. << "Expected timeout but got all " << total << " bytes";
  15505. svr.stop();
  15506. t.join();
  15507. }
  15508. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  15509. // Test connection closed detection via BodyReader
  15510. Server svr;
  15511. std::atomic<bool> close_now{false};
  15512. svr.Get("/will-close", [&](const Request &, Response &res) {
  15513. res.set_content_provider(
  15514. 10000, // Large content_length that we won't fully send
  15515. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  15516. if (offset < 100) {
  15517. std::string data(100, 'X');
  15518. sink.write(data.c_str(), data.size());
  15519. return true;
  15520. }
  15521. // Wait for signal then abort
  15522. while (!close_now) {
  15523. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  15524. }
  15525. return false; // Abort - server will close connection
  15526. });
  15527. });
  15528. auto port = 8092;
  15529. std::thread t([&]() { svr.listen("localhost", port); });
  15530. svr.wait_until_ready();
  15531. Client cli("localhost", port);
  15532. auto handle = cli.open_stream("GET", "/will-close");
  15533. ASSERT_TRUE(handle.is_valid());
  15534. char buf[256];
  15535. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  15536. EXPECT_GT(n, 0) << "First read should succeed";
  15537. // Signal server to close
  15538. close_now = true;
  15539. // Keep reading until error or EOF
  15540. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  15541. // Keep reading
  15542. }
  15543. // Should get an error since content_length wasn't satisfied
  15544. if (n < 0) {
  15545. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  15546. handle.get_read_error() == Error::Read)
  15547. << "Actual error: " << to_string(handle.get_read_error());
  15548. }
  15549. svr.stop();
  15550. t.join();
  15551. }
  15552. #ifdef CPPHTTPLIB_SSL_ENABLED
  15553. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  15554. // Test that read timeout during SSL streaming is detected
  15555. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15556. svr.Get("/slow-stream", [](const Request &, Response &res) {
  15557. res.set_content_provider(
  15558. 1000, "text/plain",
  15559. [](size_t offset, size_t /*length*/, DataSink &sink) {
  15560. if (offset < 100) {
  15561. std::string data(100, 'A');
  15562. sink.write(data.c_str(), data.size());
  15563. return true;
  15564. }
  15565. std::this_thread::sleep_for(std::chrono::seconds(3));
  15566. std::string data(900, 'B');
  15567. sink.write(data.c_str(), data.size());
  15568. return true;
  15569. });
  15570. });
  15571. auto port = 8093;
  15572. std::thread t([&]() { svr.listen("localhost", port); });
  15573. svr.wait_until_ready();
  15574. SSLClient cli("localhost", port);
  15575. cli.enable_server_certificate_verification(false);
  15576. cli.set_read_timeout(1, 0); // 1 second timeout
  15577. auto handle = cli.open_stream("GET", "/slow-stream");
  15578. ASSERT_TRUE(handle.is_valid());
  15579. char buf[256];
  15580. ssize_t total = 0;
  15581. ssize_t n;
  15582. bool got_error = false;
  15583. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  15584. total += n;
  15585. }
  15586. if (n < 0) {
  15587. got_error = true;
  15588. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  15589. handle.get_read_error() == Error::Read)
  15590. << "Actual error: " << to_string(handle.get_read_error());
  15591. }
  15592. EXPECT_TRUE(got_error || total < 1000)
  15593. << "Expected timeout but got all " << total << " bytes";
  15594. svr.stop();
  15595. t.join();
  15596. }
  15597. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  15598. // Test SSL connection closed detection
  15599. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15600. std::atomic<bool> close_now{false};
  15601. svr.Get("/will-close", [&](const Request &, Response &res) {
  15602. res.set_content_provider(
  15603. 10000, "text/plain",
  15604. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  15605. if (offset < 100) {
  15606. std::string data(100, 'X');
  15607. sink.write(data.c_str(), data.size());
  15608. return true;
  15609. }
  15610. while (!close_now) {
  15611. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  15612. }
  15613. return false;
  15614. });
  15615. });
  15616. auto port = 8094;
  15617. std::thread t([&]() { svr.listen("localhost", port); });
  15618. svr.wait_until_ready();
  15619. SSLClient cli("localhost", port);
  15620. cli.enable_server_certificate_verification(false);
  15621. auto handle = cli.open_stream("GET", "/will-close");
  15622. ASSERT_TRUE(handle.is_valid());
  15623. char buf[256];
  15624. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  15625. EXPECT_GT(n, 0);
  15626. // Signal server to close
  15627. close_now = true;
  15628. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  15629. // Keep reading
  15630. }
  15631. if (n < 0) {
  15632. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  15633. handle.get_read_error() == Error::Read)
  15634. << "Actual error: " << to_string(handle.get_read_error());
  15635. }
  15636. svr.stop();
  15637. t.join();
  15638. }
  15639. #endif
  15640. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  15641. using namespace httplib;
  15642. // Create a test file
  15643. const char *fname = "etag_testfile.txt";
  15644. const char *content = "etag-content";
  15645. {
  15646. std::ofstream ofs(fname);
  15647. ofs << content;
  15648. ASSERT_TRUE(ofs.good());
  15649. }
  15650. Server svr;
  15651. svr.set_mount_point("/static", ".");
  15652. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  15653. svr.wait_until_ready();
  15654. Client cli(HOST, PORT);
  15655. // First request: should get 200 with ETag header
  15656. auto res1 = cli.Get("/static/etag_testfile.txt");
  15657. ASSERT_TRUE(res1);
  15658. ASSERT_EQ(200, res1->status);
  15659. ASSERT_TRUE(res1->has_header("ETag"));
  15660. std::string etag = res1->get_header_value("ETag");
  15661. EXPECT_FALSE(etag.empty());
  15662. // Verify ETag format: W/"hex-hex"
  15663. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  15664. EXPECT_EQ('W', etag[0]);
  15665. EXPECT_EQ('/', etag[1]);
  15666. EXPECT_EQ('"', etag[2]);
  15667. EXPECT_EQ('"', etag.back());
  15668. // Exact match: expect 304 Not Modified
  15669. Headers h2 = {{"If-None-Match", etag}};
  15670. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  15671. ASSERT_TRUE(res2);
  15672. EXPECT_EQ(304, res2->status);
  15673. // Wildcard match: expect 304 Not Modified
  15674. Headers h3 = {{"If-None-Match", "*"}};
  15675. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  15676. ASSERT_TRUE(res3);
  15677. EXPECT_EQ(304, res3->status);
  15678. // Non-matching ETag: expect 200
  15679. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  15680. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  15681. ASSERT_TRUE(res4);
  15682. EXPECT_EQ(200, res4->status);
  15683. // Multiple ETags with one matching: expect 304
  15684. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  15685. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  15686. ASSERT_TRUE(res5);
  15687. EXPECT_EQ(304, res5->status);
  15688. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  15689. // that equivalent to the single comma-separated list above, so the match on
  15690. // the second line must still be found.
  15691. Headers h6;
  15692. h6.emplace("If-None-Match", "W/\"other\"");
  15693. h6.emplace("If-None-Match", etag);
  15694. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  15695. ASSERT_TRUE(res6);
  15696. EXPECT_EQ(304, res6->status);
  15697. svr.stop();
  15698. t.join();
  15699. std::remove(fname);
  15700. }
  15701. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  15702. using namespace httplib;
  15703. Server svr;
  15704. svr.set_mount_point("/static", ".");
  15705. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15706. svr.wait_until_ready();
  15707. Client cli(HOST, PORT);
  15708. // Send If-None-Match: * to a non-existent file
  15709. Headers h = {{"If-None-Match", "*"}};
  15710. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  15711. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15712. EXPECT_EQ(404, res->status);
  15713. svr.stop();
  15714. t.join();
  15715. }
  15716. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  15717. using namespace httplib;
  15718. // Create a test file
  15719. const char *fname = "etag_boundary_testfile.txt";
  15720. const char *content = "boundary-test";
  15721. {
  15722. std::ofstream ofs(fname);
  15723. ofs << content;
  15724. ASSERT_TRUE(ofs.good());
  15725. }
  15726. Server svr;
  15727. svr.set_mount_point("/static", ".");
  15728. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  15729. svr.wait_until_ready();
  15730. Client cli(HOST, PORT);
  15731. // Get the actual ETag
  15732. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  15733. ASSERT_TRUE(res1);
  15734. ASSERT_EQ(200, res1->status);
  15735. ASSERT_TRUE(res1->has_header("ETag"));
  15736. std::string etag = res1->get_header_value("ETag");
  15737. // Test 1: Very long ETag value (longer than actual ETag)
  15738. // Should NOT match and return 200 (not trigger out-of-bounds read)
  15739. Headers h1 = {{"If-None-Match", "W/"
  15740. "\"very-long-etag-value-that-is-much-longer-"
  15741. "than-the-actual-etag-value\""}};
  15742. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  15743. ASSERT_TRUE(res2);
  15744. EXPECT_EQ(200, res2->status); // Should not match
  15745. // Test 2: Long string followed by wildcard
  15746. // Should match on "*" and return 304 (without out-of-bounds read on the long
  15747. // string)
  15748. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  15749. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  15750. ASSERT_TRUE(res3);
  15751. EXPECT_EQ(304, res3->status); // Should match on "*"
  15752. // Test 3: Wildcard followed by long string
  15753. // Should match on "*" immediately and return 304
  15754. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  15755. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  15756. ASSERT_TRUE(res4);
  15757. EXPECT_EQ(304, res4->status); // Should match on "*"
  15758. // Test 4: Multiple long non-matching values
  15759. // Should NOT match and return 200 (test that all comparisons are safe)
  15760. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  15761. "W/\"second-long-non-matching-value\", "
  15762. "W/\"third-long-non-matching-value\""}};
  15763. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  15764. ASSERT_TRUE(res5);
  15765. EXPECT_EQ(200, res5->status); // Should not match
  15766. // Test 5: Single character that is not "*" (edge case)
  15767. Headers h5 = {{"If-None-Match", "X"}};
  15768. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  15769. ASSERT_TRUE(res6);
  15770. EXPECT_EQ(200, res6->status); // Should not match
  15771. svr.stop();
  15772. t.join();
  15773. std::remove(fname);
  15774. }
  15775. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  15776. using namespace httplib;
  15777. // Create a test file
  15778. const char *fname = "ims_testfile.txt";
  15779. const char *content = "if-modified-since-test";
  15780. {
  15781. std::ofstream ofs(fname);
  15782. ofs << content;
  15783. ASSERT_TRUE(ofs.good());
  15784. }
  15785. Server svr;
  15786. svr.set_mount_point("/static", ".");
  15787. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15788. svr.wait_until_ready();
  15789. Client cli(HOST, PORT);
  15790. // First request: should get 200 with Last-Modified header
  15791. auto res1 = cli.Get("/static/ims_testfile.txt");
  15792. ASSERT_TRUE(res1);
  15793. ASSERT_EQ(200, res1->status);
  15794. ASSERT_TRUE(res1->has_header("Last-Modified"));
  15795. std::string last_modified = res1->get_header_value("Last-Modified");
  15796. EXPECT_FALSE(last_modified.empty());
  15797. // If-Modified-Since with same time: expect 304
  15798. Headers h2 = {{"If-Modified-Since", last_modified}};
  15799. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  15800. ASSERT_TRUE(res2);
  15801. EXPECT_EQ(304, res2->status);
  15802. // If-Modified-Since with future time: expect 304
  15803. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  15804. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  15805. ASSERT_TRUE(res3);
  15806. EXPECT_EQ(304, res3->status);
  15807. // If-Modified-Since with past time: expect 200
  15808. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  15809. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  15810. ASSERT_TRUE(res4);
  15811. EXPECT_EQ(200, res4->status);
  15812. // If-None-Match takes precedence over If-Modified-Since
  15813. // (send matching ETag with old If-Modified-Since -> should still be 304)
  15814. ASSERT_TRUE(res1->has_header("ETag"));
  15815. std::string etag = res1->get_header_value("ETag");
  15816. Headers h5 = {{"If-None-Match", etag},
  15817. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  15818. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  15819. ASSERT_TRUE(res5);
  15820. EXPECT_EQ(304, res5->status);
  15821. svr.stop();
  15822. t.join();
  15823. std::remove(fname);
  15824. }
  15825. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  15826. using namespace httplib;
  15827. Server svr;
  15828. // Endpoint that returns compressible content
  15829. svr.Get("/compressible", [](const Request &, Response &res) {
  15830. // Return a large enough body to trigger compression
  15831. std::string body(1000, 'a');
  15832. res.set_content(body, "text/plain");
  15833. });
  15834. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15835. svr.wait_until_ready();
  15836. Client cli(HOST, PORT);
  15837. // Request with gzip support: should get Vary header when compressed
  15838. cli.set_compress(true);
  15839. auto res1 = cli.Get("/compressible");
  15840. ASSERT_TRUE(res1);
  15841. EXPECT_EQ(200, res1->status);
  15842. // If Content-Encoding is set, Vary should also be set
  15843. if (res1->has_header("Content-Encoding")) {
  15844. EXPECT_TRUE(res1->has_header("Vary"));
  15845. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  15846. }
  15847. // Request without Accept-Encoding header: should not have compression
  15848. Headers h_no_compress;
  15849. auto res2 = cli.Get("/compressible", h_no_compress);
  15850. ASSERT_TRUE(res2);
  15851. EXPECT_EQ(200, res2->status);
  15852. // Verify Vary header is present when compression is applied
  15853. // (the exact behavior depends on server configuration)
  15854. svr.stop();
  15855. t.join();
  15856. }
  15857. TEST(ETagTest, IfRangeWithETag) {
  15858. using namespace httplib;
  15859. // Create a test file with known content
  15860. const char *fname = "if_range_testfile.txt";
  15861. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  15862. {
  15863. std::ofstream ofs(fname);
  15864. ofs << content;
  15865. ASSERT_TRUE(ofs.good());
  15866. }
  15867. Server svr;
  15868. svr.set_mount_point("/static", ".");
  15869. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15870. svr.wait_until_ready();
  15871. Client cli(HOST, PORT);
  15872. // First request: get ETag
  15873. auto res1 = cli.Get("/static/if_range_testfile.txt");
  15874. ASSERT_TRUE(res1);
  15875. ASSERT_EQ(200, res1->status);
  15876. ASSERT_TRUE(res1->has_header("ETag"));
  15877. std::string etag = res1->get_header_value("ETag");
  15878. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  15879. // Since our server generates weak ETags (W/"..."), If-Range with our
  15880. // ETag should NOT result in partial content - it should return full content.
  15881. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  15882. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  15883. ASSERT_TRUE(res2);
  15884. // Weak ETag in If-Range -> full content (200), not partial (206)
  15885. EXPECT_EQ(200, res2->status);
  15886. EXPECT_EQ(content, res2->body);
  15887. EXPECT_FALSE(res2->has_header("Content-Range"));
  15888. // Range request with non-matching If-Range (ETag): should get 200 (full
  15889. // content)
  15890. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  15891. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  15892. ASSERT_TRUE(res3);
  15893. EXPECT_EQ(200, res3->status);
  15894. EXPECT_EQ(content, res3->body);
  15895. EXPECT_FALSE(res3->has_header("Content-Range"));
  15896. // Range request with strong ETag (hypothetical - our server doesn't generate
  15897. // strong ETags, but if client sends a strong ETag that doesn't match, it
  15898. // should return full content)
  15899. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  15900. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  15901. ASSERT_TRUE(res4);
  15902. EXPECT_EQ(200, res4->status);
  15903. EXPECT_EQ(content, res4->body);
  15904. EXPECT_FALSE(res4->has_header("Content-Range"));
  15905. svr.stop();
  15906. t.join();
  15907. std::remove(fname);
  15908. }
  15909. TEST(ETagTest, IfRangeWithDate) {
  15910. using namespace httplib;
  15911. // Create a test file
  15912. const char *fname = "if_range_date_testfile.txt";
  15913. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  15914. {
  15915. std::ofstream ofs(fname);
  15916. ofs << content;
  15917. ASSERT_TRUE(ofs.good());
  15918. }
  15919. Server svr;
  15920. svr.set_mount_point("/static", ".");
  15921. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15922. svr.wait_until_ready();
  15923. Client cli(HOST, PORT);
  15924. // First request: get Last-Modified
  15925. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  15926. ASSERT_TRUE(res1);
  15927. ASSERT_EQ(200, res1->status);
  15928. ASSERT_TRUE(res1->has_header("Last-Modified"));
  15929. std::string last_modified = res1->get_header_value("Last-Modified");
  15930. // Range request with matching If-Range (date): should get 206
  15931. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  15932. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  15933. ASSERT_TRUE(res2);
  15934. EXPECT_EQ(206, res2->status);
  15935. EXPECT_EQ("FGHIJ", res2->body);
  15936. // Range request with old If-Range date: should get 200 (full content)
  15937. Headers h3 = {{"Range", "bytes=5-9"},
  15938. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  15939. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  15940. ASSERT_TRUE(res3);
  15941. EXPECT_EQ(200, res3->status);
  15942. EXPECT_EQ(content, res3->body);
  15943. // Range request with future If-Range date: should get 206
  15944. Headers h4 = {{"Range", "bytes=0-4"},
  15945. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  15946. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  15947. ASSERT_TRUE(res4);
  15948. EXPECT_EQ(206, res4->status);
  15949. EXPECT_EQ("ABCDE", res4->body);
  15950. svr.stop();
  15951. t.join();
  15952. std::remove(fname);
  15953. }
  15954. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  15955. using namespace httplib;
  15956. const char *fname = "etag_malformed.txt";
  15957. const char *content = "malformed-etag";
  15958. {
  15959. std::ofstream ofs(fname);
  15960. ofs << content;
  15961. ASSERT_TRUE(ofs.good());
  15962. }
  15963. Server svr;
  15964. svr.set_mount_point("/static", ".");
  15965. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15966. svr.wait_until_ready();
  15967. Client cli(HOST, PORT);
  15968. // baseline: should get 200 and an ETag
  15969. auto res1 = cli.Get("/static/etag_malformed.txt");
  15970. ASSERT_TRUE(res1);
  15971. ASSERT_EQ(200, res1->status);
  15972. ASSERT_TRUE(res1->has_header("ETag"));
  15973. // Malformed ETag value (missing quotes) should be treated as non-matching
  15974. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  15975. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  15976. ASSERT_TRUE(res_bad);
  15977. EXPECT_EQ(200, res_bad->status);
  15978. // Whitespace-only header value should be considered invalid / non-matching
  15979. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  15980. "Host: localhost\r\n"
  15981. "If-None-Match: \r\n"
  15982. "Connection: close\r\n"
  15983. "\r\n";
  15984. std::string out;
  15985. ASSERT_TRUE(send_request(5, raw_req, &out));
  15986. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  15987. svr.stop();
  15988. t.join();
  15989. std::remove(fname);
  15990. }
  15991. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  15992. using namespace httplib;
  15993. const char *fname = "ims_invalid_format.txt";
  15994. const char *content = "ims-bad-format";
  15995. {
  15996. std::ofstream ofs(fname);
  15997. ofs << content;
  15998. ASSERT_TRUE(ofs.good());
  15999. }
  16000. Server svr;
  16001. svr.set_mount_point("/static", ".");
  16002. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16003. svr.wait_until_ready();
  16004. Client cli(HOST, PORT);
  16005. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  16006. ASSERT_TRUE(res1);
  16007. ASSERT_EQ(200, res1->status);
  16008. ASSERT_TRUE(res1->has_header("Last-Modified"));
  16009. // If-Modified-Since with invalid format should not result in 304
  16010. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  16011. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  16012. ASSERT_TRUE(res_bad);
  16013. EXPECT_EQ(200, res_bad->status);
  16014. // If-Range with invalid date format should be treated as mismatch -> full
  16015. // content (200)
  16016. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  16017. {"If-Range", "invalid-date"}};
  16018. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  16019. ASSERT_TRUE(res_ifrange);
  16020. EXPECT_EQ(200, res_ifrange->status);
  16021. svr.stop();
  16022. t.join();
  16023. std::remove(fname);
  16024. }
  16025. TEST(ETagTest, IfRangeWithMalformedETag) {
  16026. using namespace httplib;
  16027. const char *fname = "ifrange_malformed.txt";
  16028. const std::string content = "0123456789";
  16029. {
  16030. std::ofstream ofs(fname);
  16031. ofs << content;
  16032. ASSERT_TRUE(ofs.good());
  16033. }
  16034. Server svr;
  16035. svr.set_mount_point("/static", ".");
  16036. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16037. svr.wait_until_ready();
  16038. Client cli(HOST, PORT);
  16039. // First request: get ETag
  16040. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  16041. ASSERT_TRUE(res1);
  16042. ASSERT_EQ(200, res1->status);
  16043. ASSERT_TRUE(res1->has_header("ETag"));
  16044. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  16045. // full content (200)
  16046. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  16047. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  16048. ASSERT_TRUE(res2);
  16049. EXPECT_EQ(200, res2->status);
  16050. EXPECT_EQ(content, res2->body);
  16051. svr.stop();
  16052. t.join();
  16053. std::remove(fname);
  16054. }
  16055. TEST(ETagTest, ExtremeLargeDateValues) {
  16056. using namespace httplib;
  16057. const char *fname = "ims_extreme_date.txt";
  16058. const char *content = "ims-extreme-date";
  16059. {
  16060. std::ofstream ofs(fname);
  16061. ofs << content;
  16062. ASSERT_TRUE(ofs.good());
  16063. }
  16064. Server svr;
  16065. svr.set_mount_point("/static", ".");
  16066. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16067. svr.wait_until_ready();
  16068. Client cli(HOST, PORT);
  16069. auto res1 = cli.Get(std::string("/static/") + fname);
  16070. ASSERT_TRUE(res1);
  16071. ASSERT_EQ(200, res1->status);
  16072. ASSERT_TRUE(res1->has_header("Last-Modified"));
  16073. // Extremely large year that may overflow date parsing routines.
  16074. Headers h_large_date = {
  16075. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  16076. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  16077. ASSERT_TRUE(res_bad);
  16078. // Expect server to treat this as invalid/mismatch and return full content
  16079. EXPECT_EQ(200, res_bad->status);
  16080. // If-Range with extremely large date should be treated as mismatch -> full
  16081. // content (200)
  16082. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  16083. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  16084. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  16085. ASSERT_TRUE(res_ifrange);
  16086. EXPECT_EQ(200, res_ifrange->status);
  16087. svr.stop();
  16088. t.join();
  16089. std::remove(fname);
  16090. }
  16091. TEST(ETagTest, NegativeFileModificationTime) {
  16092. using namespace httplib;
  16093. const char *fname = "ims_negative_mtime.txt";
  16094. const std::string content = "negative-mtime";
  16095. {
  16096. std::ofstream ofs(fname);
  16097. ofs << content;
  16098. ASSERT_TRUE(ofs.good());
  16099. }
  16100. // Try to set file mtime to a negative value. This may fail on some
  16101. // platforms/filesystems; if it fails, the test will still verify server
  16102. // behaves safely by performing a regular conditional request.
  16103. #if defined(__APPLE__) || defined(__linux__)
  16104. bool set_negative = false;
  16105. do {
  16106. struct timeval times[2];
  16107. // access time: now
  16108. times[0].tv_sec = time(nullptr);
  16109. times[0].tv_usec = 0;
  16110. // modification time: negative (e.g., -1)
  16111. times[1].tv_sec = -1;
  16112. times[1].tv_usec = 0;
  16113. if (utimes(fname, times) == 0) { set_negative = true; }
  16114. } while (0);
  16115. #else
  16116. bool set_negative = false;
  16117. #endif
  16118. Server svr;
  16119. svr.set_mount_point("/static", ".");
  16120. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16121. svr.wait_until_ready();
  16122. Client cli(HOST, PORT);
  16123. auto res1 = cli.Get(std::string("/static/") + fname);
  16124. ASSERT_TRUE(res1);
  16125. ASSERT_EQ(200, res1->status);
  16126. bool has_last_modified = res1->has_header("Last-Modified");
  16127. std::string last_modified;
  16128. if (has_last_modified) {
  16129. last_modified = res1->get_header_value("Last-Modified");
  16130. }
  16131. if (set_negative) {
  16132. // If we successfully set a negative mtime, ensure server returns a
  16133. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  16134. // with an old date and ensure server handles it without crash.
  16135. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  16136. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  16137. ASSERT_TRUE(res2);
  16138. // Behavior may vary; at minimum ensure server responds (200 or 304).
  16139. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  16140. } else {
  16141. // Could not set negative mtime on this platform; fall back to verifying
  16142. // that normal invalid/malformed dates are treated safely (non-304).
  16143. Headers h_bad_date = {
  16144. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  16145. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  16146. ASSERT_TRUE(res_bad);
  16147. EXPECT_EQ(200, res_bad->status);
  16148. }
  16149. svr.stop();
  16150. t.join();
  16151. std::remove(fname);
  16152. }
  16153. //==============================================================================
  16154. // SSE Parsing Tests
  16155. //==============================================================================
  16156. class SSEParsingTest : public ::testing::Test {
  16157. protected:
  16158. // Test helper that mimics SSE parsing behavior
  16159. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  16160. int &retry_ms) {
  16161. // Blank line signals end of event
  16162. if (line.empty() || line == "\r") { return true; }
  16163. // Lines starting with ':' are comments (ignored)
  16164. if (!line.empty() && line[0] == ':') { return false; }
  16165. // Find the colon separator
  16166. auto colon_pos = line.find(':');
  16167. if (colon_pos == std::string::npos) {
  16168. // Line with no colon is treated as field name with empty value
  16169. return false;
  16170. }
  16171. std::string field = line.substr(0, colon_pos);
  16172. std::string value;
  16173. // Value starts after colon, skip optional single space
  16174. if (colon_pos + 1 < line.size()) {
  16175. size_t value_start = colon_pos + 1;
  16176. if (line[value_start] == ' ') { value_start++; }
  16177. value = line.substr(value_start);
  16178. // Remove trailing \r if present
  16179. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  16180. }
  16181. // Handle known fields
  16182. if (field == "event") {
  16183. msg.event = value;
  16184. } else if (field == "data") {
  16185. // Multiple data lines are concatenated with newlines
  16186. if (!msg.data.empty()) { msg.data += "\n"; }
  16187. msg.data += value;
  16188. } else if (field == "id") {
  16189. // Empty id is valid (clears the last event ID)
  16190. msg.id = value;
  16191. } else if (field == "retry") {
  16192. // Parse retry interval in milliseconds
  16193. {
  16194. int v = 0;
  16195. auto res =
  16196. detail::from_chars(value.data(), value.data() + value.size(), v);
  16197. if (res.ec == std::errc{}) { retry_ms = v; }
  16198. }
  16199. }
  16200. // Unknown fields are ignored per SSE spec
  16201. return false;
  16202. }
  16203. };
  16204. // Test: Single-line data
  16205. TEST_F(SSEParsingTest, SingleLineData) {
  16206. sse::SSEMessage msg;
  16207. int retry_ms = 3000;
  16208. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  16209. EXPECT_EQ(msg.data, "hello");
  16210. EXPECT_EQ(msg.event, "message");
  16211. // Blank line ends event
  16212. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  16213. }
  16214. // Test: Multi-line data
  16215. TEST_F(SSEParsingTest, MultiLineData) {
  16216. sse::SSEMessage msg;
  16217. int retry_ms = 3000;
  16218. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  16219. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  16220. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  16221. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  16222. }
  16223. // Test: Custom event types
  16224. TEST_F(SSEParsingTest, CustomEventType) {
  16225. sse::SSEMessage msg;
  16226. int retry_ms = 3000;
  16227. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  16228. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  16229. EXPECT_EQ(msg.event, "update");
  16230. EXPECT_EQ(msg.data, "payload");
  16231. }
  16232. // Test: Event ID handling
  16233. TEST_F(SSEParsingTest, EventIdHandling) {
  16234. sse::SSEMessage msg;
  16235. int retry_ms = 3000;
  16236. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  16237. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  16238. EXPECT_EQ(msg.id, "12345");
  16239. }
  16240. // Test: Empty event ID (clears last event ID)
  16241. TEST_F(SSEParsingTest, EmptyEventId) {
  16242. sse::SSEMessage msg;
  16243. msg.id = "previous";
  16244. int retry_ms = 3000;
  16245. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  16246. EXPECT_EQ(msg.id, "");
  16247. }
  16248. // Test: Retry field parsing
  16249. TEST_F(SSEParsingTest, RetryFieldParsing) {
  16250. sse::SSEMessage msg;
  16251. int retry_ms = 3000;
  16252. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  16253. EXPECT_EQ(retry_ms, 5000);
  16254. }
  16255. // Test: Invalid retry value
  16256. TEST_F(SSEParsingTest, InvalidRetryValue) {
  16257. sse::SSEMessage msg;
  16258. int retry_ms = 3000;
  16259. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  16260. EXPECT_EQ(retry_ms, 3000); // Unchanged
  16261. }
  16262. // Test: Comments (lines starting with :)
  16263. TEST_F(SSEParsingTest, CommentsIgnored) {
  16264. sse::SSEMessage msg;
  16265. int retry_ms = 3000;
  16266. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  16267. EXPECT_EQ(msg.data, "");
  16268. EXPECT_EQ(msg.event, "message");
  16269. }
  16270. // Test: Colon in value
  16271. TEST_F(SSEParsingTest, ColonInValue) {
  16272. sse::SSEMessage msg;
  16273. int retry_ms = 3000;
  16274. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  16275. EXPECT_EQ(msg.data, "hello:world:test");
  16276. }
  16277. // Test: Line with no colon (field name only)
  16278. TEST_F(SSEParsingTest, FieldNameOnly) {
  16279. sse::SSEMessage msg;
  16280. int retry_ms = 3000;
  16281. // According to SSE spec, this is treated as field name with empty value
  16282. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  16283. // Since we don't recognize "data" without colon, data should be empty
  16284. EXPECT_EQ(msg.data, "");
  16285. }
  16286. // Test: Trailing \r handling
  16287. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  16288. sse::SSEMessage msg;
  16289. int retry_ms = 3000;
  16290. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  16291. EXPECT_EQ(msg.data, "hello");
  16292. }
  16293. // Test: Unknown fields ignored
  16294. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  16295. sse::SSEMessage msg;
  16296. int retry_ms = 3000;
  16297. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  16298. EXPECT_EQ(msg.data, "");
  16299. EXPECT_EQ(msg.event, "message");
  16300. }
  16301. // Test: Space after colon is optional
  16302. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  16303. sse::SSEMessage msg1, msg2;
  16304. int retry_ms = 3000;
  16305. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  16306. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  16307. EXPECT_EQ(msg1.data, "hello");
  16308. EXPECT_EQ(msg2.data, "hello");
  16309. }
  16310. // Test: SSEMessage clear
  16311. TEST_F(SSEParsingTest, MessageClear) {
  16312. sse::SSEMessage msg;
  16313. msg.event = "custom";
  16314. msg.data = "some data";
  16315. msg.id = "123";
  16316. msg.clear();
  16317. EXPECT_EQ(msg.event, "message");
  16318. EXPECT_EQ(msg.data, "");
  16319. EXPECT_EQ(msg.id, "");
  16320. }
  16321. // Test: Complete event parsing
  16322. TEST_F(SSEParsingTest, CompleteEventParsing) {
  16323. sse::SSEMessage msg;
  16324. int retry_ms = 3000;
  16325. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  16326. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  16327. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  16328. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  16329. // Blank line ends event
  16330. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  16331. EXPECT_EQ(msg.event, "notification");
  16332. EXPECT_EQ(msg.id, "evt-42");
  16333. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  16334. EXPECT_EQ(retry_ms, 1000);
  16335. }
  16336. //==============================================================================
  16337. // Integration Tests with Server
  16338. //==============================================================================
  16339. class SSEIntegrationTest : public ::testing::Test {
  16340. protected:
  16341. void SetUp() override {
  16342. stop_server_.store(false);
  16343. events_.clear();
  16344. server_ = httplib::detail::make_unique<Server>();
  16345. setup_server();
  16346. start_server();
  16347. }
  16348. void TearDown() override {
  16349. stop_server_.store(true);
  16350. event_cv_.notify_all();
  16351. server_->stop();
  16352. if (server_thread_.joinable()) { server_thread_.join(); }
  16353. }
  16354. void setup_server() {
  16355. // Simple SSE endpoint
  16356. server_->Get("/events", [this](const Request &req, Response &res) {
  16357. auto last_id = req.get_header_value("Last-Event-ID");
  16358. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  16359. res.set_chunked_content_provider(
  16360. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  16361. std::unique_lock<std::mutex> lock(event_mutex_);
  16362. if (event_cv_.wait_for(
  16363. lock, std::chrono::milliseconds(200), [this] {
  16364. return !events_.empty() || stop_server_.load();
  16365. })) {
  16366. if (stop_server_.load()) { return false; }
  16367. if (!events_.empty()) {
  16368. std::string event = events_.front();
  16369. events_.erase(events_.begin());
  16370. sink.write(event.data(), event.size());
  16371. return true;
  16372. }
  16373. }
  16374. return !stop_server_.load();
  16375. });
  16376. });
  16377. // Endpoint that returns error
  16378. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  16379. res.status = 500;
  16380. res.set_content("Internal Server Error", "text/plain");
  16381. });
  16382. // Endpoint for custom event types
  16383. server_->Get("/custom-events", [](const Request &, Response &res) {
  16384. res.set_chunked_content_provider(
  16385. "text/event-stream", [](size_t offset, DataSink &sink) {
  16386. if (offset == 0) {
  16387. std::string event = "event: update\ndata: updated\n\n"
  16388. "event: delete\ndata: deleted\n\n";
  16389. sink.write(event.data(), event.size());
  16390. }
  16391. return false; // End stream after sending
  16392. });
  16393. });
  16394. }
  16395. void start_server() {
  16396. port_ = server_->bind_to_any_port(HOST);
  16397. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  16398. // Wait for server to start
  16399. while (!server_->is_running()) {
  16400. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16401. }
  16402. }
  16403. int get_port() const { return port_; }
  16404. void send_event(const std::string &event) {
  16405. std::lock_guard<std::mutex> lock(event_mutex_);
  16406. events_.push_back(event);
  16407. event_cv_.notify_all();
  16408. }
  16409. std::unique_ptr<Server> server_;
  16410. std::thread server_thread_;
  16411. std::mutex event_mutex_;
  16412. std::condition_variable event_cv_;
  16413. std::vector<std::string> events_;
  16414. std::atomic<bool> stop_server_{false};
  16415. std::string last_received_event_id_;
  16416. int port_ = 0;
  16417. };
  16418. // Test: Successful connection and on_open callback
  16419. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  16420. // Add a simple endpoint that sends one event and closes
  16421. server_->Get("/simple-event", [](const Request &, Response &res) {
  16422. res.set_chunked_content_provider(
  16423. "text/event-stream", [](size_t offset, DataSink &sink) {
  16424. if (offset == 0) {
  16425. std::string event = "data: hello\n\n";
  16426. sink.write(event.data(), event.size());
  16427. }
  16428. return false; // Close stream after sending
  16429. });
  16430. });
  16431. Client client("localhost", get_port());
  16432. sse::SSEClient sse(client, "/simple-event");
  16433. std::atomic<bool> open_called{false};
  16434. std::atomic<bool> message_received{false};
  16435. sse.on_open([&open_called]() { open_called.store(true); });
  16436. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  16437. if (msg.data == "hello") { message_received.store(true); }
  16438. });
  16439. sse.set_reconnect_interval(100);
  16440. sse.set_max_reconnect_attempts(1);
  16441. // Start async
  16442. sse.start_async();
  16443. // Wait for message to be processed
  16444. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  16445. sse.stop();
  16446. EXPECT_TRUE(open_called.load());
  16447. EXPECT_TRUE(message_received.load());
  16448. }
  16449. // Test: on_message callback
  16450. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  16451. // Endpoint that sends multiple events then closes
  16452. server_->Get("/multi-event", [](const Request &, Response &res) {
  16453. res.set_chunked_content_provider(
  16454. "text/event-stream", [](size_t offset, DataSink &sink) {
  16455. if (offset == 0) {
  16456. std::string events = "data: message1\n\ndata: message2\n\n";
  16457. sink.write(events.data(), events.size());
  16458. }
  16459. return false;
  16460. });
  16461. });
  16462. Client client("localhost", get_port());
  16463. sse::SSEClient sse(client, "/multi-event");
  16464. std::vector<std::string> received_messages;
  16465. std::mutex messages_mutex;
  16466. sse.on_message([&](const sse::SSEMessage &msg) {
  16467. std::lock_guard<std::mutex> lock(messages_mutex);
  16468. received_messages.push_back(msg.data);
  16469. });
  16470. sse.set_reconnect_interval(100);
  16471. sse.set_max_reconnect_attempts(1);
  16472. sse.start_async();
  16473. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  16474. sse.stop();
  16475. std::lock_guard<std::mutex> lock(messages_mutex);
  16476. EXPECT_GE(received_messages.size(), 2u);
  16477. if (received_messages.size() >= 2) {
  16478. EXPECT_EQ(received_messages[0], "message1");
  16479. EXPECT_EQ(received_messages[1], "message2");
  16480. }
  16481. }
  16482. // Test: on_event for specific types
  16483. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  16484. Client client("localhost", get_port());
  16485. sse::SSEClient sse(client, "/custom-events");
  16486. std::atomic<bool> update_received{false};
  16487. std::atomic<bool> delete_received{false};
  16488. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  16489. if (msg.data == "updated") { update_received.store(true); }
  16490. });
  16491. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  16492. if (msg.data == "deleted") { delete_received.store(true); }
  16493. });
  16494. sse.set_max_reconnect_attempts(1);
  16495. sse.start_async();
  16496. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  16497. sse.stop();
  16498. EXPECT_TRUE(update_received.load());
  16499. EXPECT_TRUE(delete_received.load());
  16500. }
  16501. // Test: on_error callback on connection failure
  16502. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  16503. // Connect to a non-existent port
  16504. Client client("localhost", 59999);
  16505. sse::SSEClient sse(client, "/events");
  16506. std::atomic<bool> error_called{false};
  16507. Error received_error = Error::Success;
  16508. sse.on_error([&](Error err) {
  16509. error_called.store(true);
  16510. received_error = err;
  16511. });
  16512. sse.set_reconnect_interval(50);
  16513. sse.set_max_reconnect_attempts(1);
  16514. sse.start_async();
  16515. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  16516. sse.stop();
  16517. EXPECT_TRUE(error_called.load());
  16518. EXPECT_NE(received_error, Error::Success);
  16519. }
  16520. // Test: Last-Event-ID header sent on reconnect
  16521. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  16522. // Endpoint that sends event with ID
  16523. server_->Get("/event-with-id", [](const Request &, Response &res) {
  16524. res.set_chunked_content_provider(
  16525. "text/event-stream", [](size_t offset, DataSink &sink) {
  16526. if (offset == 0) {
  16527. std::string event = "id: evt-123\ndata: test\n\n";
  16528. sink.write(event.data(), event.size());
  16529. }
  16530. return false;
  16531. });
  16532. });
  16533. Client client("localhost", get_port());
  16534. sse::SSEClient sse(client, "/event-with-id");
  16535. std::atomic<bool> id_received{false};
  16536. sse.on_message([&](const sse::SSEMessage &msg) {
  16537. if (!msg.id.empty()) { id_received.store(true); }
  16538. });
  16539. sse.set_reconnect_interval(100);
  16540. sse.set_max_reconnect_attempts(1);
  16541. sse.start_async();
  16542. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  16543. sse.stop();
  16544. EXPECT_TRUE(id_received.load());
  16545. EXPECT_EQ(sse.last_event_id(), "evt-123");
  16546. }
  16547. // Test: Manual stop
  16548. TEST_F(SSEIntegrationTest, ManualStop) {
  16549. // Endpoint that sends one event and stays open briefly
  16550. std::atomic<bool> handler_running{true};
  16551. server_->Get("/stay-open", [&handler_running](const Request &,
  16552. Response &res) {
  16553. res.set_chunked_content_provider(
  16554. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  16555. if (offset == 0) {
  16556. std::string event = "data: connected\n\n";
  16557. sink.write(event.data(), event.size());
  16558. }
  16559. // Keep connection open while handler_running is true
  16560. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  16561. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  16562. }
  16563. return false;
  16564. });
  16565. });
  16566. Client client("localhost", get_port());
  16567. sse::SSEClient sse(client, "/stay-open");
  16568. std::atomic<bool> connected{false};
  16569. sse.on_open([&connected]() { connected.store(true); });
  16570. sse.set_reconnect_interval(100);
  16571. sse.set_max_reconnect_attempts(1);
  16572. sse.start_async();
  16573. // Wait for connection to establish
  16574. for (int i = 0; i < 20 && !connected.load(); ++i) {
  16575. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  16576. }
  16577. EXPECT_TRUE(connected.load());
  16578. EXPECT_TRUE(sse.is_connected());
  16579. // Signal handler to stop
  16580. handler_running.store(false);
  16581. // Stop SSE client
  16582. sse.stop();
  16583. EXPECT_FALSE(sse.is_connected());
  16584. }
  16585. // Test: SSEClient with custom headers
  16586. TEST_F(SSEIntegrationTest, CustomHeaders) {
  16587. // Setup a server endpoint that checks for custom header
  16588. std::atomic<bool> header_received{false};
  16589. server_->Get("/header-check", [&](const Request &req, Response &res) {
  16590. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  16591. header_received.store(true);
  16592. }
  16593. res.set_chunked_content_provider("text/event-stream",
  16594. [](size_t, DataSink &) { return false; });
  16595. });
  16596. Client client("localhost", get_port());
  16597. Headers headers = {{"X-Custom-Header", "custom-value"}};
  16598. sse::SSEClient sse(client, "/header-check", headers);
  16599. sse.set_max_reconnect_attempts(1);
  16600. sse.start_async();
  16601. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  16602. sse.stop();
  16603. EXPECT_TRUE(header_received.load());
  16604. }
  16605. // Test: Reconnect interval configuration
  16606. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  16607. Client client("localhost", get_port());
  16608. sse::SSEClient sse(client, "/events");
  16609. auto &result = sse.set_reconnect_interval(500);
  16610. // Builder pattern should return reference to self
  16611. EXPECT_EQ(&result, &sse);
  16612. }
  16613. // Test: Max reconnect attempts
  16614. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  16615. // Connect to non-existent port to force reconnects
  16616. Client client("localhost", 59998);
  16617. sse::SSEClient sse(client, "/events");
  16618. std::atomic<int> error_count{0};
  16619. sse.on_error([&](Error) { error_count.fetch_add(1); });
  16620. sse.set_reconnect_interval(50);
  16621. sse.set_max_reconnect_attempts(2);
  16622. auto start = std::chrono::steady_clock::now();
  16623. sse.start(); // Blocking call
  16624. auto end = std::chrono::steady_clock::now();
  16625. // Should have stopped after 2 failed attempts
  16626. EXPECT_GE(error_count.load(), 2);
  16627. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  16628. auto duration =
  16629. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  16630. #ifdef _WIN32
  16631. // Windows is much slower for socket connection failures
  16632. EXPECT_LT(duration.count(), 7000);
  16633. #else
  16634. EXPECT_LT(duration.count(), 1000);
  16635. #endif
  16636. }
  16637. // Test: Multi-line data in integration
  16638. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  16639. // Endpoint with multi-line data
  16640. server_->Get("/multiline-data", [](const Request &, Response &res) {
  16641. res.set_chunked_content_provider(
  16642. "text/event-stream", [](size_t offset, DataSink &sink) {
  16643. if (offset == 0) {
  16644. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  16645. sink.write(event.data(), event.size());
  16646. }
  16647. return false;
  16648. });
  16649. });
  16650. Client client("localhost", get_port());
  16651. sse::SSEClient sse(client, "/multiline-data");
  16652. std::string received_data;
  16653. std::mutex data_mutex;
  16654. sse.on_message([&](const sse::SSEMessage &msg) {
  16655. std::lock_guard<std::mutex> lock(data_mutex);
  16656. received_data = msg.data;
  16657. });
  16658. sse.set_reconnect_interval(100);
  16659. sse.set_max_reconnect_attempts(1);
  16660. sse.start_async();
  16661. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  16662. sse.stop();
  16663. std::lock_guard<std::mutex> lock(data_mutex);
  16664. EXPECT_EQ(received_data, "line1\nline2\nline3");
  16665. }
  16666. // Test: Auto-reconnect after server disconnection
  16667. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  16668. std::atomic<int> connection_count{0};
  16669. std::atomic<int> message_count{0};
  16670. // Endpoint that sends one event and closes, forcing reconnect
  16671. server_->Get("/reconnect-test",
  16672. [&connection_count](const Request &, Response &res) {
  16673. connection_count.fetch_add(1);
  16674. res.set_chunked_content_provider(
  16675. "text/event-stream", [](size_t offset, DataSink &sink) {
  16676. if (offset == 0) {
  16677. std::string event = "data: hello\n\n";
  16678. sink.write(event.data(), event.size());
  16679. }
  16680. return false; // Close connection after sending
  16681. });
  16682. });
  16683. Client client("localhost", get_port());
  16684. sse::SSEClient sse(client, "/reconnect-test");
  16685. sse.on_message([&message_count](const sse::SSEMessage &) {
  16686. message_count.fetch_add(1);
  16687. });
  16688. sse.set_reconnect_interval(100);
  16689. sse.set_max_reconnect_attempts(3);
  16690. sse.start_async();
  16691. // Wait long enough for multiple reconnects
  16692. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  16693. sse.stop();
  16694. // Should have connected multiple times (initial + reconnects)
  16695. EXPECT_GE(connection_count.load(), 2);
  16696. // Should have received messages from multiple connections
  16697. EXPECT_GE(message_count.load(), 2);
  16698. }
  16699. // Test: Last-Event-ID sent on reconnect
  16700. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  16701. std::atomic<int> connection_count{0};
  16702. std::vector<std::string> received_last_event_ids;
  16703. std::mutex id_mutex;
  16704. // Endpoint that checks Last-Event-ID header and sends event with ID
  16705. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  16706. int conn = connection_count.fetch_add(1);
  16707. // Capture the Last-Event-ID header from each connection
  16708. {
  16709. std::lock_guard<std::mutex> lock(id_mutex);
  16710. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  16711. }
  16712. res.set_chunked_content_provider(
  16713. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  16714. if (offset == 0) {
  16715. std::string event =
  16716. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  16717. sink.write(event.data(), event.size());
  16718. }
  16719. return false;
  16720. });
  16721. });
  16722. Client client("localhost", get_port());
  16723. sse::SSEClient sse(client, "/reconnect-with-id");
  16724. sse.set_reconnect_interval(100);
  16725. sse.set_max_reconnect_attempts(3);
  16726. sse.start_async();
  16727. // Wait for at least 2 connections
  16728. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  16729. sse.stop();
  16730. // Verify behavior
  16731. std::lock_guard<std::mutex> lock(id_mutex);
  16732. EXPECT_GE(received_last_event_ids.size(), 2u);
  16733. // First connection should have no Last-Event-ID
  16734. if (!received_last_event_ids.empty()) {
  16735. EXPECT_EQ(received_last_event_ids[0], "");
  16736. }
  16737. // Second connection should have Last-Event-ID from first connection
  16738. if (received_last_event_ids.size() >= 2) {
  16739. EXPECT_EQ(received_last_event_ids[1], "event-0");
  16740. }
  16741. }
  16742. // Test: set_headers updates headers used on reconnect
  16743. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  16744. std::vector<std::string> received_tokens;
  16745. std::mutex token_mutex;
  16746. // Endpoint that captures Authorization header
  16747. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  16748. {
  16749. std::lock_guard<std::mutex> lock(token_mutex);
  16750. received_tokens.push_back(req.get_header_value("Authorization"));
  16751. }
  16752. res.set_chunked_content_provider(
  16753. "text/event-stream", [](size_t offset, DataSink &sink) {
  16754. if (offset == 0) {
  16755. std::string event = "data: hello\n\n";
  16756. sink.write(event.data(), event.size());
  16757. }
  16758. return false; // Close connection to trigger reconnect
  16759. });
  16760. });
  16761. Client client("localhost", get_port());
  16762. Headers headers = {{"Authorization", "Bearer old-token"}};
  16763. sse::SSEClient sse(client, "/auth-check", headers);
  16764. // Update headers on each successful connection
  16765. sse.on_open(
  16766. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  16767. sse.set_reconnect_interval(100);
  16768. sse.set_max_reconnect_attempts(3);
  16769. sse.start_async();
  16770. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  16771. sse.stop();
  16772. std::lock_guard<std::mutex> lock(token_mutex);
  16773. ASSERT_GE(received_tokens.size(), 2u);
  16774. // First connection uses original header
  16775. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  16776. // Second connection uses updated header from set_headers
  16777. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  16778. }
  16779. // Test: 401 allows reconnection (so on_error can refresh headers)
  16780. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  16781. std::atomic<int> connection_count{0};
  16782. // Endpoint: returns 401 on first attempt, 200 on second
  16783. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  16784. int conn = connection_count.fetch_add(1);
  16785. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  16786. res.status = StatusCode::Unauthorized_401;
  16787. res.set_content("Unauthorized", "text/plain");
  16788. return;
  16789. }
  16790. res.set_chunked_content_provider(
  16791. "text/event-stream", [](size_t offset, DataSink &sink) {
  16792. if (offset == 0) {
  16793. std::string event = "data: authenticated\n\n";
  16794. sink.write(event.data(), event.size());
  16795. }
  16796. return false;
  16797. });
  16798. });
  16799. Client client("localhost", get_port());
  16800. Headers headers = {{"Authorization", "Bearer expired"}};
  16801. sse::SSEClient sse(client, "/auth-retry", headers);
  16802. std::atomic<bool> message_received{false};
  16803. // Refresh token on error
  16804. sse.on_error(
  16805. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  16806. sse.on_message([&](const sse::SSEMessage &msg) {
  16807. if (msg.data == "authenticated") { message_received.store(true); }
  16808. });
  16809. sse.set_reconnect_interval(100);
  16810. sse.set_max_reconnect_attempts(3);
  16811. sse.start_async();
  16812. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  16813. sse.stop();
  16814. // Should have reconnected after 401 and succeeded with new token
  16815. EXPECT_GE(connection_count.load(), 2);
  16816. EXPECT_TRUE(message_received.load());
  16817. }
  16818. TEST(Issue2318Test, EmptyHostString) {
  16819. {
  16820. httplib::Client cli_empty("", PORT);
  16821. auto res = cli_empty.Get("/");
  16822. ASSERT_FALSE(res);
  16823. EXPECT_EQ(httplib::Error::Connection, res.error());
  16824. }
  16825. {
  16826. httplib::Client cli(" ", PORT);
  16827. auto res = cli.Get("/");
  16828. ASSERT_FALSE(res);
  16829. EXPECT_EQ(httplib::Error::Connection, res.error());
  16830. }
  16831. }
  16832. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  16833. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  16834. Server svr;
  16835. // Set a small payload limit (1KB)
  16836. svr.set_payload_max_length(1024);
  16837. svr.Post("/test", [&](const Request &req, Response &res) {
  16838. res.set_content("Body size: " + std::to_string(req.body.size()),
  16839. "text/plain");
  16840. });
  16841. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16842. auto se = detail::scope_exit([&] {
  16843. svr.stop();
  16844. listen_thread.join();
  16845. });
  16846. svr.wait_until_ready();
  16847. // Create data that compresses well but exceeds limit when decompressed
  16848. // 8KB of repeated null bytes compresses to a very small size
  16849. std::string original_data(8 * 1024, '\0');
  16850. // Compress the data using gzip
  16851. std::string compressed_data;
  16852. detail::gzip_compressor compressor;
  16853. compressor.compress(original_data.data(), original_data.size(), true,
  16854. [&](const char *data, size_t size) {
  16855. compressed_data.append(data, size);
  16856. return true;
  16857. });
  16858. // Verify compression worked (compressed should be much smaller)
  16859. ASSERT_LT(compressed_data.size(), original_data.size());
  16860. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  16861. // Send compressed data with Content-Encoding: gzip
  16862. Client cli(HOST, PORT);
  16863. Headers headers = {{"Content-Encoding", "gzip"}};
  16864. auto res =
  16865. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  16866. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  16867. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16868. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  16869. }
  16870. #endif
  16871. // ============================================================================
  16872. // OpenSSL-Specific Tests
  16873. // ============================================================================
  16874. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  16875. X509 *readCertificate(const std::string &strFileName) {
  16876. std::ifstream inStream(strFileName);
  16877. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  16878. std::istreambuf_iterator<char>());
  16879. if (strCertPEM.empty()) return (nullptr);
  16880. BIO *pbCert = BIO_new(BIO_s_mem());
  16881. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  16882. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  16883. BIO_free(pbCert);
  16884. return (pCert);
  16885. }
  16886. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  16887. std::ifstream inStream(strFileName);
  16888. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  16889. std::istreambuf_iterator<char>());
  16890. if (strPrivateKeyPEM.empty()) return (nullptr);
  16891. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  16892. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  16893. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  16894. BIO_free(pbPrivKey);
  16895. return (pPrivateKey);
  16896. }
  16897. TEST(BindServerTest, UpdateCerts) {
  16898. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  16899. int port = svr.bind_to_any_port("0.0.0.0");
  16900. ASSERT_TRUE(svr.is_valid());
  16901. ASSERT_TRUE(port > 0);
  16902. X509 *cert = readCertificate(SERVER_CERT_FILE);
  16903. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  16904. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  16905. ASSERT_TRUE(cert != nullptr);
  16906. ASSERT_TRUE(ca_cert != nullptr);
  16907. ASSERT_TRUE(key != nullptr);
  16908. X509_STORE *cert_store = X509_STORE_new();
  16909. X509_STORE_add_cert(cert_store, ca_cert);
  16910. // svr.update_certs(cert, key, cert_store); // deprecated
  16911. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  16912. CLIENT_CA_CERT_FILE);
  16913. ASSERT_TRUE(svr.is_valid());
  16914. svr.stop();
  16915. X509_STORE_free(cert_store);
  16916. X509_free(cert);
  16917. X509_free(ca_cert);
  16918. EVP_PKEY_free(key);
  16919. }
  16920. // Test that update_certs() updates client CA list correctly
  16921. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  16922. // Start with file-based constructor
  16923. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16924. ASSERT_TRUE(svr.is_valid());
  16925. // Initially no client CA list should be set
  16926. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  16927. ASSERT_TRUE(ssl_ctx != nullptr);
  16928. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  16929. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  16930. EXPECT_EQ(0, count_before);
  16931. // Now update with client CA (PEM string)
  16932. std::string cert_pem, key_pem, ca_pem;
  16933. read_file(SERVER_CERT_FILE, cert_pem);
  16934. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  16935. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  16936. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  16937. ASSERT_TRUE(svr.is_valid());
  16938. // Now client CA list should be set
  16939. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  16940. ASSERT_TRUE(ca_list_after != nullptr);
  16941. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  16942. }
  16943. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  16944. // Test that the file-path SSLServer constructor properly sets the client CA
  16945. // list that is sent to clients during the TLS handshake (CertificateRequest)
  16946. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  16947. ASSERT_TRUE(svr.is_valid());
  16948. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  16949. ASSERT_TRUE(ssl_ctx != nullptr);
  16950. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  16951. ASSERT_TRUE(ca_list != nullptr);
  16952. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  16953. }
  16954. #endif
  16955. // ============================================================================
  16956. // MbedTLS-Specific Tests
  16957. // ============================================================================
  16958. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  16959. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  16960. using namespace httplib::tls;
  16961. // Track if callback was invoked
  16962. bool callback_invoked = false;
  16963. // The callback receives void* ctx which is actually MbedTlsContext*
  16964. // We can access the mbedtls_ssl_config via the context
  16965. auto setup_callback = [&callback_invoked](void *ctx) {
  16966. callback_invoked = true;
  16967. // Cast to MbedTlsContext* to access the ssl config
  16968. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  16969. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  16970. // Use static variables to hold certificate data (simplified for test)
  16971. static mbedtls_x509_crt own_cert;
  16972. static mbedtls_pk_context own_key;
  16973. static mbedtls_x509_crt ca_chain;
  16974. static bool initialized = false;
  16975. if (!initialized) {
  16976. mbedtls_x509_crt_init(&own_cert);
  16977. mbedtls_pk_init(&own_key);
  16978. mbedtls_x509_crt_init(&ca_chain);
  16979. // Load server certificate
  16980. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  16981. return false;
  16982. }
  16983. // Load server private key.
  16984. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  16985. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  16986. #if MBEDTLS_VERSION_MAJOR == 3
  16987. ,
  16988. mbedtls_ctr_drbg_random, nullptr
  16989. #endif
  16990. ) != 0) {
  16991. return false;
  16992. }
  16993. // Load CA chain for client verification
  16994. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  16995. return false;
  16996. }
  16997. initialized = true;
  16998. }
  16999. // Configure the SSL config
  17000. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  17001. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  17002. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  17003. // Set minimum TLS version using mbedTLS native API
  17004. #if MBEDTLS_VERSION_MAJOR >= 3
  17005. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  17006. #else
  17007. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  17008. MBEDTLS_SSL_MINOR_VERSION_3);
  17009. #endif
  17010. return true;
  17011. };
  17012. SSLServer svr(setup_callback);
  17013. ASSERT_TRUE(svr.is_valid());
  17014. ASSERT_TRUE(callback_invoked);
  17015. svr.Get("/test", [&](const Request &req, Response &res) {
  17016. res.set_content("test", "text/plain");
  17017. auto cert = req.peer_cert();
  17018. ASSERT_TRUE(static_cast<bool>(cert));
  17019. auto common_name = cert.subject_cn();
  17020. EXPECT_EQ("Common Name", common_name);
  17021. });
  17022. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  17023. auto se = detail::scope_exit([&] {
  17024. svr.stop();
  17025. t.join();
  17026. ASSERT_FALSE(svr.is_running());
  17027. });
  17028. svr.wait_until_ready();
  17029. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  17030. cli.enable_server_certificate_verification(false);
  17031. cli.set_connection_timeout(30);
  17032. auto res = cli.Get("/test");
  17033. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17034. ASSERT_EQ(StatusCode::OK_200, res->status);
  17035. }
  17036. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  17037. // context (owning mbedtls_ssl_config) before shutting down a still-open
  17038. // keep-alive SSL session, which reads through that config in
  17039. // mbedtls_ssl_close_notify.
  17040. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  17041. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17042. ASSERT_TRUE(svr.is_valid());
  17043. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  17044. res.set_content("test", "text/plain");
  17045. });
  17046. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  17047. auto se = detail::scope_exit([&] {
  17048. svr.stop();
  17049. t.join();
  17050. ASSERT_FALSE(svr.is_running());
  17051. });
  17052. svr.wait_until_ready();
  17053. {
  17054. SSLClient cli(HOST, PORT);
  17055. cli.enable_server_certificate_verification(false);
  17056. cli.set_keep_alive(true);
  17057. auto res = cli.Get("/test");
  17058. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17059. ASSERT_EQ(StatusCode::OK_200, res->status);
  17060. // cli is destructed here with the keep-alive SSL session still open.
  17061. }
  17062. }
  17063. #endif
  17064. // WebSocket Tests
  17065. TEST(WebSocketTest, RSVBitsMustBeZero) {
  17066. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  17067. // defining the meaning of these bits has been negotiated.
  17068. auto make_frame = [](uint8_t first_byte) {
  17069. std::string frame;
  17070. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  17071. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  17072. frame += "Hello";
  17073. return frame;
  17074. };
  17075. // RSV1 set (0x40)
  17076. {
  17077. detail::BufferStream strm;
  17078. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  17079. ws::Opcode opcode;
  17080. std::string payload;
  17081. bool fin;
  17082. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17083. false, 1024));
  17084. }
  17085. // RSV2 set (0x20)
  17086. {
  17087. detail::BufferStream strm;
  17088. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  17089. ws::Opcode opcode;
  17090. std::string payload;
  17091. bool fin;
  17092. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17093. false, 1024));
  17094. }
  17095. // RSV3 set (0x10)
  17096. {
  17097. detail::BufferStream strm;
  17098. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  17099. ws::Opcode opcode;
  17100. std::string payload;
  17101. bool fin;
  17102. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17103. false, 1024));
  17104. }
  17105. // No RSV bits set - should succeed
  17106. {
  17107. detail::BufferStream strm;
  17108. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  17109. ws::Opcode opcode;
  17110. std::string payload;
  17111. bool fin;
  17112. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17113. false, 1024));
  17114. EXPECT_EQ(ws::Opcode::Text, opcode);
  17115. EXPECT_EQ("Hello", payload);
  17116. EXPECT_TRUE(fin);
  17117. }
  17118. }
  17119. TEST(WebSocketTest, ControlFrameValidation) {
  17120. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  17121. // payload length <= 125.
  17122. // Ping with FIN=0 - must be rejected
  17123. {
  17124. detail::BufferStream strm;
  17125. std::string frame;
  17126. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  17127. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  17128. strm.write(frame.data(), frame.size());
  17129. ws::Opcode opcode;
  17130. std::string payload;
  17131. bool fin;
  17132. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17133. false, 1024));
  17134. }
  17135. // Close with FIN=0 - must be rejected
  17136. {
  17137. detail::BufferStream strm;
  17138. std::string frame;
  17139. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  17140. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  17141. strm.write(frame.data(), frame.size());
  17142. ws::Opcode opcode;
  17143. std::string payload;
  17144. bool fin;
  17145. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17146. false, 1024));
  17147. }
  17148. // Ping with payload_len=126 (extended length) - must be rejected
  17149. {
  17150. detail::BufferStream strm;
  17151. std::string frame;
  17152. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  17153. frame += static_cast<char>(126); // payload_len=126 (>125)
  17154. frame += static_cast<char>(0x00); // extended length high byte
  17155. frame += static_cast<char>(126); // extended length low byte
  17156. frame += std::string(126, 'x');
  17157. strm.write(frame.data(), frame.size());
  17158. ws::Opcode opcode;
  17159. std::string payload;
  17160. bool fin;
  17161. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17162. false, 1024));
  17163. }
  17164. // Ping with FIN=1 and payload_len=125 - should succeed
  17165. {
  17166. detail::BufferStream strm;
  17167. std::string frame;
  17168. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  17169. frame += static_cast<char>(125); // payload_len=125
  17170. frame += std::string(125, 'x');
  17171. strm.write(frame.data(), frame.size());
  17172. ws::Opcode opcode;
  17173. std::string payload;
  17174. bool fin;
  17175. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17176. false, 1024));
  17177. EXPECT_EQ(ws::Opcode::Ping, opcode);
  17178. EXPECT_EQ(125u, payload.size());
  17179. EXPECT_TRUE(fin);
  17180. }
  17181. }
  17182. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  17183. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  17184. // length MUST be 0.
  17185. // MSB set - must be rejected
  17186. {
  17187. detail::BufferStream strm;
  17188. std::string frame;
  17189. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  17190. frame += static_cast<char>(127); // 64-bit extended length
  17191. frame += static_cast<char>(0x80); // MSB set (invalid)
  17192. frame += std::string(7, '\0'); // remaining 7 bytes of length
  17193. strm.write(frame.data(), frame.size());
  17194. ws::Opcode opcode;
  17195. std::string payload;
  17196. bool fin;
  17197. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17198. false, 1024));
  17199. }
  17200. // MSB clear - should pass length parsing (will be rejected by max_len,
  17201. // but that's a different check; use a small length to verify)
  17202. {
  17203. detail::BufferStream strm;
  17204. std::string frame;
  17205. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  17206. frame += static_cast<char>(127); // 64-bit extended length
  17207. frame += std::string(7, '\0'); // high bytes = 0
  17208. frame += static_cast<char>(0x03); // length = 3
  17209. frame += "abc";
  17210. strm.write(frame.data(), frame.size());
  17211. ws::Opcode opcode;
  17212. std::string payload;
  17213. bool fin;
  17214. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17215. false, 1024));
  17216. EXPECT_EQ(ws::Opcode::Text, opcode);
  17217. EXPECT_EQ("abc", payload);
  17218. }
  17219. }
  17220. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  17221. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  17222. // Valid UTF-8
  17223. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  17224. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  17225. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  17226. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  17227. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  17228. // Invalid UTF-8
  17229. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  17230. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  17231. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  17232. EXPECT_FALSE(
  17233. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  17234. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  17235. }
  17236. TEST(WebSocketTest, ConnectAndDisconnect) {
  17237. Server svr;
  17238. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  17239. std::string msg;
  17240. while (ws.read(msg)) {}
  17241. });
  17242. auto port = svr.bind_to_any_port(HOST);
  17243. std::thread t([&]() { svr.listen_after_bind(); });
  17244. svr.wait_until_ready();
  17245. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  17246. auto res = client.connect();
  17247. ASSERT_TRUE(res);
  17248. EXPECT_EQ(Error::Success, res.error());
  17249. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  17250. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  17251. EXPECT_TRUE(client.is_open());
  17252. client.close();
  17253. EXPECT_FALSE(client.is_open());
  17254. svr.stop();
  17255. t.join();
  17256. }
  17257. TEST(WebSocketTest, ValidURL) {
  17258. ws::WebSocketClient ws1("ws://localhost:8080/path");
  17259. EXPECT_TRUE(ws1.is_valid());
  17260. ws::WebSocketClient ws2("ws://example.com/path");
  17261. EXPECT_TRUE(ws2.is_valid());
  17262. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  17263. EXPECT_TRUE(ws3.is_valid());
  17264. #ifdef CPPHTTPLIB_SSL_ENABLED
  17265. ws::WebSocketClient wss1("wss://example.com/path");
  17266. EXPECT_TRUE(wss1.is_valid());
  17267. ws::WebSocketClient wss2("wss://example.com:443/path");
  17268. EXPECT_TRUE(wss2.is_valid());
  17269. #endif
  17270. }
  17271. TEST(WebSocketTest, InvalidURL) {
  17272. // No scheme
  17273. ws::WebSocketClient ws1("localhost:8080/path");
  17274. EXPECT_FALSE(ws1.is_valid());
  17275. // No path
  17276. ws::WebSocketClient ws2("ws://localhost:8080");
  17277. EXPECT_FALSE(ws2.is_valid());
  17278. // Empty string
  17279. ws::WebSocketClient ws3("");
  17280. EXPECT_FALSE(ws3.is_valid());
  17281. // Missing host
  17282. ws::WebSocketClient ws4("ws://:8080/path");
  17283. EXPECT_FALSE(ws4.is_valid());
  17284. // Port number overflow — should not crash
  17285. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  17286. EXPECT_FALSE(ws5.is_valid());
  17287. // Port out of range
  17288. ws::WebSocketClient ws6("ws://localhost:99999/path");
  17289. EXPECT_FALSE(ws6.is_valid());
  17290. }
  17291. TEST(WebSocketTest, UnsupportedScheme) {
  17292. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  17293. ws::WebSocketClient ws1("http://localhost:8080/path");
  17294. EXPECT_FALSE(ws1.is_valid());
  17295. ws::WebSocketClient ws2("https://localhost:8080/path");
  17296. EXPECT_FALSE(ws2.is_valid());
  17297. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  17298. EXPECT_FALSE(ws3.is_valid());
  17299. #else
  17300. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  17301. std::invalid_argument);
  17302. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  17303. std::invalid_argument);
  17304. #endif
  17305. }
  17306. TEST(WebSocketTest, ConnectWhenInvalid) {
  17307. ws::WebSocketClient ws("not a valid url");
  17308. EXPECT_FALSE(ws.is_valid());
  17309. auto res = ws.connect();
  17310. EXPECT_FALSE(res);
  17311. EXPECT_EQ(Error::Connection, res.error());
  17312. EXPECT_EQ(-1, res.status());
  17313. }
  17314. TEST(WebSocketTest, ConnectRefusedReportsError) {
  17315. // Grab a port that is free, then close it again so nothing listens there
  17316. Server svr;
  17317. auto port = svr.bind_to_any_port(HOST);
  17318. svr.stop();
  17319. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  17320. auto res = client.connect();
  17321. ASSERT_FALSE(res);
  17322. EXPECT_EQ(Error::Connection, res.error());
  17323. EXPECT_EQ(-1, res.status());
  17324. }
  17325. TEST(WebSocketTest, DefaultPort) {
  17326. ws::WebSocketClient ws1("ws://example.com/path");
  17327. EXPECT_TRUE(ws1.is_valid());
  17328. // ws:// defaults to port 80 (verified by successful parse)
  17329. #ifdef CPPHTTPLIB_SSL_ENABLED
  17330. ws::WebSocketClient ws2("wss://example.com/path");
  17331. EXPECT_TRUE(ws2.is_valid());
  17332. // wss:// defaults to port 443 (verified by successful parse)
  17333. #endif
  17334. }
  17335. TEST(WebSocketTest, IPv6LiteralAddress) {
  17336. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  17337. EXPECT_TRUE(ws1.is_valid());
  17338. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  17339. EXPECT_TRUE(ws2.is_valid());
  17340. }
  17341. TEST(WebSocketTest, ComplexPath) {
  17342. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  17343. EXPECT_TRUE(ws1.is_valid());
  17344. ws::WebSocketClient ws2("ws://localhost:8080/");
  17345. EXPECT_TRUE(ws2.is_valid());
  17346. }
  17347. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  17348. Server svr;
  17349. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  17350. std::string msg;
  17351. while (ws.read(msg)) {}
  17352. });
  17353. auto port = svr.bind_to_any_port(HOST);
  17354. std::thread t([&]() { svr.listen_after_bind(); });
  17355. svr.wait_until_ready();
  17356. auto another_host = "example.com";
  17357. auto wrong_ip = "192.0.2.1";
  17358. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  17359. client.set_hostname_addr_map({{another_host, wrong_ip}});
  17360. ASSERT_TRUE(client.connect());
  17361. EXPECT_TRUE(client.is_open());
  17362. client.close();
  17363. svr.stop();
  17364. t.join();
  17365. }
  17366. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  17367. Server svr;
  17368. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  17369. std::string msg;
  17370. while (ws.read(msg)) {}
  17371. });
  17372. auto port = svr.bind_to_any_port(HOST);
  17373. std::thread t([&]() { svr.listen_after_bind(); });
  17374. svr.wait_until_ready();
  17375. auto wrong_ip = "192.0.2.1";
  17376. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  17377. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  17378. client.set_connection_timeout(1);
  17379. client.set_read_timeout(1);
  17380. client.set_write_timeout(1);
  17381. EXPECT_FALSE(client.connect());
  17382. EXPECT_FALSE(client.is_open());
  17383. svr.stop();
  17384. t.join();
  17385. }
  17386. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  17387. // A mapped value that is not an IP literal must be resolved. HOST resolves
  17388. // from the hosts file, so this test needs no external DNS. "target.invalid"
  17389. // (RFC 6761) is only a map key and the Host header value.
  17390. auto host = "target.invalid";
  17391. Server svr;
  17392. std::string received_host;
  17393. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  17394. received_host = req.get_header_value("Host");
  17395. std::string msg;
  17396. while (ws.read(msg)) {}
  17397. });
  17398. auto port = svr.bind_to_any_port(HOST);
  17399. std::thread t([&]() { svr.listen_after_bind(); });
  17400. // ASSERT_* below returns from the test body, which would leave t joinable
  17401. // and make ~thread call std::terminate.
  17402. auto se = detail::scope_exit([&] {
  17403. svr.stop();
  17404. if (t.joinable()) { t.join(); }
  17405. });
  17406. svr.wait_until_ready();
  17407. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  17408. std::to_string(port) + "/ws");
  17409. client.set_hostname_addr_map({{host, HOST}});
  17410. ASSERT_TRUE(client.connect());
  17411. EXPECT_TRUE(client.is_open());
  17412. client.close();
  17413. svr.stop();
  17414. t.join();
  17415. // The mapping only redirects the connection; the identity stays host_.
  17416. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  17417. }
  17418. class WebSocketIntegrationTest : public ::testing::Test {
  17419. protected:
  17420. void SetUp() override {
  17421. server_ = httplib::detail::make_unique<Server>();
  17422. setup_server();
  17423. start_server();
  17424. }
  17425. void TearDown() override {
  17426. server_->stop();
  17427. if (server_thread_.joinable()) { server_thread_.join(); }
  17428. }
  17429. void setup_server() {
  17430. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  17431. std::string msg;
  17432. ws::ReadResult ret;
  17433. while ((ret = ws.read(msg))) {
  17434. if (ret == ws::Binary) {
  17435. ws.send(msg.data(), msg.size());
  17436. } else {
  17437. ws.send(msg);
  17438. }
  17439. }
  17440. });
  17441. server_->WebSocket("/ws-echo-string",
  17442. [](const Request &, ws::WebSocket &ws) {
  17443. std::string msg;
  17444. while (ws.read(msg)) {
  17445. ws.send("echo: " + msg);
  17446. }
  17447. });
  17448. server_->WebSocket(
  17449. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  17450. // Echo back request metadata
  17451. ws.send("path:" + req.path);
  17452. ws.send("header:" + req.get_header_value("X-Test-Header"));
  17453. std::string msg;
  17454. while (ws.read(msg)) {}
  17455. });
  17456. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  17457. std::string msg;
  17458. ws.read(msg); // wait for a message
  17459. ws.close();
  17460. });
  17461. server_->WebSocket("/ws-close-status",
  17462. [](const Request &, ws::WebSocket &ws) {
  17463. std::string msg;
  17464. ws.read(msg); // wait for a message
  17465. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  17466. });
  17467. server_->WebSocket(
  17468. "/ws-subprotocol",
  17469. [](const Request &, ws::WebSocket &ws) {
  17470. std::string msg;
  17471. while (ws.read(msg)) {
  17472. ws.send(msg);
  17473. }
  17474. },
  17475. [](const std::vector<std::string> &protocols) -> std::string {
  17476. for (const auto &p : protocols) {
  17477. if (p == "graphql-ws") { return p; }
  17478. }
  17479. return "";
  17480. });
  17481. }
  17482. void start_server() {
  17483. port_ = server_->bind_to_any_port(HOST);
  17484. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  17485. server_->wait_until_ready();
  17486. }
  17487. std::unique_ptr<Server> server_;
  17488. std::thread server_thread_;
  17489. int port_ = 0;
  17490. };
  17491. TEST_F(WebSocketIntegrationTest, TextEcho) {
  17492. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17493. "/ws-echo");
  17494. ASSERT_TRUE(client.connect());
  17495. ASSERT_TRUE(client.is_open());
  17496. ASSERT_TRUE(client.send("Hello WebSocket"));
  17497. std::string msg;
  17498. EXPECT_EQ(ws::Text, client.read(msg));
  17499. EXPECT_EQ("Hello WebSocket", msg);
  17500. client.close();
  17501. }
  17502. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  17503. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17504. "/ws-echo");
  17505. ASSERT_TRUE(client.connect());
  17506. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  17507. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  17508. std::string msg;
  17509. EXPECT_EQ(ws::Binary, client.read(msg));
  17510. EXPECT_EQ(binary_data, msg);
  17511. client.close();
  17512. }
  17513. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  17514. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17515. "/ws-echo");
  17516. ASSERT_TRUE(client.connect());
  17517. for (int i = 0; i < 10; i++) {
  17518. auto text = "message " + std::to_string(i);
  17519. ASSERT_TRUE(client.send(text));
  17520. std::string msg;
  17521. ASSERT_TRUE(client.read(msg));
  17522. EXPECT_EQ(text, msg);
  17523. }
  17524. client.close();
  17525. }
  17526. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  17527. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17528. "/ws-close");
  17529. ASSERT_TRUE(client.connect());
  17530. // Send a message to trigger the server to close
  17531. ASSERT_TRUE(client.send("trigger close"));
  17532. // The server will close, so read should return false
  17533. std::string msg;
  17534. EXPECT_FALSE(client.read(msg));
  17535. EXPECT_FALSE(client.is_open());
  17536. }
  17537. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  17538. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17539. "/ws-echo");
  17540. ASSERT_TRUE(client.connect());
  17541. // 128KB message
  17542. std::string large_data(128 * 1024, 'X');
  17543. ASSERT_TRUE(client.send(large_data));
  17544. std::string msg;
  17545. ASSERT_TRUE(client.read(msg));
  17546. EXPECT_EQ(large_data, msg);
  17547. client.close();
  17548. }
  17549. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  17550. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17551. "/ws-echo");
  17552. ASSERT_TRUE(client.connect());
  17553. const int num_threads = 4;
  17554. std::vector<std::thread> threads;
  17555. std::atomic<int> send_count{0};
  17556. for (int t = 0; t < num_threads; t++) {
  17557. threads.emplace_back([&client, &send_count, t]() {
  17558. for (int i = 0; i < 5; i++) {
  17559. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  17560. if (client.send(text)) { send_count++; }
  17561. }
  17562. });
  17563. }
  17564. for (auto &th : threads) {
  17565. th.join();
  17566. }
  17567. int received = 0;
  17568. std::string msg;
  17569. while (received < send_count.load()) {
  17570. if (!client.read(msg)) { break; }
  17571. received++;
  17572. }
  17573. EXPECT_EQ(send_count.load(), received);
  17574. client.close();
  17575. }
  17576. TEST_F(WebSocketIntegrationTest, ReadString) {
  17577. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17578. "/ws-echo-string");
  17579. ASSERT_TRUE(client.connect());
  17580. ASSERT_TRUE(client.send("hello"));
  17581. std::string msg;
  17582. ASSERT_TRUE(client.read(msg));
  17583. EXPECT_EQ("echo: hello", msg);
  17584. ASSERT_TRUE(client.send("world"));
  17585. ASSERT_TRUE(client.read(msg));
  17586. EXPECT_EQ("echo: world", msg);
  17587. client.close();
  17588. }
  17589. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  17590. Headers headers = {{"X-Test-Header", "test-value"}};
  17591. ws::WebSocketClient client(
  17592. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  17593. ASSERT_TRUE(client.connect());
  17594. std::string msg;
  17595. ASSERT_TRUE(client.read(msg));
  17596. EXPECT_EQ("path:/ws-request-info", msg);
  17597. ASSERT_TRUE(client.read(msg));
  17598. EXPECT_EQ("header:test-value", msg);
  17599. client.close();
  17600. }
  17601. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  17602. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17603. "/ws-echo");
  17604. client.set_read_timeout(1, 0); // 1 second
  17605. ASSERT_TRUE(client.connect());
  17606. // Don't send anything — server echo handler waits for a message,
  17607. // so read() should time out and return false.
  17608. std::string msg;
  17609. EXPECT_FALSE(client.read(msg));
  17610. }
  17611. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  17612. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17613. "/ws-echo");
  17614. client.set_read_timeout(5, 0);
  17615. ASSERT_TRUE(client.connect());
  17616. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  17617. // The server should reject it and close the connection.
  17618. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  17619. client.send(oversized);
  17620. // The server's read() should have failed due to payload limit,
  17621. // so our read() should return false (connection closed).
  17622. std::string msg;
  17623. EXPECT_FALSE(client.read(msg));
  17624. }
  17625. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  17626. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17627. "/ws-echo");
  17628. client.set_read_timeout(10, 0);
  17629. ASSERT_TRUE(client.connect());
  17630. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  17631. // This should succeed.
  17632. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  17633. ASSERT_TRUE(client.send(at_limit));
  17634. std::string msg;
  17635. ASSERT_TRUE(client.read(msg));
  17636. EXPECT_EQ(at_limit.size(), msg.size());
  17637. client.close();
  17638. }
  17639. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  17640. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17641. "/nonexistent");
  17642. auto res = client.connect();
  17643. EXPECT_FALSE(res);
  17644. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  17645. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  17646. EXPECT_FALSE(client.is_open());
  17647. }
  17648. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  17649. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17650. "/ws-echo");
  17651. ASSERT_TRUE(client.connect());
  17652. ASSERT_TRUE(client.send(""));
  17653. std::string msg;
  17654. EXPECT_EQ(ws::Text, client.read(msg));
  17655. EXPECT_EQ("", msg);
  17656. client.close();
  17657. }
  17658. TEST_F(WebSocketIntegrationTest, Reconnect) {
  17659. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17660. "/ws-echo");
  17661. // First connection
  17662. ASSERT_TRUE(client.connect());
  17663. ASSERT_TRUE(client.send("first"));
  17664. std::string msg;
  17665. ASSERT_TRUE(client.read(msg));
  17666. EXPECT_EQ("first", msg);
  17667. client.close();
  17668. EXPECT_FALSE(client.is_open());
  17669. // Reconnect using the same client object
  17670. ASSERT_TRUE(client.connect());
  17671. ASSERT_TRUE(client.is_open());
  17672. ASSERT_TRUE(client.send("second"));
  17673. ASSERT_TRUE(client.read(msg));
  17674. EXPECT_EQ("second", msg);
  17675. client.close();
  17676. }
  17677. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  17678. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17679. "/ws-close-status");
  17680. ASSERT_TRUE(client.connect());
  17681. // Trigger the server to close with GoingAway status
  17682. ASSERT_TRUE(client.send("trigger"));
  17683. // read() should return false after receiving the close frame
  17684. std::string msg;
  17685. EXPECT_FALSE(client.read(msg));
  17686. EXPECT_FALSE(client.is_open());
  17687. }
  17688. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  17689. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17690. "/ws-echo");
  17691. ASSERT_TRUE(client.connect());
  17692. client.close(ws::CloseStatus::GoingAway, "client leaving");
  17693. EXPECT_FALSE(client.is_open());
  17694. }
  17695. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  17696. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  17697. ws::WebSocketClient client(
  17698. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  17699. ASSERT_TRUE(client.connect());
  17700. // Server should have selected graphql-ws
  17701. EXPECT_EQ("graphql-ws", client.subprotocol());
  17702. client.close();
  17703. }
  17704. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  17705. Headers headers;
  17706. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  17707. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  17708. ws::WebSocketClient client(
  17709. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  17710. ASSERT_TRUE(client.connect());
  17711. // The offer on the second field line counts too, so graphql-ws is selected
  17712. EXPECT_EQ("graphql-ws", client.subprotocol());
  17713. client.close();
  17714. }
  17715. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  17716. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  17717. ws::WebSocketClient client(
  17718. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  17719. ASSERT_TRUE(client.connect());
  17720. // Server should not have selected any subprotocol
  17721. EXPECT_TRUE(client.subprotocol().empty());
  17722. client.close();
  17723. }
  17724. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  17725. // Connect without requesting any subprotocol
  17726. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17727. "/ws-subprotocol");
  17728. ASSERT_TRUE(client.connect());
  17729. EXPECT_TRUE(client.subprotocol().empty());
  17730. client.close();
  17731. }
  17732. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  17733. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17734. "/ws-echo");
  17735. client.set_tcp_nodelay(true);
  17736. client.set_connection_timeout(3, 0);
  17737. bool socket_options_called = false;
  17738. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  17739. ASSERT_TRUE(client.connect());
  17740. ASSERT_TRUE(client.is_open());
  17741. EXPECT_TRUE(socket_options_called);
  17742. ASSERT_TRUE(client.send("hello"));
  17743. std::string msg;
  17744. auto result = client.read(msg);
  17745. EXPECT_EQ(result, ws::ReadResult::Text);
  17746. EXPECT_EQ(msg, "hello");
  17747. client.close();
  17748. }
  17749. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  17750. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17751. "/ws-echo");
  17752. client.set_connection_timeout(std::chrono::seconds(3));
  17753. client.set_write_timeout(std::chrono::seconds(3));
  17754. // A sub-second remainder exercises the seconds/microseconds split.
  17755. client.set_read_timeout(std::chrono::milliseconds(1500));
  17756. ASSERT_TRUE(client.connect());
  17757. auto start = std::chrono::steady_clock::now();
  17758. std::string msg;
  17759. EXPECT_EQ(client.read(msg), ws::ReadResult::Fail);
  17760. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17761. std::chrono::steady_clock::now() - start)
  17762. .count();
  17763. // Above 1s so that dropping the microseconds half of the split fails here,
  17764. // and well under the 300s default so that ignoring the setter fails too.
  17765. EXPECT_GE(elapsed, 1400);
  17766. EXPECT_LT(elapsed, 30000);
  17767. }
  17768. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  17769. Server svr;
  17770. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  17771. if (!req.has_header("Authorization")) {
  17772. res.status = StatusCode::Unauthorized_401;
  17773. res.set_content("Unauthorized", "text/plain");
  17774. return Server::HandlerResponse::Handled;
  17775. }
  17776. return Server::HandlerResponse::Unhandled;
  17777. });
  17778. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  17779. std::string msg;
  17780. while (ws.read(msg)) {
  17781. ws.send(msg);
  17782. }
  17783. });
  17784. auto port = svr.bind_to_any_port("localhost");
  17785. std::thread t([&]() { svr.listen_after_bind(); });
  17786. svr.wait_until_ready();
  17787. // Without Authorization header - should be rejected before upgrade
  17788. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  17789. EXPECT_FALSE(client1.connect());
  17790. // With Authorization header - should succeed
  17791. Headers headers = {{"Authorization", "Bearer token123"}};
  17792. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  17793. headers);
  17794. ASSERT_TRUE(client2.connect());
  17795. ASSERT_TRUE(client2.send("hello"));
  17796. std::string msg;
  17797. ASSERT_TRUE(client2.read(msg));
  17798. EXPECT_EQ("hello", msg);
  17799. client2.close();
  17800. svr.stop();
  17801. t.join();
  17802. }
  17803. TEST(WebSocketTest, QueryStringInHandshake) {
  17804. Server svr;
  17805. std::mutex mtx;
  17806. std::string received_target;
  17807. std::string received_token;
  17808. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  17809. {
  17810. std::lock_guard<std::mutex> lock(mtx);
  17811. received_target = req.target;
  17812. if (req.has_param("token")) {
  17813. received_token = req.get_param_value("token");
  17814. }
  17815. }
  17816. std::string msg;
  17817. while (ws.read(msg)) {
  17818. ws.send(msg);
  17819. }
  17820. });
  17821. auto port = svr.bind_to_any_port("localhost");
  17822. std::thread t([&]() { svr.listen_after_bind(); });
  17823. svr.wait_until_ready();
  17824. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  17825. "/ws?token=ABC&session=123");
  17826. ASSERT_TRUE(client.connect());
  17827. // Round-trip ensures the handler has run and captured the request.
  17828. ASSERT_TRUE(client.send("hello"));
  17829. std::string msg;
  17830. ASSERT_TRUE(client.read(msg));
  17831. EXPECT_EQ("hello", msg);
  17832. client.close();
  17833. {
  17834. std::lock_guard<std::mutex> lock(mtx);
  17835. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  17836. EXPECT_EQ("ABC", received_token);
  17837. }
  17838. svr.stop();
  17839. t.join();
  17840. }
  17841. // Run a handshake against a throwaway server and hand the request the server
  17842. // received back to the caller, so tests can assert on the headers the client
  17843. // actually put on the wire.
  17844. static void capture_websocket_handshake_request(
  17845. const Headers &client_headers,
  17846. std::function<void(const Request &, int port)> verify) {
  17847. Server svr;
  17848. std::mutex mtx;
  17849. Request received;
  17850. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  17851. {
  17852. std::lock_guard<std::mutex> lock(mtx);
  17853. received = req;
  17854. }
  17855. std::string msg;
  17856. while (ws.read(msg)) {
  17857. ws.send(msg);
  17858. }
  17859. });
  17860. auto port = svr.bind_to_any_port("localhost");
  17861. std::thread t([&]() { svr.listen_after_bind(); });
  17862. auto se = detail::scope_exit([&] {
  17863. svr.stop();
  17864. t.join();
  17865. });
  17866. svr.wait_until_ready();
  17867. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  17868. client_headers);
  17869. ASSERT_TRUE(client.connect());
  17870. ASSERT_TRUE(client.send("hello"));
  17871. std::string msg;
  17872. ASSERT_TRUE(client.read(msg));
  17873. client.close();
  17874. {
  17875. std::lock_guard<std::mutex> lock(mtx);
  17876. verify(received, port);
  17877. }
  17878. }
  17879. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  17880. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  17881. // Non-default port must be present in the Host header. Default ports
  17882. // (80/443) are omitted; that logic is covered by
  17883. // MakeHostAndPortStringTest.
  17884. EXPECT_EQ("localhost:" + std::to_string(port),
  17885. req.get_header_value("Host"));
  17886. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  17887. req.get_header_value("User-Agent"));
  17888. EXPECT_FALSE(req.has_header("Accept"));
  17889. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  17890. EXPECT_FALSE(req.has_header("Content-Length"));
  17891. });
  17892. }
  17893. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  17894. capture_websocket_handshake_request(
  17895. {{"Host", "example.com"},
  17896. {"User-Agent", "custom-agent"},
  17897. {"X-Custom", "value"}},
  17898. [](const Request &req, int) {
  17899. EXPECT_EQ("example.com", req.get_header_value("Host"));
  17900. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  17901. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  17902. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  17903. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  17904. });
  17905. }
  17906. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  17907. capture_websocket_handshake_request(
  17908. {{"Upgrade", "bogus"},
  17909. {"Connection", "close"},
  17910. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  17911. {"Sec-WebSocket-Version", "8"}},
  17912. [](const Request &req, int) {
  17913. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  17914. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  17915. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  17916. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  17917. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  17918. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  17919. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  17920. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  17921. req.get_header_value("Sec-WebSocket-Key"));
  17922. });
  17923. }
  17924. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  17925. // A header the client refuses to send must abort the handshake before any
  17926. // part of it reaches the wire; a lone request line would otherwise sit in
  17927. // the peer's buffer as a truncated request.
  17928. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17929. ASSERT_NE(INVALID_SOCKET, srv);
  17930. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  17931. sockaddr_in addr{};
  17932. addr.sin_family = AF_INET;
  17933. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  17934. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17935. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17936. ASSERT_EQ(0, ::listen(srv, 1));
  17937. sockaddr_in bound{};
  17938. socklen_t bound_len = sizeof(bound);
  17939. ASSERT_EQ(
  17940. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  17941. auto port = ntohs(bound.sin_port);
  17942. ssize_t received = -1;
  17943. std::thread t([&] {
  17944. // Bound every blocking call so a regression fails the test with a bad
  17945. // value instead of hanging the suite.
  17946. fd_set rfds;
  17947. FD_ZERO(&rfds);
  17948. FD_SET(srv, &rfds);
  17949. timeval tv{5, 0};
  17950. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  17951. 0) {
  17952. return;
  17953. }
  17954. sockaddr_in cli_addr{};
  17955. socklen_t cli_len = sizeof(cli_addr);
  17956. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17957. if (cli == INVALID_SOCKET) { return; }
  17958. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  17959. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  17960. char buf[4096];
  17961. received = ::recv(cli, buf, sizeof(buf), 0);
  17962. });
  17963. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  17964. // connect() has already shut the socket down by the time it returns false,
  17965. // so the peer sees EOF without waiting for the client to be destroyed.
  17966. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  17967. {{"X-Bad", "a\r\nInjected: 1"}});
  17968. EXPECT_FALSE(client.connect());
  17969. t.join();
  17970. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  17971. EXPECT_EQ(0, received);
  17972. }
  17973. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  17974. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  17975. // contains "upgrade" as a substring is a different token and must not
  17976. // start a WebSocket handshake.
  17977. auto make_request = [](const std::vector<std::string> &connection_values) {
  17978. Request req;
  17979. req.method = "GET";
  17980. req.headers.emplace("Upgrade", "websocket");
  17981. for (const auto &value : connection_values) {
  17982. req.headers.emplace("Connection", value);
  17983. }
  17984. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  17985. req.headers.emplace("Sec-WebSocket-Version", "13");
  17986. return req;
  17987. };
  17988. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  17989. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  17990. EXPECT_TRUE(
  17991. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  17992. EXPECT_TRUE(
  17993. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  17994. EXPECT_TRUE(
  17995. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  17996. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  17997. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  17998. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  17999. EXPECT_FALSE(
  18000. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  18001. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  18002. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  18003. }
  18004. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  18005. Server svr;
  18006. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  18007. auto port = svr.bind_to_any_port("localhost");
  18008. std::thread t([&]() { svr.listen_after_bind(); });
  18009. auto se = detail::scope_exit([&] {
  18010. svr.stop();
  18011. t.join();
  18012. });
  18013. svr.wait_until_ready();
  18014. Headers headers = {{"Upgrade", "websocket"},
  18015. {"Connection", "notupgrade"},
  18016. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  18017. {"Sec-WebSocket-Version", "13"}};
  18018. Client cli("localhost", port);
  18019. auto res = cli.Get("/ws", headers);
  18020. // The route exists only as a WebSocket route, so a request that fails the
  18021. // handshake check falls through to ordinary routing.
  18022. ASSERT_TRUE(res);
  18023. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  18024. }
  18025. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  18026. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  18027. // Connection value is the only thing left for the client to reject.
  18028. Server svr;
  18029. svr.Get("/ws", [](const Request &req, Response &res) {
  18030. res.status = StatusCode::SwitchingProtocol_101;
  18031. res.set_header("Upgrade", "websocket");
  18032. res.set_header("Connection", "notupgrade");
  18033. res.set_header("Sec-WebSocket-Accept",
  18034. detail::websocket_accept_key(
  18035. req.get_header_value("Sec-WebSocket-Key")));
  18036. });
  18037. auto port = svr.bind_to_any_port("localhost");
  18038. std::thread t([&]() { svr.listen_after_bind(); });
  18039. auto se = detail::scope_exit([&] {
  18040. svr.stop();
  18041. t.join();
  18042. });
  18043. svr.wait_until_ready();
  18044. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  18045. auto res = client.connect();
  18046. EXPECT_FALSE(res);
  18047. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  18048. EXPECT_FALSE(client.is_open());
  18049. }
  18050. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  18051. // The socket path doubles as the URL host, so it must not contain '/'.
  18052. const char *shard = getenv("GTEST_SHARD_INDEX");
  18053. const std::string sock_path =
  18054. shard ? std::string("httplib-ws-") + shard + ".sock"
  18055. : std::string("httplib-ws.sock");
  18056. std::remove(sock_path.c_str());
  18057. Server svr;
  18058. std::mutex mtx;
  18059. std::string received_host;
  18060. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  18061. {
  18062. std::lock_guard<std::mutex> lock(mtx);
  18063. received_host = req.get_header_value("Host");
  18064. }
  18065. std::string msg;
  18066. while (ws.read(msg)) {
  18067. ws.send(msg);
  18068. }
  18069. });
  18070. svr.set_address_family(AF_UNIX);
  18071. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  18072. auto se = detail::scope_exit([&] {
  18073. svr.stop();
  18074. t.join();
  18075. std::remove(sock_path.c_str());
  18076. });
  18077. svr.wait_until_ready();
  18078. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  18079. client.set_address_family(AF_UNIX);
  18080. ASSERT_TRUE(client.connect());
  18081. ASSERT_TRUE(client.send("hello"));
  18082. std::string msg;
  18083. ASSERT_TRUE(client.read(msg));
  18084. client.close();
  18085. {
  18086. std::lock_guard<std::mutex> lock(mtx);
  18087. // There is no host:port for a Unix socket, so the same "localhost"
  18088. // placeholder the HTTP client uses is expected.
  18089. EXPECT_EQ("localhost", received_host);
  18090. }
  18091. }
  18092. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  18093. class WebSocketSSLIntegrationTest : public ::testing::Test {
  18094. protected:
  18095. void SetUp() override {
  18096. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  18097. SERVER_PRIVATE_KEY_FILE);
  18098. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  18099. std::string msg;
  18100. ws::ReadResult ret;
  18101. while ((ret = ws.read(msg))) {
  18102. if (ret == ws::Binary) {
  18103. ws.send(msg.data(), msg.size());
  18104. } else {
  18105. ws.send(msg);
  18106. }
  18107. }
  18108. });
  18109. port_ = server_->bind_to_any_port(HOST);
  18110. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  18111. server_->wait_until_ready();
  18112. }
  18113. void TearDown() override {
  18114. server_->stop();
  18115. if (server_thread_.joinable()) { server_thread_.join(); }
  18116. }
  18117. std::unique_ptr<SSLServer> server_;
  18118. std::thread server_thread_;
  18119. int port_ = 0;
  18120. };
  18121. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  18122. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  18123. "/ws-echo");
  18124. client.enable_server_certificate_verification(false);
  18125. ASSERT_TRUE(client.connect());
  18126. ASSERT_TRUE(client.is_open());
  18127. ASSERT_TRUE(client.send("Hello WSS"));
  18128. std::string msg;
  18129. EXPECT_EQ(ws::Text, client.read(msg));
  18130. EXPECT_EQ("Hello WSS", msg);
  18131. client.close();
  18132. }
  18133. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  18134. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  18135. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  18136. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  18137. // client (without calling close() first) is the only path that runs
  18138. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  18139. // bug exactly.
  18140. //
  18141. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  18142. // when linked against an instrumented libssl; run under Valgrind to catch it
  18143. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  18144. // suite (the freed session otherwise stalls on the close handshake) — this test
  18145. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  18146. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  18147. {
  18148. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  18149. "/ws-echo");
  18150. client.enable_server_certificate_verification(false);
  18151. client.set_read_timeout(2, 0);
  18152. client.set_write_timeout(2, 0);
  18153. ASSERT_TRUE(client.connect());
  18154. ASSERT_TRUE(client.is_open());
  18155. ASSERT_TRUE(client.send("still open"));
  18156. // Intentionally do NOT call client.close(): leaving scope runs
  18157. // shutdown_and_close() with the WebSocket still open, which must send the
  18158. // close frame while the TLS session is still alive.
  18159. }
  18160. }
  18161. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  18162. // shutdown_and_close() at the start of connect(), reproducing the same
  18163. // use-after-free within the test body rather than at scope exit. The second
  18164. // connect must succeed and echo, proving the close handshake ran over a live
  18165. // session. See the note above about memory-tool requirements.
  18166. TEST_F(WebSocketSSLIntegrationTest,
  18167. ReconnectWhileOpenSendsCloseOverLiveSession) {
  18168. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  18169. "/ws-echo");
  18170. client.enable_server_certificate_verification(false);
  18171. client.set_read_timeout(2, 0);
  18172. client.set_write_timeout(2, 0);
  18173. ASSERT_TRUE(client.connect());
  18174. ASSERT_TRUE(client.is_open());
  18175. ASSERT_TRUE(client.send("still open"));
  18176. // Reconnect without closing first: connect() calls shutdown_and_close() on
  18177. // the still-open connection, which must not touch a freed TLS session.
  18178. ASSERT_TRUE(client.connect());
  18179. ASSERT_TRUE(client.is_open());
  18180. ASSERT_TRUE(client.send("after reconnect"));
  18181. std::string msg;
  18182. EXPECT_EQ(ws::Text, client.read(msg));
  18183. EXPECT_EQ("after reconnect", msg);
  18184. client.close();
  18185. }
  18186. #endif
  18187. #ifdef CPPHTTPLIB_SSL_ENABLED
  18188. class WebSocketSSLCATest : public ::testing::Test {
  18189. protected:
  18190. void SetUp() override {
  18191. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  18192. SERVER_PRIVATE_KEY_FILE);
  18193. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  18194. std::string msg;
  18195. while (ws.read(msg)) {
  18196. ws.send(msg);
  18197. }
  18198. });
  18199. port_ = server_->bind_to_any_port("127.0.0.1");
  18200. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  18201. server_->wait_until_ready();
  18202. }
  18203. void TearDown() override {
  18204. server_->stop();
  18205. if (server_thread_.joinable()) { server_thread_.join(); }
  18206. }
  18207. std::string url() const {
  18208. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  18209. }
  18210. std::unique_ptr<SSLServer> server_;
  18211. std::thread server_thread_;
  18212. int port_ = 0;
  18213. };
  18214. // A custom CA loaded as PEM verifies the server with full certificate
  18215. // verification enabled
  18216. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  18217. ws::WebSocketClient client(url());
  18218. std::string cert;
  18219. read_file(SERVER_CERT2_FILE, cert);
  18220. client.load_ca_cert_store(cert.c_str(), cert.size());
  18221. ASSERT_TRUE(client.connect());
  18222. ASSERT_TRUE(client.send("hello"));
  18223. std::string msg;
  18224. EXPECT_EQ(ws::Text, client.read(msg));
  18225. EXPECT_EQ("hello", msg);
  18226. client.close();
  18227. }
  18228. // A custom CA that does not cover the server must fail verification (the
  18229. // custom CA is exclusive; system certs are not loaded alongside it)
  18230. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  18231. ws::WebSocketClient client(url());
  18232. std::string cert;
  18233. read_file(CLIENT_CA_CERT_FILE, cert);
  18234. client.load_ca_cert_store(cert.c_str(), cert.size());
  18235. auto res = client.connect();
  18236. ASSERT_FALSE(res);
  18237. EXPECT_EQ(Error::SSLServerVerification, res.error());
  18238. EXPECT_EQ(-1, res.status());
  18239. EXPECT_NE(0u, res.ssl_backend_error());
  18240. }
  18241. // The same CA as a file path rather than PEM in memory
  18242. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  18243. ws::WebSocketClient client(url());
  18244. client.set_ca_cert_path(SERVER_CERT2_FILE);
  18245. ASSERT_TRUE(client.connect());
  18246. ASSERT_TRUE(client.send("hello"));
  18247. std::string msg;
  18248. EXPECT_EQ(ws::Text, client.read(msg));
  18249. EXPECT_EQ("hello", msg);
  18250. client.close();
  18251. }
  18252. // ...and a CA file that does not cover the server still fails, so it is the
  18253. // path above that decides the outcome
  18254. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  18255. ws::WebSocketClient client(url());
  18256. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  18257. ASSERT_FALSE(client.connect());
  18258. }
  18259. // Regression test: reconnecting with a native custom CA store used to reuse
  18260. // a store handle the previous TLS context had already freed (use-after-free
  18261. // under the OpenSSL backend). The context now lives as long as the client.
  18262. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  18263. ws::WebSocketClient client(url());
  18264. std::string cert;
  18265. read_file(SERVER_CERT2_FILE, cert);
  18266. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  18267. ASSERT_TRUE(client.connect());
  18268. client.close();
  18269. ASSERT_TRUE(client.connect());
  18270. ASSERT_TRUE(client.send("again"));
  18271. std::string msg;
  18272. EXPECT_EQ(ws::Text, client.read(msg));
  18273. EXPECT_EQ("again", msg);
  18274. client.close();
  18275. }
  18276. // Regression test: a certificate with a trusted chain but no identity match
  18277. // for the server IP must be rejected. The Mbed TLS backend used to skip
  18278. // verification entirely for IP hosts, so this connection succeeded there.
  18279. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  18280. // chain verification while the identity check must still fail.
  18281. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  18282. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18283. ASSERT_TRUE(svr.is_valid());
  18284. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  18285. std::string msg;
  18286. while (ws.read(msg)) {
  18287. ws.send(msg);
  18288. }
  18289. });
  18290. auto port = svr.bind_to_any_port("127.0.0.1");
  18291. auto t = std::thread([&]() { svr.listen_after_bind(); });
  18292. auto se = detail::scope_exit([&] {
  18293. svr.stop();
  18294. t.join();
  18295. });
  18296. svr.wait_until_ready();
  18297. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  18298. "/echo");
  18299. std::string cert;
  18300. read_file(SERVER_CERT_FILE, cert);
  18301. client.load_ca_cert_store(cert.c_str(), cert.size());
  18302. ASSERT_FALSE(client.connect());
  18303. }
  18304. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  18305. // SNI, so nothing binds the host name to the TLS session. These bind the
  18306. // server to "localhost" instead, the only shape that exercises the SNI and
  18307. // hostname-verification path with certificate verification left enabled.
  18308. class WebSocketSSLDnsHostTest : public ::testing::Test {
  18309. protected:
  18310. void Start(const char *cert_file) {
  18311. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  18312. SERVER_PRIVATE_KEY_FILE);
  18313. ASSERT_TRUE(server_->is_valid());
  18314. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  18315. std::string msg;
  18316. while (ws.read(msg)) {
  18317. ws.send(msg);
  18318. }
  18319. });
  18320. port_ = server_->bind_to_any_port("localhost");
  18321. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  18322. server_->wait_until_ready();
  18323. }
  18324. void TearDown() override {
  18325. if (server_) { server_->stop(); }
  18326. if (server_thread_.joinable()) { server_thread_.join(); }
  18327. }
  18328. std::string url() const {
  18329. return "wss://localhost:" + std::to_string(port_) + "/echo";
  18330. }
  18331. std::unique_ptr<SSLServer> server_;
  18332. std::thread server_thread_;
  18333. int port_ = 0;
  18334. };
  18335. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  18336. // out and the connection is usable
  18337. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  18338. Start(SERVER_CERT2_FILE);
  18339. ws::WebSocketClient client(url());
  18340. client.set_ca_cert_path(SERVER_CERT2_FILE);
  18341. ASSERT_TRUE(client.connect());
  18342. ASSERT_TRUE(client.send("hello"));
  18343. std::string msg;
  18344. EXPECT_EQ(ws::Text, client.read(msg));
  18345. EXPECT_EQ("hello", msg);
  18346. client.close();
  18347. }
  18348. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  18349. // while the identity check must still reject "localhost"
  18350. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  18351. Start(SERVER_CERT_FILE);
  18352. ws::WebSocketClient client(url());
  18353. client.set_ca_cert_path(SERVER_CERT_FILE);
  18354. auto res = client.connect();
  18355. ASSERT_FALSE(res);
  18356. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  18357. EXPECT_EQ(-1, res.status());
  18358. }
  18359. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  18360. // disabled: the chain is still checked, only the identity check is skipped
  18361. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  18362. Start(SERVER_CERT_FILE);
  18363. ws::WebSocketClient client(url());
  18364. client.set_ca_cert_path(SERVER_CERT_FILE);
  18365. client.enable_server_hostname_verification(false);
  18366. ASSERT_TRUE(client.connect());
  18367. ASSERT_TRUE(client.send("hello"));
  18368. std::string msg;
  18369. EXPECT_EQ(ws::Text, client.read(msg));
  18370. EXPECT_EQ("hello", msg);
  18371. client.close();
  18372. }
  18373. // A CA that did not sign the server certificate fails the chain, even though
  18374. // the name would match
  18375. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  18376. Start(SERVER_CERT2_FILE);
  18377. ws::WebSocketClient client(url());
  18378. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  18379. ASSERT_FALSE(client.connect());
  18380. }
  18381. // With verification disabled, neither the chain nor the name is checked
  18382. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  18383. Start(SERVER_CERT_FILE);
  18384. ws::WebSocketClient client(url());
  18385. client.enable_server_certificate_verification(false);
  18386. ASSERT_TRUE(client.connect());
  18387. ASSERT_TRUE(client.send("hello"));
  18388. std::string msg;
  18389. EXPECT_EQ(ws::Text, client.read(msg));
  18390. EXPECT_EQ("hello", msg);
  18391. client.close();
  18392. }
  18393. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  18394. protected:
  18395. void SetUp() override {
  18396. server_ = httplib::detail::make_unique<SSLServer>(
  18397. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  18398. ASSERT_TRUE(server_->is_valid());
  18399. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  18400. std::string msg;
  18401. while (ws.read(msg)) {
  18402. ws.send(msg);
  18403. }
  18404. });
  18405. port_ = server_->bind_to_any_port("localhost");
  18406. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  18407. server_->wait_until_ready();
  18408. }
  18409. void TearDown() override {
  18410. server_->stop();
  18411. if (server_thread_.joinable()) { server_thread_.join(); }
  18412. }
  18413. std::string url() const {
  18414. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  18415. }
  18416. void ConnectWithClientCert(const std::string &client_cert_file,
  18417. const std::string &client_private_key_file,
  18418. const char *private_key_password) {
  18419. std::string cert_pem, key_pem;
  18420. read_file(client_cert_file, cert_pem);
  18421. read_file(client_private_key_file, key_pem);
  18422. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  18423. key_pem.c_str(), key_pem.size(),
  18424. private_key_password};
  18425. ws::WebSocketClient client(url(), pem);
  18426. ASSERT_TRUE(client.is_valid());
  18427. client.enable_server_certificate_verification(false);
  18428. ASSERT_TRUE(client.connect());
  18429. ASSERT_TRUE(client.send("hello"));
  18430. std::string msg;
  18431. EXPECT_EQ(ws::Text, client.read(msg));
  18432. EXPECT_EQ("hello", msg);
  18433. client.close();
  18434. }
  18435. std::unique_ptr<SSLServer> server_;
  18436. std::thread server_thread_;
  18437. int port_ = 0;
  18438. };
  18439. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  18440. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  18441. }
  18442. // Control for the tests above: the fixture's server really does require a
  18443. // client certificate, so it is the PEM the constructor installed that decides
  18444. // the outcome.
  18445. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  18446. ws::WebSocketClient client(url());
  18447. ASSERT_TRUE(client.is_valid());
  18448. client.enable_server_certificate_verification(false);
  18449. EXPECT_FALSE(client.connect());
  18450. }
  18451. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  18452. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  18453. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  18454. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  18455. }
  18456. #endif
  18457. #if !defined(_WIN32)
  18458. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  18459. auto secret_dir = std::string("./symlink_test_secret");
  18460. auto served_dir = std::string("./symlink_test_served");
  18461. auto secret_file = secret_dir + "/secret.txt";
  18462. auto symlink_path = served_dir + "/escape";
  18463. // Setup: create directories and files
  18464. mkdir(secret_dir.c_str(), 0755);
  18465. mkdir(served_dir.c_str(), 0755);
  18466. {
  18467. std::ofstream ofs(secret_file);
  18468. ofs << "SECRET_DATA";
  18469. }
  18470. // Create symlink using absolute path so it resolves correctly
  18471. #ifdef PATH_MAX
  18472. char abs_secret[PATH_MAX];
  18473. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  18474. #else
  18475. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  18476. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  18477. ASSERT_NE(nullptr, abs_secret);
  18478. #endif
  18479. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  18480. auto se = detail::scope_exit([&] {
  18481. unlink(symlink_path.c_str());
  18482. unlink(secret_file.c_str());
  18483. rmdir(served_dir.c_str());
  18484. rmdir(secret_dir.c_str());
  18485. });
  18486. Server svr;
  18487. svr.set_mount_point("/", served_dir);
  18488. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  18489. auto se2 = detail::scope_exit([&] {
  18490. svr.stop();
  18491. listen_thread.join();
  18492. });
  18493. svr.wait_until_ready();
  18494. Client cli("localhost", PORT);
  18495. // Symlink pointing outside base dir should be blocked
  18496. auto res = cli.Get("/escape/secret.txt");
  18497. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18498. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  18499. }
  18500. #endif
  18501. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  18502. // A GET request with Content-Length to a static file handler must have its
  18503. // body drained before the keep-alive connection is reused. Otherwise the
  18504. // unread body bytes are interpreted as the next HTTP request.
  18505. //
  18506. // The body is sent AFTER receiving the first response (as in the original
  18507. // PoC) so that the stream_line_reader cannot buffer it together with the
  18508. // headers of the first request.
  18509. Server svr;
  18510. svr.set_mount_point("/", "./www");
  18511. std::atomic<int> smuggled_count(0);
  18512. svr.Get("/smuggled", [&](const Request &, Response &res) {
  18513. smuggled_count++;
  18514. res.set_content("oops", "text/plain");
  18515. });
  18516. auto port = svr.bind_to_any_port("localhost");
  18517. thread t = thread([&] { svr.listen_after_bind(); });
  18518. auto se = detail::scope_exit([&] {
  18519. svr.stop();
  18520. t.join();
  18521. });
  18522. svr.wait_until_ready();
  18523. auto error = Error::Success;
  18524. auto sock = detail::create_client_socket(
  18525. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  18526. /*connection_timeout_sec=*/2, 0,
  18527. /*read_timeout_sec=*/2, 0,
  18528. /*write_timeout_sec=*/2, 0, std::string(), error);
  18529. ASSERT_NE(INVALID_SOCKET, sock);
  18530. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  18531. // The "smuggled" request will be sent as the body of the outer GET
  18532. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  18533. "Host: localhost\r\n"
  18534. "Connection: close\r\n"
  18535. "\r\n";
  18536. // Step 1: Send only the outer request headers (no body yet)
  18537. std::string outer_headers = "GET /file HTTP/1.1\r\n"
  18538. "Host: localhost\r\n"
  18539. "Content-Length: " +
  18540. std::to_string(smuggled.size()) +
  18541. "\r\n"
  18542. "\r\n";
  18543. auto sent = send(sock, outer_headers.data(), outer_headers.size(), 0);
  18544. ASSERT_EQ(static_cast<ssize_t>(outer_headers.size()), sent);
  18545. // Step 2: Read the first response (server serves file without reading body)
  18546. std::string first_response;
  18547. char buf[4096];
  18548. for (;;) {
  18549. auto n = recv(sock, buf, sizeof(buf), 0);
  18550. if (n <= 0) break;
  18551. first_response.append(buf, static_cast<size_t>(n));
  18552. // Stop once we have a complete response (headers + body)
  18553. auto hdr_end = first_response.find("\r\n\r\n");
  18554. if (hdr_end != std::string::npos) {
  18555. // Check for Content-Length to know when the body is complete
  18556. auto cl_pos = first_response.find("Content-Length:");
  18557. if (cl_pos != std::string::npos) {
  18558. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  18559. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  18560. auto cl = std::stoul(
  18561. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  18562. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  18563. } else {
  18564. break; // No Content-Length, assume headers-only response
  18565. }
  18566. }
  18567. }
  18568. ASSERT_TRUE(first_response.find("HTTP/1.1 200") != std::string::npos);
  18569. // Step 3: Now send the body, which looks like a new HTTP request.
  18570. // On a vulnerable server the keep-alive loop reads this as a second request.
  18571. sent = send(sock, smuggled.data(), smuggled.size(), 0);
  18572. ASSERT_EQ(static_cast<ssize_t>(smuggled.size()), sent);
  18573. // Step 4: Try to read a second response (should NOT exist after fix)
  18574. std::string second_response;
  18575. for (;;) {
  18576. auto n = recv(sock, buf, sizeof(buf), 0);
  18577. if (n <= 0) break;
  18578. second_response.append(buf, static_cast<size_t>(n));
  18579. }
  18580. // The smuggled request must NOT have been processed
  18581. EXPECT_EQ(0, smuggled_count.load());
  18582. }
  18583. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  18584. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  18585. // must be rejected with 400 Bad Request.
  18586. Server svr;
  18587. svr.Post("/test", [&](const Request &, Response &res) {
  18588. res.set_content("ok", "text/plain");
  18589. });
  18590. thread t = thread([&] { svr.listen(HOST, PORT); });
  18591. auto se = detail::scope_exit([&] {
  18592. svr.stop();
  18593. t.join();
  18594. ASSERT_FALSE(svr.is_running());
  18595. });
  18596. svr.wait_until_ready();
  18597. // Exact "chunked"
  18598. {
  18599. auto req = "POST /test HTTP/1.1\r\n"
  18600. "Host: localhost\r\n"
  18601. "Content-Length: 5\r\n"
  18602. "Transfer-Encoding: chunked\r\n"
  18603. "Connection: close\r\n"
  18604. "\r\n"
  18605. "hello";
  18606. std::string response;
  18607. ASSERT_TRUE(send_request(1, req, &response));
  18608. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  18609. response.substr(0, response.find("\r\n")));
  18610. }
  18611. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  18612. {
  18613. auto req = "POST /test HTTP/1.1\r\n"
  18614. "Host: localhost\r\n"
  18615. "Content-Length: 5\r\n"
  18616. "Transfer-Encoding: gzip, chunked\r\n"
  18617. "Connection: close\r\n"
  18618. "\r\n"
  18619. "hello";
  18620. std::string response;
  18621. ASSERT_TRUE(send_request(1, req, &response));
  18622. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  18623. response.substr(0, response.find("\r\n")));
  18624. }
  18625. }
  18626. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  18627. Server svr;
  18628. svr.Post("/test", [&](const Request &, Response &res) {
  18629. res.set_content("ok", "text/plain");
  18630. });
  18631. thread t = thread([&] { svr.listen(HOST, PORT); });
  18632. auto se = detail::scope_exit([&] {
  18633. svr.stop();
  18634. t.join();
  18635. ASSERT_FALSE(svr.is_running());
  18636. });
  18637. svr.wait_until_ready();
  18638. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  18639. // length cannot be determined, so the server must answer 400 and close
  18640. // rather than treat the request as bodyless and leave the body in the
  18641. // socket for the next request to pick up.
  18642. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  18643. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  18644. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  18645. std::string response;
  18646. ASSERT_TRUE(send_request(1, req, &response));
  18647. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  18648. response.substr(0, response.find("\r\n")))
  18649. << transfer_encoding;
  18650. }
  18651. // RFC 9110 5.3: the codings may also be split across several
  18652. // Transfer-Encoding lines, which combine in the order they were received.
  18653. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  18654. // just like the single-line "chunked, gzip" above.
  18655. {
  18656. auto req = "POST /test HTTP/1.1\r\n"
  18657. "Host: localhost\r\n"
  18658. "Transfer-Encoding: chunked\r\n"
  18659. "Transfer-Encoding: gzip\r\n"
  18660. "\r\n"
  18661. "0\r\n\r\n";
  18662. std::string response;
  18663. ASSERT_TRUE(send_request(1, req, &response));
  18664. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  18665. response.substr(0, response.find("\r\n")));
  18666. }
  18667. // A sequence ending in chunked stays valid.
  18668. auto req = "POST /test HTTP/1.1\r\n"
  18669. "Host: localhost\r\n"
  18670. "Transfer-Encoding: gzip, chunked\r\n"
  18671. "Connection: close\r\n"
  18672. "\r\n"
  18673. "0\r\n\r\n";
  18674. std::string response;
  18675. ASSERT_TRUE(send_request(1, req, &response));
  18676. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  18677. // ...including when it is spread over several lines.
  18678. auto split_req = "POST /test HTTP/1.1\r\n"
  18679. "Host: localhost\r\n"
  18680. "Transfer-Encoding: gzip\r\n"
  18681. "Transfer-Encoding: chunked\r\n"
  18682. "Connection: close\r\n"
  18683. "\r\n"
  18684. "0\r\n\r\n";
  18685. std::string split_response;
  18686. ASSERT_TRUE(send_request(1, split_req, &split_response));
  18687. EXPECT_EQ("HTTP/1.1 200 OK",
  18688. split_response.substr(0, split_response.find("\r\n")));
  18689. }
  18690. // Regression for issue #2450: a DELETE without Content-Length on a
  18691. // keep-alive connection must not let the post-response drain consume the
  18692. // next request's bytes.
  18693. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  18694. Server svr;
  18695. std::atomic<int> delete_count(0);
  18696. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  18697. delete_count++;
  18698. res.status = StatusCode::NoContent_204;
  18699. });
  18700. auto port = svr.bind_to_any_port(HOST);
  18701. thread t = thread([&] { svr.listen_after_bind(); });
  18702. auto se = detail::scope_exit([&] {
  18703. svr.stop();
  18704. t.join();
  18705. });
  18706. svr.wait_until_ready();
  18707. auto error = Error::Success;
  18708. auto sock = detail::create_client_socket(
  18709. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  18710. /*connection_timeout_sec=*/2, 0,
  18711. /*read_timeout_sec=*/2, 0,
  18712. /*write_timeout_sec=*/2, 0, std::string(), error);
  18713. ASSERT_NE(INVALID_SOCKET, sock);
  18714. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  18715. auto send_request_and_read_response = [&](const std::string &req,
  18716. std::string &out) -> bool {
  18717. auto sent = send(sock, req.data(), req.size(), 0);
  18718. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  18719. char buf[4096];
  18720. for (;;) {
  18721. auto n = recv(sock, buf, sizeof(buf), 0);
  18722. if (n <= 0) { return !out.empty(); }
  18723. out.append(buf, static_cast<size_t>(n));
  18724. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  18725. }
  18726. };
  18727. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  18728. "Host: localhost\r\n"
  18729. "\r\n";
  18730. std::string resp1;
  18731. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  18732. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  18733. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  18734. "Host: localhost\r\n"
  18735. "Connection: close\r\n"
  18736. "\r\n";
  18737. std::string resp2;
  18738. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  18739. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  18740. EXPECT_EQ(2, delete_count.load());
  18741. }
  18742. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  18743. Server svr;
  18744. svr.Post("/ingest", [&](const Request &, Response &res,
  18745. const ContentReader &content_reader) {
  18746. auto consumed = content_reader([](const char *, size_t) { return false; });
  18747. EXPECT_FALSE(consumed);
  18748. res.status = StatusCode::Conflict_409;
  18749. res.set_header("Connection", "close");
  18750. });
  18751. auto port = svr.bind_to_any_port(HOST);
  18752. thread t = thread([&] { svr.listen_after_bind(); });
  18753. auto se = detail::scope_exit([&] {
  18754. svr.stop();
  18755. t.join();
  18756. });
  18757. svr.wait_until_ready();
  18758. auto error = Error::Success;
  18759. auto sock = detail::create_client_socket(
  18760. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  18761. /*connection_timeout_sec=*/2, 0,
  18762. /*read_timeout_sec=*/1, 0,
  18763. /*write_timeout_sec=*/2, 0, std::string(), error);
  18764. ASSERT_NE(INVALID_SOCKET, sock);
  18765. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  18766. std::string request = "POST /ingest HTTP/1.1\r\n"
  18767. "Host: localhost\r\n"
  18768. "Transfer-Encoding: chunked\r\n"
  18769. "\r\n"
  18770. "4\r\n"
  18771. "data\r\n";
  18772. auto sent = send(sock, request.data(), request.size(), 0);
  18773. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  18774. std::string response;
  18775. ssize_t received = 0;
  18776. do {
  18777. char buf[4096];
  18778. received = recv(sock, buf, sizeof(buf), 0);
  18779. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  18780. } while (received > 0);
  18781. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  18782. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  18783. EXPECT_EQ(0, received);
  18784. }
  18785. namespace no_proxy_test {
  18786. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  18787. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  18788. // calling listen().
  18789. class ScopedServer {
  18790. public:
  18791. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  18792. ~ScopedServer() {
  18793. svr_.stop();
  18794. if (th_.joinable()) { th_.join(); }
  18795. }
  18796. Server &svr() { return svr_; }
  18797. int port() const { return port_; }
  18798. void listen() {
  18799. th_ = std::thread([this] { svr_.listen_after_bind(); });
  18800. svr_.wait_until_ready();
  18801. }
  18802. private:
  18803. Server svr_;
  18804. std::thread th_;
  18805. int port_ = 0;
  18806. };
  18807. class ProxyAndTargetServers {
  18808. public:
  18809. ProxyAndTargetServers() {
  18810. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  18811. proxy_hits_++;
  18812. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  18813. res.set_content("via-proxy", "text/plain");
  18814. });
  18815. target_.Get(".*", [this](const Request &req, Response &res) {
  18816. target_hits_++;
  18817. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  18818. res.set_content("direct", "text/plain");
  18819. });
  18820. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  18821. target_port_ = target_.bind_to_any_port("127.0.0.1");
  18822. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  18823. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  18824. proxy_mock_.wait_until_ready();
  18825. target_.wait_until_ready();
  18826. }
  18827. ~ProxyAndTargetServers() {
  18828. proxy_mock_.stop();
  18829. target_.stop();
  18830. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  18831. if (target_thread_.joinable()) { target_thread_.join(); }
  18832. }
  18833. Server &proxy_mock() { return proxy_mock_; }
  18834. Server &target() { return target_; }
  18835. int proxy_port() const { return proxy_port_; }
  18836. int target_port() const { return target_port_; }
  18837. int proxy_hits() const { return proxy_hits_.load(); }
  18838. int target_hits() const { return target_hits_.load(); }
  18839. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  18840. void reset_counters() {
  18841. proxy_hits_ = 0;
  18842. target_hits_ = 0;
  18843. last_had_proxy_authz_ = false;
  18844. }
  18845. private:
  18846. Server proxy_mock_;
  18847. Server target_;
  18848. std::thread proxy_thread_;
  18849. std::thread target_thread_;
  18850. int proxy_port_ = 0;
  18851. int target_port_ = 0;
  18852. std::atomic<int> proxy_hits_{0};
  18853. std::atomic<int> target_hits_{0};
  18854. std::atomic<bool> last_had_proxy_authz_{false};
  18855. };
  18856. inline std::unique_ptr<Client> make_client(const std::string &host,
  18857. ProxyAndTargetServers &s) {
  18858. auto cli = detail::make_unique<Client>(host, s.target_port());
  18859. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  18860. cli->set_proxy("127.0.0.1", s.proxy_port());
  18861. return cli;
  18862. }
  18863. } // namespace no_proxy_test
  18864. using no_proxy_test::make_client;
  18865. using no_proxy_test::ProxyAndTargetServers;
  18866. TEST(NoProxyTest, ExactHostnameBypasses) {
  18867. ProxyAndTargetServers s;
  18868. auto cli = make_client("example.com", s);
  18869. cli->set_no_proxy({"example.com"});
  18870. auto res = cli->Get("/");
  18871. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18872. EXPECT_EQ(0, s.proxy_hits());
  18873. EXPECT_EQ(1, s.target_hits());
  18874. }
  18875. TEST(NoProxyTest, SubdomainBypasses) {
  18876. ProxyAndTargetServers s;
  18877. auto cli = make_client("foo.example.com", s);
  18878. cli->set_no_proxy({"example.com"});
  18879. auto res = cli->Get("/");
  18880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18881. EXPECT_EQ(0, s.proxy_hits());
  18882. EXPECT_EQ(1, s.target_hits());
  18883. }
  18884. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  18885. // Regression guard: "evilexample.com" must not be considered a subdomain
  18886. // of "example.com". Without the dot-boundary rule, a naive endsWith
  18887. // check would let traffic bypass the proxy and leak credentials direct
  18888. // to the attacker host.
  18889. ProxyAndTargetServers s;
  18890. auto cli = make_client("evilexample.com", s);
  18891. cli->set_no_proxy({"example.com"});
  18892. auto res = cli->Get("/");
  18893. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18894. EXPECT_GE(s.proxy_hits(), 1);
  18895. EXPECT_EQ(0, s.target_hits());
  18896. }
  18897. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  18898. ProxyAndTargetServers s;
  18899. auto cli = make_client("example.com.evil.com", s);
  18900. cli->set_no_proxy({"example.com"});
  18901. auto res = cli->Get("/");
  18902. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18903. EXPECT_GE(s.proxy_hits(), 1);
  18904. EXPECT_EQ(0, s.target_hits());
  18905. }
  18906. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  18907. ProxyAndTargetServers s;
  18908. auto cli = make_client("example.com", s);
  18909. cli->set_no_proxy({".example.com"});
  18910. auto res = cli->Get("/");
  18911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18912. EXPECT_EQ(0, s.proxy_hits());
  18913. EXPECT_EQ(1, s.target_hits());
  18914. }
  18915. TEST(NoProxyTest, CaseInsensitiveHostname) {
  18916. ProxyAndTargetServers s;
  18917. auto cli = make_client("Example.COM", s);
  18918. cli->set_no_proxy({"EXAMPLE.com"});
  18919. auto res = cli->Get("/");
  18920. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18921. EXPECT_EQ(0, s.proxy_hits());
  18922. EXPECT_EQ(1, s.target_hits());
  18923. }
  18924. TEST(NoProxyTest, TrailingDotIsNormalized) {
  18925. ProxyAndTargetServers s;
  18926. auto cli = make_client("example.com.", s);
  18927. cli->set_no_proxy({"example.com"});
  18928. auto res = cli->Get("/");
  18929. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18930. EXPECT_EQ(0, s.proxy_hits());
  18931. EXPECT_EQ(1, s.target_hits());
  18932. }
  18933. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  18934. // Trailing dots must be normalized on BOTH sides — host and entry.
  18935. // An implementation that only strips the host-side trailing dot would
  18936. // fail to match host "example.com" against entry "example.com." because
  18937. // a literal substring search would compare 11 chars against 12.
  18938. ProxyAndTargetServers s;
  18939. auto cli = make_client("example.com", s);
  18940. cli->set_no_proxy({"example.com."});
  18941. auto res = cli->Get("/");
  18942. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18943. EXPECT_EQ(0, s.proxy_hits());
  18944. EXPECT_EQ(1, s.target_hits());
  18945. }
  18946. TEST(NoProxyTest, WildcardBypassesEverything) {
  18947. ProxyAndTargetServers s;
  18948. auto cli = make_client("anything.invalid.test", s);
  18949. cli->set_no_proxy({"*"});
  18950. auto res = cli->Get("/");
  18951. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18952. EXPECT_EQ(0, s.proxy_hits());
  18953. EXPECT_EQ(1, s.target_hits());
  18954. }
  18955. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  18956. ProxyAndTargetServers s;
  18957. Client cli("127.0.0.1", s.target_port());
  18958. cli.set_proxy("127.0.0.1", s.proxy_port());
  18959. cli.set_no_proxy({"127.0.0.1"});
  18960. auto res = cli.Get("/");
  18961. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18962. EXPECT_EQ(0, s.proxy_hits());
  18963. EXPECT_EQ(1, s.target_hits());
  18964. }
  18965. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  18966. ProxyAndTargetServers s;
  18967. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  18968. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  18969. cli.set_proxy("127.0.0.1", s.proxy_port());
  18970. cli.set_no_proxy({"::1"});
  18971. auto res = cli.Get("/");
  18972. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18973. EXPECT_EQ(0, s.proxy_hits());
  18974. EXPECT_EQ(1, s.target_hits());
  18975. }
  18976. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  18977. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  18978. // must still be recognized as IPv6 for CIDR matching. Implementations
  18979. // that detect IPv6 only when the host begins with '[' would parse the
  18980. // host as a hostname and miss the match.
  18981. ProxyAndTargetServers s;
  18982. Client cli("fe80::1", s.target_port());
  18983. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  18984. cli.set_proxy("127.0.0.1", s.proxy_port());
  18985. cli.set_no_proxy({"fe80::/10"});
  18986. auto res = cli.Get("/");
  18987. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18988. EXPECT_EQ(0, s.proxy_hits());
  18989. EXPECT_EQ(1, s.target_hits());
  18990. }
  18991. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  18992. ProxyAndTargetServers s;
  18993. Client cli("::1", s.target_port());
  18994. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  18995. cli.set_proxy("127.0.0.1", s.proxy_port());
  18996. cli.set_no_proxy({"[::1]"});
  18997. auto res = cli.Get("/");
  18998. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18999. EXPECT_EQ(0, s.proxy_hits());
  19000. EXPECT_EQ(1, s.target_hits());
  19001. }
  19002. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  19003. ProxyAndTargetServers s;
  19004. Client cli("fe80::1", s.target_port());
  19005. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  19006. cli.set_proxy("127.0.0.1", s.proxy_port());
  19007. cli.set_no_proxy({"[fe80::]/10"});
  19008. auto res = cli.Get("/");
  19009. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19010. EXPECT_EQ(0, s.proxy_hits());
  19011. EXPECT_EQ(1, s.target_hits());
  19012. }
  19013. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  19014. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  19015. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  19016. // tricks via address-family conversion.
  19017. ProxyAndTargetServers s;
  19018. Client cli("::ffff:127.0.0.1", s.target_port());
  19019. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  19020. cli.set_proxy("127.0.0.1", s.proxy_port());
  19021. cli.set_no_proxy({"127.0.0.1"});
  19022. auto res = cli.Get("/");
  19023. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19024. EXPECT_GE(s.proxy_hits(), 1);
  19025. EXPECT_EQ(0, s.target_hits());
  19026. }
  19027. TEST(NoProxyTest, IPv4CidrMatch) {
  19028. ProxyAndTargetServers s;
  19029. Client cli("127.0.0.1", s.target_port());
  19030. cli.set_proxy("127.0.0.1", s.proxy_port());
  19031. cli.set_no_proxy({"127.0.0.0/8"});
  19032. auto res = cli.Get("/");
  19033. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19034. EXPECT_EQ(0, s.proxy_hits());
  19035. EXPECT_EQ(1, s.target_hits());
  19036. }
  19037. TEST(NoProxyTest, IPv4CidrNonMatch) {
  19038. ProxyAndTargetServers s;
  19039. Client cli("127.0.0.1", s.target_port());
  19040. cli.set_proxy("127.0.0.1", s.proxy_port());
  19041. cli.set_no_proxy({"10.0.0.0/8"});
  19042. auto res = cli.Get("/");
  19043. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19044. EXPECT_GE(s.proxy_hits(), 1);
  19045. EXPECT_EQ(0, s.target_hits());
  19046. }
  19047. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  19048. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  19049. // IPv4 target matches.
  19050. ProxyAndTargetServers s;
  19051. Client cli("127.0.0.1", s.target_port());
  19052. cli.set_proxy("127.0.0.1", s.proxy_port());
  19053. cli.set_no_proxy({"0.0.0.0/0"});
  19054. auto res = cli.Get("/");
  19055. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19056. EXPECT_EQ(0, s.proxy_hits());
  19057. EXPECT_EQ(1, s.target_hits());
  19058. }
  19059. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  19060. ProxyAndTargetServers s;
  19061. Client cli("127.0.0.1", s.target_port());
  19062. cli.set_proxy("127.0.0.1", s.proxy_port());
  19063. cli.set_no_proxy({"127.0.0.1"});
  19064. auto res = cli.Get("/");
  19065. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19066. EXPECT_EQ(0, s.proxy_hits());
  19067. EXPECT_EQ(1, s.target_hits());
  19068. }
  19069. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  19070. ProxyAndTargetServers s;
  19071. Client cli("127.0.0.1", s.target_port());
  19072. cli.set_proxy("127.0.0.1", s.proxy_port());
  19073. cli.set_no_proxy({"127.0.0.0/33"});
  19074. auto res = cli.Get("/");
  19075. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19076. EXPECT_GE(s.proxy_hits(), 1);
  19077. EXPECT_EQ(0, s.target_hits());
  19078. }
  19079. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  19080. // Empty prefix after the slash must be rejected, not silently treated as /32.
  19081. ProxyAndTargetServers s;
  19082. Client cli("127.0.0.1", s.target_port());
  19083. cli.set_proxy("127.0.0.1", s.proxy_port());
  19084. cli.set_no_proxy({"127.0.0.1/"});
  19085. auto res = cli.Get("/");
  19086. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19087. EXPECT_GE(s.proxy_hits(), 1);
  19088. EXPECT_EQ(0, s.target_hits());
  19089. }
  19090. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  19091. ProxyAndTargetServers s;
  19092. auto cli = make_client("internal.corp", s);
  19093. cli->set_proxy_basic_auth("u", "p");
  19094. cli->set_no_proxy({"internal.corp"});
  19095. auto res = cli->Get("/");
  19096. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19097. EXPECT_EQ(1, s.target_hits());
  19098. EXPECT_EQ(0, s.proxy_hits());
  19099. EXPECT_FALSE(s.last_had_proxy_authz())
  19100. << "Proxy-Authorization must not be sent direct to the target";
  19101. }
  19102. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  19103. ProxyAndTargetServers s;
  19104. auto cli = make_client("public.example", s);
  19105. cli->set_proxy_basic_auth("u", "p");
  19106. cli->set_no_proxy({"internal.corp"}); // does not match
  19107. auto res = cli->Get("/");
  19108. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19109. EXPECT_GE(s.proxy_hits(), 1);
  19110. EXPECT_TRUE(s.last_had_proxy_authz());
  19111. }
  19112. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  19113. ProxyAndTargetServers s;
  19114. auto cli = make_client("anything.test", s);
  19115. auto res = cli->Get("/");
  19116. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19117. EXPECT_GE(s.proxy_hits(), 1);
  19118. EXPECT_EQ(0, s.target_hits());
  19119. }
  19120. TEST(NoProxyTest, PortSpecificEntryRejected) {
  19121. ProxyAndTargetServers s;
  19122. auto cli = make_client("example.com", s);
  19123. cli->set_no_proxy({"example.com:8080"});
  19124. auto res = cli->Get("/");
  19125. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19126. EXPECT_GE(s.proxy_hits(), 1);
  19127. EXPECT_EQ(0, s.target_hits());
  19128. }
  19129. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  19130. ProxyAndTargetServers s;
  19131. auto cli = make_client("anything.test", s);
  19132. cli->set_no_proxy({"", " ", "\t"});
  19133. auto res = cli->Get("/");
  19134. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19135. EXPECT_GE(s.proxy_hits(), 1);
  19136. EXPECT_EQ(0, s.target_hits());
  19137. }
  19138. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  19139. // An entry with leading/trailing whitespace must still match — env-style
  19140. // values are commonly pasted with stray spaces and an implementation
  19141. // that feeds the raw token directly to inet_pton would fail to match
  19142. // valid CIDRs because of the spaces.
  19143. ProxyAndTargetServers s;
  19144. Client cli("127.0.0.1", s.target_port());
  19145. cli.set_proxy("127.0.0.1", s.proxy_port());
  19146. cli.set_no_proxy({" 127.0.0.0/8 "});
  19147. auto res = cli.Get("/");
  19148. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19149. EXPECT_EQ(0, s.proxy_hits());
  19150. EXPECT_EQ(1, s.target_hits());
  19151. }
  19152. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  19153. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  19154. // go direct and must NOT carry Proxy-Authorization.
  19155. std::atomic<int> proxy_hits{0};
  19156. std::atomic<int> target_hits{0};
  19157. std::atomic<bool> target_saw_authz{false};
  19158. no_proxy_test::ScopedServer proxy_mock, target;
  19159. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  19160. proxy_hits++;
  19161. res.status = 302;
  19162. res.set_header("Location", "http://127.0.0.1:" +
  19163. std::to_string(target.port()) + "/landed");
  19164. });
  19165. target.svr().Get(".*", [&](const Request &req, Response &res) {
  19166. target_hits++;
  19167. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  19168. res.set_content("direct", "text/plain");
  19169. });
  19170. proxy_mock.listen();
  19171. target.listen();
  19172. Client cli("public.example", target.port());
  19173. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  19174. cli.set_proxy("127.0.0.1", proxy_mock.port());
  19175. cli.set_proxy_basic_auth("u", "p");
  19176. cli.set_no_proxy({"127.0.0.1"});
  19177. cli.set_follow_location(true);
  19178. auto res = cli.Get("/redir");
  19179. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19180. EXPECT_GE(proxy_hits.load(), 1);
  19181. EXPECT_GE(target_hits.load(), 1);
  19182. EXPECT_FALSE(target_saw_authz.load());
  19183. }
  19184. #ifdef CPPHTTPLIB_SSL_ENABLED
  19185. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  19186. // Direct origin replying 407 must not trigger the digest retry; otherwise
  19187. // proxy creds would be sent to the (possibly hostile) origin.
  19188. std::atomic<int> target_hits{0};
  19189. std::atomic<bool> target_saw_proxy_authz{false};
  19190. no_proxy_test::ScopedServer target;
  19191. target.svr().Get(".*", [&](const Request &req, Response &res) {
  19192. target_hits++;
  19193. if (req.has_header("Proxy-Authorization")) {
  19194. target_saw_proxy_authz = true;
  19195. }
  19196. res.status = StatusCode::ProxyAuthenticationRequired_407;
  19197. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  19198. "nonce=\"abc\", algorithm=MD5");
  19199. });
  19200. target.listen();
  19201. // The proxy address is set to the target's port: the bypass MUST kick in;
  19202. // if it doesn't, the test still routes "via proxy" to the same server and
  19203. // the Proxy-Authorization assertion below catches the leak.
  19204. Client cli("evil.example", target.port());
  19205. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  19206. cli.set_proxy("127.0.0.1", target.port());
  19207. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  19208. cli.set_no_proxy({"evil.example"});
  19209. auto res = cli.Get("/x");
  19210. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19211. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  19212. EXPECT_EQ(1, target_hits.load());
  19213. EXPECT_FALSE(target_saw_proxy_authz.load());
  19214. }
  19215. #endif
  19216. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  19217. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  19218. std::atomic<int> proxy_hits{0};
  19219. std::atomic<int> bypass_hits{0};
  19220. std::atomic<bool> proxy_saw_c_url{false};
  19221. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  19222. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  19223. proxy_hits++;
  19224. if (req.path.find("/start") != std::string::npos) {
  19225. res.status = 302;
  19226. res.set_header("Location", "http://127.0.0.1:" +
  19227. std::to_string(bypass_server.port()) +
  19228. "/middle");
  19229. return;
  19230. }
  19231. if (req.path.find("/end") != std::string::npos) {
  19232. proxy_saw_c_url = true;
  19233. res.set_content("c-via-proxy", "text/plain");
  19234. return;
  19235. }
  19236. res.set_content("unexpected", "text/plain");
  19237. });
  19238. // public.example's "advertised" port is arbitrary (the request never lands
  19239. // there — it goes through the proxy), but use a dynamic value to stay
  19240. // friendly with sharded parallel runs.
  19241. int public_port = bypass_server.port();
  19242. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  19243. bypass_hits++;
  19244. res.status = 302;
  19245. res.set_header("Location", "http://public.example:" +
  19246. std::to_string(public_port) + "/end");
  19247. });
  19248. proxy_mock.listen();
  19249. bypass_server.listen();
  19250. Client cli("public.example", public_port);
  19251. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  19252. cli.set_proxy("127.0.0.1", proxy_mock.port());
  19253. cli.set_no_proxy({"127.0.0.1"});
  19254. cli.set_follow_location(true);
  19255. auto res = cli.Get("/start");
  19256. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19257. EXPECT_EQ(StatusCode::OK_200, res->status);
  19258. EXPECT_EQ("c-via-proxy", res->body);
  19259. EXPECT_GE(proxy_hits.load(), 2);
  19260. EXPECT_GE(bypass_hits.load(), 1);
  19261. EXPECT_TRUE(proxy_saw_c_url.load());
  19262. }
  19263. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  19264. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  19265. // request reconnects to the correct endpoint.
  19266. std::atomic<int> proxy_hits{0};
  19267. std::atomic<int> target_hits{0};
  19268. no_proxy_test::ScopedServer proxy_mock, target;
  19269. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  19270. proxy_hits++;
  19271. res.set_content("via-proxy", "text/plain");
  19272. });
  19273. target.svr().Get(".*", [&](const Request &, Response &res) {
  19274. target_hits++;
  19275. res.set_content("direct", "text/plain");
  19276. });
  19277. proxy_mock.listen();
  19278. target.listen();
  19279. Client cli("public.example", target.port());
  19280. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  19281. cli.set_proxy("127.0.0.1", proxy_mock.port());
  19282. cli.set_keep_alive(true);
  19283. auto res1 = cli.Get("/a");
  19284. ASSERT_TRUE(res1);
  19285. EXPECT_EQ("via-proxy", res1->body);
  19286. EXPECT_EQ(1, proxy_hits.load());
  19287. EXPECT_EQ(0, target_hits.load());
  19288. cli.set_no_proxy({"public.example"});
  19289. auto res2 = cli.Get("/b");
  19290. ASSERT_TRUE(res2);
  19291. EXPECT_EQ("direct", res2->body);
  19292. EXPECT_EQ(1, proxy_hits.load());
  19293. EXPECT_EQ(1, target_hits.load());
  19294. }
  19295. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  19296. namespace proxy_tunnel_test {
  19297. // SSLServer counterpart to no_proxy_test::ScopedServer.
  19298. class ScopedSSLServer {
  19299. public:
  19300. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  19301. port_ = svr_.bind_to_any_port("127.0.0.1");
  19302. }
  19303. ~ScopedSSLServer() {
  19304. svr_.stop();
  19305. if (th_.joinable()) { th_.join(); }
  19306. }
  19307. SSLServer &svr() { return svr_; }
  19308. int port() const { return port_; }
  19309. void listen() {
  19310. th_ = std::thread([this] { svr_.listen_after_bind(); });
  19311. svr_.wait_until_ready();
  19312. }
  19313. private:
  19314. SSLServer svr_;
  19315. std::thread th_;
  19316. int port_ = 0;
  19317. };
  19318. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  19319. class ScopedConnectProxy {
  19320. public:
  19321. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  19322. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  19323. if (listen_fd_ < 0) { return; }
  19324. int yes = 1;
  19325. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  19326. sockaddr_in a{};
  19327. a.sin_family = AF_INET;
  19328. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  19329. a.sin_port = 0;
  19330. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  19331. return;
  19332. }
  19333. socklen_t alen = sizeof(a);
  19334. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  19335. 0) {
  19336. return;
  19337. }
  19338. port_ = ntohs(a.sin_port);
  19339. if (::listen(listen_fd_, 1) != 0) { return; }
  19340. th_ = std::thread([this] { run(); });
  19341. }
  19342. ~ScopedConnectProxy() {
  19343. stop_ = true;
  19344. if (listen_fd_ >= 0) {
  19345. ::shutdown(listen_fd_, SHUT_RDWR);
  19346. ::close(listen_fd_);
  19347. }
  19348. if (th_.joinable()) { th_.join(); }
  19349. }
  19350. int port() const { return port_; }
  19351. int connect_hits() const { return connect_hits_.load(); }
  19352. private:
  19353. void run() {
  19354. while (!stop_.load()) {
  19355. fd_set rfds;
  19356. FD_ZERO(&rfds);
  19357. FD_SET(listen_fd_, &rfds);
  19358. timeval tv{0, 100 * 1000};
  19359. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  19360. if (sel <= 0) { continue; }
  19361. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  19362. if (client_fd < 0) { continue; }
  19363. std::string req;
  19364. char buf[2048];
  19365. while (req.find("\r\n\r\n") == std::string::npos) {
  19366. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  19367. if (n <= 0) { break; }
  19368. req.append(buf, static_cast<size_t>(n));
  19369. }
  19370. if (req.compare(0, 7, "CONNECT") != 0) {
  19371. ::close(client_fd);
  19372. continue;
  19373. }
  19374. connect_hits_++;
  19375. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  19376. ::send(client_fd, ok, std::strlen(ok), 0);
  19377. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  19378. sockaddr_in o{};
  19379. o.sin_family = AF_INET;
  19380. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  19381. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  19382. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  19383. 0) {
  19384. ::close(client_fd);
  19385. ::close(origin_fd);
  19386. continue;
  19387. }
  19388. auto forward = [](int from, int to) {
  19389. char b[8192];
  19390. for (;;) {
  19391. ssize_t n = ::recv(from, b, sizeof(b), 0);
  19392. if (n <= 0) { break; }
  19393. ssize_t off = 0;
  19394. while (off < n) {
  19395. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  19396. if (s <= 0) {
  19397. off = n;
  19398. break;
  19399. }
  19400. off += s;
  19401. }
  19402. }
  19403. ::shutdown(to, SHUT_WR);
  19404. };
  19405. std::thread t1([&] { forward(client_fd, origin_fd); });
  19406. std::thread t2([&] { forward(origin_fd, client_fd); });
  19407. t1.join();
  19408. t2.join();
  19409. ::close(client_fd);
  19410. ::close(origin_fd);
  19411. }
  19412. }
  19413. int forward_port_ = -1;
  19414. int listen_fd_ = -1;
  19415. int port_ = 0;
  19416. std::thread th_;
  19417. std::atomic<bool> stop_{false};
  19418. std::atomic<int> connect_hits_{0};
  19419. };
  19420. } // namespace proxy_tunnel_test
  19421. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  19422. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  19423. // retry; otherwise proxy creds would be sent to the origin.
  19424. std::atomic<int> origin_hits{0};
  19425. std::atomic<bool> origin_saw_proxy_authz{false};
  19426. proxy_tunnel_test::ScopedSSLServer origin;
  19427. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  19428. origin_hits++;
  19429. if (req.has_header("Proxy-Authorization")) {
  19430. origin_saw_proxy_authz = true;
  19431. }
  19432. res.status = StatusCode::ProxyAuthenticationRequired_407;
  19433. res.set_header("Proxy-Authenticate",
  19434. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  19435. "algorithm=MD5");
  19436. });
  19437. origin.listen();
  19438. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  19439. ASSERT_NE(0, proxy.port());
  19440. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  19441. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  19442. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  19443. // and answer with its own status, making this test flaky.
  19444. SSLClient cli("127.0.0.1", origin.port());
  19445. cli.enable_server_certificate_verification(false);
  19446. cli.set_proxy("127.0.0.1", proxy.port());
  19447. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  19448. auto res = cli.Get("/x");
  19449. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19450. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  19451. EXPECT_EQ(1, origin_hits.load());
  19452. EXPECT_FALSE(origin_saw_proxy_authz.load());
  19453. EXPECT_EQ(1, proxy.connect_hits());
  19454. }
  19455. #endif