test.cc 864 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725
  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(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  305. // accept() reports failures through WSAGetLastError() on Windows and through
  306. // errno everywhere else. Asking the wrong one is what made the accept loop
  307. // treat every recoverable failure as fatal on Windows.
  308. struct Classification {
  309. bool resource;
  310. bool transient;
  311. };
  312. auto classify = [](int err) {
  313. #ifdef _WIN32
  314. WSASetLastError(err);
  315. #else
  316. errno = err;
  317. #endif
  318. // Read both before asserting: an assertion may clobber the error slot.
  319. Classification c;
  320. c.resource = detail::is_accept_resource_error();
  321. c.transient = detail::is_accept_transient_error();
  322. return c;
  323. };
  324. #ifdef _WIN32
  325. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  326. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  327. WSAECONNRESET, WSAECONNABORTED};
  328. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  329. #else
  330. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  331. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  332. ECONNABORTED};
  333. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  334. #endif
  335. for (auto err : resource_errors) {
  336. const auto c = classify(err);
  337. EXPECT_TRUE(c.resource) << "error " << err;
  338. EXPECT_FALSE(c.transient) << "error " << err;
  339. }
  340. for (auto err : transient_errors) {
  341. const auto c = classify(err);
  342. EXPECT_TRUE(c.transient) << "error " << err;
  343. EXPECT_FALSE(c.resource) << "error " << err;
  344. }
  345. for (auto err : fatal_errors) {
  346. const auto c = classify(err);
  347. EXPECT_FALSE(c.resource) << "error " << err;
  348. EXPECT_FALSE(c.transient) << "error " << err;
  349. }
  350. #ifdef _WIN32
  351. WSASetLastError(0);
  352. #else
  353. errno = 0;
  354. #endif
  355. }
  356. TEST(ClientTest, MoveConstructible) {
  357. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  358. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  359. }
  360. TEST(ClientTest, MoveAssignable) {
  361. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  362. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  363. }
  364. #ifdef _WIN32
  365. TEST(StartupTest, WSAStartup) {
  366. WSADATA wsaData;
  367. int ret = WSAStartup(0x0002, &wsaData);
  368. ASSERT_EQ(0, ret);
  369. }
  370. #endif
  371. TEST(DecodePathTest, PercentCharacter) {
  372. EXPECT_EQ(
  373. decode_path_component(
  374. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  375. U8("descrip=Gastos áéíóúñÑ 6"));
  376. }
  377. TEST(DecodePathTest, PercentCharacterNUL) {
  378. string expected;
  379. expected.push_back('x');
  380. expected.push_back('\0');
  381. expected.push_back('x');
  382. EXPECT_EQ(decode_path_component("x%00x"), expected);
  383. }
  384. TEST(DecodePathTest, UnicodeEncoding) {
  385. // %u0041 = 'A' (1-byte UTF-8)
  386. EXPECT_EQ("A", decode_path_component("%u0041"));
  387. // %u00E9 = 'é' (2-byte UTF-8)
  388. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  389. // %u3042 = 'あ' (3-byte UTF-8)
  390. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  391. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  392. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  393. // %uD800 = surrogate (invalid, silently dropped)
  394. EXPECT_EQ("", decode_path_component("%uD800"));
  395. }
  396. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  397. // A sign or whitespace inside the two-character escape window must not be
  398. // accepted as a valid percent-encoding; the sequence is passed through
  399. // literally, matching decode_uri_component / decode_path_component.
  400. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  401. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  402. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  403. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  404. // Well-formed escapes still decode.
  405. EXPECT_EQ("-", decode_query_component("%2D", false));
  406. EXPECT_EQ("A", decode_query_component("%41", false));
  407. }
  408. TEST(SanitizeFilenameTest, VariousPatterns) {
  409. // Path traversal
  410. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  411. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  412. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  413. // Normal and edge cases
  414. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  415. EXPECT_EQ("filename.txt",
  416. httplib::sanitize_filename("/path/to/filename.txt"));
  417. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  418. EXPECT_EQ("", httplib::sanitize_filename(".."));
  419. EXPECT_EQ("", httplib::sanitize_filename(""));
  420. // Null bytes stripped
  421. EXPECT_EQ("safe.txt",
  422. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  423. // Whitespace-only rejected
  424. EXPECT_EQ("", httplib::sanitize_filename(" "));
  425. }
  426. // Forward declaration (see the base64_encode note below): split builds move the
  427. // definition into httplib.cc, so re-declaring it here lets the test link.
  428. namespace httplib {
  429. namespace detail {
  430. bool is_chunked_transfer_encoding(const Headers &headers);
  431. } // namespace detail
  432. } // namespace httplib
  433. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  434. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  435. auto make = [](std::initializer_list<const char *> lines) {
  436. Headers h;
  437. for (auto te : lines) {
  438. if (te) { h.emplace("Transfer-Encoding", te); }
  439. }
  440. return h;
  441. };
  442. // Sole coding, matched case-insensitively.
  443. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  444. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  445. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  446. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  447. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  448. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  449. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  450. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  451. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  452. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  453. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  454. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  455. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  456. // were received, into one list. Headers preserves that order, so the answer
  457. // is decided by the last coding of the last line and the order the lines
  458. // arrived in is significant.
  459. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  460. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  461. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  462. // The split can fall anywhere in the list.
  463. EXPECT_TRUE(
  464. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  465. EXPECT_FALSE(
  466. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  467. // A trailing line naming no coding leaves the list ending in nothing, so it
  468. // must not inherit the chunked from the line before it.
  469. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  470. }
  471. // Forward declaration: in split builds split.py strips `inline` and moves the
  472. // definition into httplib.cc, so detail::base64_encode is not visible from the
  473. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  474. // in both header-only and split builds.
  475. namespace httplib {
  476. namespace detail {
  477. std::string base64_encode(const std::string &in);
  478. } // namespace detail
  479. } // namespace httplib
  480. TEST(Base64EncodeTest, KnownAnswers) {
  481. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  482. // where the accumulator's top bit is already set before the next shift.
  483. EXPECT_EQ("", detail::base64_encode(""));
  484. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  485. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  486. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  487. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  488. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  489. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  490. // High bytes keep the top bit set across several rounds.
  491. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  492. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  493. }
  494. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  495. string unescapedCharacters = "-_.!~*'()";
  496. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  497. }
  498. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  499. string reservedCharacters = ";,/?:@&=+$";
  500. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  501. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  502. }
  503. TEST(ClientQueryOrder, PreserveOrder) {
  504. // This test reproduces Issue #2259: client may reorder query parameters
  505. // when sending a GET request. The expected behavior is that the client
  506. // preserves the original query string order when the caller supplied it
  507. // as part of the path.
  508. Server svr;
  509. svr.Get("/", [&](const Request &req, Response &res) {
  510. // Echo back the raw target so the test can assert ordering
  511. res.set_content(req.target, "text/plain");
  512. });
  513. std::thread t{[&] { svr.listen(HOST, PORT); }};
  514. auto se = detail::scope_exit([&] {
  515. svr.stop();
  516. t.join();
  517. ASSERT_FALSE(svr.is_running());
  518. });
  519. svr.wait_until_ready();
  520. Client cli(HOST, PORT);
  521. ASSERT_TRUE(cli.is_valid());
  522. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  523. auto res = cli.Get(original);
  524. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  525. // Expect the echoed target to exactly match the original path (order
  526. // preserved)
  527. EXPECT_EQ(res->body, original);
  528. }
  529. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  530. string chineseCharacters = U8("中国語");
  531. string russianCharacters = U8("дом");
  532. string brazilianCharacters = U8("óculos");
  533. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  534. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  535. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  536. "%D0%B4%D0%BE%D0%BC");
  537. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  538. }
  539. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  540. string unescapedCharacters = "-_.!~*'()";
  541. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  542. }
  543. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  544. string reservedCharacters = ";,/?:@&=+$";
  545. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  546. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  547. }
  548. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  549. string chineseCharacters = U8("中国語");
  550. string russianCharacters = U8("дом");
  551. string brazilianCharacters = U8("óculos");
  552. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  553. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  554. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  555. "%D0%B4%D0%BE%D0%BC");
  556. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  557. }
  558. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  559. // Issue #2082 use case: encoding path component with ampersand
  560. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  561. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  562. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  563. }
  564. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  565. string unescapedCharacters = "-_.!~*'()";
  566. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  567. }
  568. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  569. string reservedCharacters = ";,/?:@&=+$#";
  570. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  571. }
  572. TEST(EncodeUriTest, TestUTF8Characters) {
  573. string chineseCharacters = U8("中国語");
  574. string russianCharacters = U8("дом");
  575. string brazilianCharacters = U8("óculos");
  576. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  577. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  578. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  579. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  580. }
  581. TEST(EncodeUriTest, TestCompleteUri) {
  582. string uri =
  583. "https://example.com/path/to/resource?query=value&param=test#fragment";
  584. EXPECT_EQ(
  585. httplib::encode_uri(uri),
  586. "https://example.com/path/to/resource?query=value&param=test#fragment");
  587. }
  588. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  589. string uri =
  590. "https://example.com/path with spaces/file name.html?q=hello world";
  591. EXPECT_EQ(httplib::encode_uri(uri),
  592. "https://example.com/path%20with%20spaces/"
  593. "file%20name.html?q=hello%20world");
  594. }
  595. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  596. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  597. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  598. }
  599. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  600. string unescapedCharacters = "-_.!~*'()";
  601. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  602. }
  603. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  604. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  605. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  606. string encodedBrazilian = "%C3%B3culos";
  607. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  608. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  609. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  610. }
  611. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  612. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  613. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  614. "Piri Tommy Villiers - on & on");
  615. }
  616. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  617. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  618. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  619. }
  620. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  621. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  622. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  623. }
  624. TEST(DecodeUriTest, TestUTF8Characters) {
  625. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  626. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  627. string encodedBrazilian = "%C3%B3culos";
  628. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  629. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  630. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  631. }
  632. TEST(DecodeUriTest, TestCompleteUri) {
  633. string encodedUri = "https://example.com/path%20with%20spaces/"
  634. "file%20name.html?q=hello%20world";
  635. EXPECT_EQ(
  636. httplib::decode_uri(encodedUri),
  637. "https://example.com/path with spaces/file name.html?q=hello world");
  638. }
  639. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  640. string original =
  641. "https://example.com/path with spaces/file name.html?q=hello world";
  642. string encoded = httplib::encode_uri(original);
  643. string decoded = httplib::decode_uri(encoded);
  644. EXPECT_EQ(decoded, original);
  645. }
  646. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  647. // decode_uri is the inverse of encode_uri: an escaped reserved character
  648. // stays encoded so it is not promoted into a real delimiter, while
  649. // non-reserved escapes still decode (like JS decodeURI).
  650. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  651. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  652. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  653. "%3F%3A%40%26%3D%2B%24%2C%3B");
  654. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  655. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  656. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  657. "http://example.com/a%2Fb");
  658. // decode_uri_component still decodes the reserved character.
  659. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  660. }
  661. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  662. string original = "Piri Tommy Villiers - on & on";
  663. string encoded = httplib::encode_uri_component(original);
  664. string decoded = httplib::decode_uri_component(encoded);
  665. EXPECT_EQ(decoded, original);
  666. }
  667. TEST(TrimTests, TrimStringTests) {
  668. EXPECT_EQ("abc", detail::trim_copy("abc"));
  669. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  670. EXPECT_TRUE(detail::trim_copy("").empty());
  671. }
  672. TEST(AsciiTest, LocaleIndependentClassification) {
  673. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  674. // which consult the global C locale: std::isalnum(0xC5) can return true
  675. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  676. // helpers must classify every byte by the ASCII grammar alone.
  677. for (int i = 0; i < 256; i++) {
  678. auto c = static_cast<char>(i);
  679. auto is_digit = i >= '0' && i <= '9';
  680. auto is_upper = i >= 'A' && i <= 'Z';
  681. auto is_lower = i >= 'a' && i <= 'z';
  682. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  683. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  684. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  685. << "byte " << i;
  686. }
  687. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  688. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  689. // Non-ASCII bytes must be percent-encoded, never passed through as
  690. // alphanumeric.
  691. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  692. }
  693. TEST(FromCharsTest, Double) {
  694. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  695. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  696. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  697. auto parse = [](const std::string &s, double &v) {
  698. return detail::from_chars(s.data(), s.data() + s.size(), v);
  699. };
  700. double v = -1.0;
  701. // Representative quality values.
  702. EXPECT_EQ(parse("0", v).ec, std::errc{});
  703. EXPECT_DOUBLE_EQ(v, 0.0);
  704. EXPECT_EQ(parse("1", v).ec, std::errc{});
  705. EXPECT_DOUBLE_EQ(v, 1.0);
  706. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  707. EXPECT_DOUBLE_EQ(v, 0.8);
  708. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  709. EXPECT_DOUBLE_EQ(v, 0.001);
  710. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  711. EXPECT_DOUBLE_EQ(v, 1.0);
  712. // A missing integer or fractional part is tolerated.
  713. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  714. EXPECT_DOUBLE_EQ(v, 0.5);
  715. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  716. EXPECT_DOUBLE_EQ(v, 5.0);
  717. // Values outside [0, 1] still parse; the caller range-checks them.
  718. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  719. EXPECT_DOUBLE_EQ(v, 123.456);
  720. // Stops at the first byte that is not part of the number and reports where.
  721. std::string trailing = "0.9, text/html";
  722. auto r = parse(trailing, v);
  723. EXPECT_EQ(r.ec, std::errc{});
  724. EXPECT_DOUBLE_EQ(v, 0.9);
  725. EXPECT_EQ(*r.ptr, ',');
  726. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  727. // outright, and an 'e'/'E' simply ends the number.
  728. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  729. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  730. std::string exp_input = "1.5e3";
  731. r = parse(exp_input, v);
  732. EXPECT_EQ(r.ec, std::errc{});
  733. EXPECT_DOUBLE_EQ(v, 1.5);
  734. EXPECT_EQ(*r.ptr, 'e');
  735. // Invalid inputs.
  736. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  737. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  738. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  739. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  740. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  741. // Pathological but well-formed inputs must stay bounded (no overflow, no
  742. // out-of-bounds table access) and stay within [0, 1] for the caller.
  743. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  744. std::errc{});
  745. EXPECT_DOUBLE_EQ(v, 0.0);
  746. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  747. std::errc{});
  748. EXPECT_GE(v, 0.0);
  749. EXPECT_LE(v, 1.0);
  750. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  751. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  752. }
  753. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  754. // Simple case without quality values
  755. std::vector<std::string> result1;
  756. EXPECT_TRUE(detail::parse_accept_header(
  757. "text/html,application/json,text/plain", result1));
  758. EXPECT_EQ(result1.size(), 3U);
  759. EXPECT_EQ(result1[0], "text/html");
  760. EXPECT_EQ(result1[1], "application/json");
  761. EXPECT_EQ(result1[2], "text/plain");
  762. // With quality values
  763. std::vector<std::string> result2;
  764. EXPECT_TRUE(detail::parse_accept_header(
  765. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  766. EXPECT_EQ(result2.size(), 3U);
  767. EXPECT_EQ(result2[0], "application/json"); // highest q value
  768. EXPECT_EQ(result2[1], "text/html");
  769. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  770. }
  771. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  772. // Mixed with and without quality values
  773. std::vector<std::string> result;
  774. EXPECT_TRUE(detail::parse_accept_header(
  775. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  776. EXPECT_EQ(result.size(), 3U);
  777. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  778. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  779. EXPECT_EQ(result[2], "application/json"); // q=0.5
  780. }
  781. TEST(ParseAcceptHeaderTest, EdgeCases) {
  782. // Empty header
  783. std::vector<std::string> empty_result;
  784. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  785. EXPECT_TRUE(empty_result.empty());
  786. // Single type
  787. std::vector<std::string> single_result;
  788. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  789. EXPECT_EQ(single_result.size(), 1U);
  790. EXPECT_EQ(single_result[0], "application/json");
  791. // Wildcard types
  792. std::vector<std::string> wildcard_result;
  793. EXPECT_TRUE(detail::parse_accept_header(
  794. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  795. EXPECT_EQ(wildcard_result.size(), 3U);
  796. EXPECT_EQ(wildcard_result[0], "application/json");
  797. EXPECT_EQ(wildcard_result[1], "text/*");
  798. EXPECT_EQ(wildcard_result[2], "*/*");
  799. }
  800. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  801. // Common browser Accept header
  802. std::vector<std::string> browser_result;
  803. EXPECT_TRUE(
  804. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  805. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  806. browser_result));
  807. EXPECT_EQ(browser_result.size(), 6U);
  808. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  809. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  810. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  811. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  812. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  813. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  814. // API client header
  815. std::vector<std::string> api_result;
  816. EXPECT_TRUE(detail::parse_accept_header(
  817. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  818. api_result));
  819. EXPECT_EQ(api_result.size(), 3U);
  820. EXPECT_EQ(api_result[0], "application/json");
  821. EXPECT_EQ(api_result[1], "application/xml");
  822. EXPECT_EQ(api_result[2], "text/plain");
  823. }
  824. TEST(ParseAcceptHeaderTest, SpecialCases) {
  825. // Quality value with 3 decimal places
  826. std::vector<std::string> decimal_result;
  827. EXPECT_TRUE(detail::parse_accept_header(
  828. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  829. EXPECT_EQ(decimal_result.size(), 2U);
  830. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  831. EXPECT_EQ(decimal_result[1], "text/html");
  832. // Zero quality (should still be included but with lowest priority)
  833. std::vector<std::string> zero_q_result;
  834. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  835. zero_q_result));
  836. EXPECT_EQ(zero_q_result.size(), 2U);
  837. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  838. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  839. // No spaces around commas
  840. std::vector<std::string> no_space_result;
  841. EXPECT_TRUE(detail::parse_accept_header(
  842. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  843. no_space_result));
  844. EXPECT_EQ(no_space_result.size(), 3U);
  845. EXPECT_EQ(no_space_result[0], "text/html");
  846. EXPECT_EQ(no_space_result[1], "application/json");
  847. EXPECT_EQ(no_space_result[2], "text/plain");
  848. }
  849. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  850. // Quality values always use '.' as the decimal separator, so parsing must
  851. // not depend on the process locale. An embedding application may have
  852. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  853. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  854. std::string saved = cur ? cur : "C";
  855. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  856. "fr_FR.UTF-8"};
  857. bool switched = false;
  858. for (const auto loc : comma_locales) {
  859. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  860. std::localeconv()->decimal_point[0] == ',') {
  861. switched = true;
  862. break;
  863. }
  864. }
  865. if (!switched) {
  866. std::setlocale(LC_NUMERIC, saved.c_str());
  867. GTEST_SKIP() << "no comma-decimal locale available on this host";
  868. }
  869. // The higher-weighted type appears later in the list, so a correct parse
  870. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  871. // sensitive parse reads both weights as 0 and leaves the original order.
  872. std::vector<std::string> result;
  873. EXPECT_TRUE(detail::parse_accept_header(
  874. "application/json;q=0.1,text/html;q=0.9", result));
  875. ASSERT_EQ(result.size(), 2U);
  876. EXPECT_EQ(result[0], "text/html");
  877. EXPECT_EQ(result[1], "application/json");
  878. std::setlocale(LC_NUMERIC, saved.c_str());
  879. }
  880. TEST(ParseAcceptHeaderTest, InvalidCases) {
  881. std::vector<std::string> result;
  882. // Invalid quality value (> 1.0)
  883. EXPECT_FALSE(
  884. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  885. // Invalid quality value (< 0.0)
  886. EXPECT_FALSE(
  887. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  888. // Invalid quality value (not a number)
  889. EXPECT_FALSE(detail::parse_accept_header(
  890. "text/html;q=invalid,application/json", result));
  891. // A valid numeric prefix does not make the entire quality value valid.
  892. EXPECT_FALSE(detail::parse_accept_header(
  893. "text/html;q=0.5junk,application/json", result));
  894. // Empty quality value
  895. EXPECT_FALSE(
  896. detail::parse_accept_header("text/html;q=,application/json", result));
  897. // Invalid media type format (no slash and not wildcard)
  898. EXPECT_FALSE(
  899. detail::parse_accept_header("invalidtype,application/json", result));
  900. // Valid cases should still work
  901. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  902. EXPECT_EQ(result.size(), 1U);
  903. EXPECT_EQ(result[0], "*/*");
  904. EXPECT_TRUE(detail::parse_accept_header("*", result));
  905. EXPECT_EQ(result.size(), 1U);
  906. EXPECT_EQ(result[0], "*");
  907. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  908. EXPECT_EQ(result.size(), 1U);
  909. EXPECT_EQ(result[0], "text/*");
  910. }
  911. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  912. // elements, so a leading, trailing or doubled comma is a legal Accept value
  913. // and must not be answered with 400 Bad Request.
  914. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  915. struct {
  916. const char *value;
  917. std::vector<std::string> expected;
  918. } cases[] = {
  919. {",application/json", {"application/json"}},
  920. {"text/html,", {"text/html"}},
  921. {"text/html,,*/*", {"text/html", "*/*"}},
  922. // An empty element may be spelled with whitespace in it
  923. {"text/html, , application/json", {"text/html", "application/json"}},
  924. // Nothing but empty elements is an empty list, which means the same
  925. // thing as no Accept header at all
  926. {",,,", {}},
  927. // Quality values still apply across ignored empty elements
  928. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  929. };
  930. for (const auto &c : cases) {
  931. std::vector<std::string> result;
  932. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  933. << "value: " << c.value;
  934. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  935. }
  936. // An invalid entry is still rejected when empty elements surround it
  937. std::vector<std::string> result;
  938. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  939. }
  940. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  941. Server svr;
  942. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  943. EXPECT_EQ(req.accept_content_types.size(), 3U);
  944. EXPECT_EQ(req.accept_content_types[0], "application/json");
  945. EXPECT_EQ(req.accept_content_types[1], "text/html");
  946. EXPECT_EQ(req.accept_content_types[2], "*/*");
  947. res.set_content("ok", "text/plain");
  948. });
  949. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  950. EXPECT_TRUE(false);
  951. res.set_content("bad request", "text/plain");
  952. });
  953. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  954. auto se = detail::scope_exit([&] {
  955. svr.stop();
  956. listen_thread.join();
  957. ASSERT_FALSE(svr.is_running());
  958. });
  959. svr.wait_until_ready();
  960. Client cli("localhost", PORT);
  961. {
  962. auto res = cli.Get(
  963. "/accept_ok",
  964. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  965. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  966. EXPECT_EQ(StatusCode::OK_200, res->status);
  967. }
  968. {
  969. auto res = cli.Get("/accept_bad_request",
  970. Headers{{"Accept", "text/html;q=abc,application/json"}});
  971. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  972. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  973. }
  974. }
  975. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  976. Server svr;
  977. svr.Get("/", [](const Request & /*req*/, Response &res) {
  978. res.set_content("ok", "text/plain");
  979. });
  980. std::atomic<int> start_count{0};
  981. std::atomic<bool> running_when_called{false};
  982. svr.set_start_handler([&]() {
  983. running_when_called = svr.is_running();
  984. start_count++;
  985. });
  986. auto port = svr.bind_to_any_port(HOST);
  987. std::thread t([&]() { svr.listen_after_bind(); });
  988. auto se = detail::scope_exit([&] {
  989. svr.stop();
  990. t.join();
  991. ASSERT_FALSE(svr.is_running());
  992. });
  993. svr.wait_until_ready();
  994. // A successful request proves the accept loop is running, which the start
  995. // handler precedes; so by now the handler must have run exactly once.
  996. Client cli(HOST, port);
  997. cli.set_connection_timeout(std::chrono::seconds(5));
  998. auto res = cli.Get("/");
  999. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1000. EXPECT_EQ(StatusCode::OK_200, res->status);
  1001. EXPECT_EQ(1, start_count.load());
  1002. EXPECT_TRUE(running_when_called.load());
  1003. }
  1004. TEST(DivideTest, DivideStringTests) {
  1005. auto divide = [](const std::string &str, char d) {
  1006. std::string lhs;
  1007. std::string rhs;
  1008. detail::divide(str, d,
  1009. [&](const char *lhs_data, std::size_t lhs_size,
  1010. const char *rhs_data, std::size_t rhs_size) {
  1011. lhs.assign(lhs_data, lhs_size);
  1012. rhs.assign(rhs_data, rhs_size);
  1013. });
  1014. return std::make_pair(std::move(lhs), std::move(rhs));
  1015. };
  1016. {
  1017. const auto res = divide("", '=');
  1018. EXPECT_EQ(res.first, "");
  1019. EXPECT_EQ(res.second, "");
  1020. }
  1021. {
  1022. const auto res = divide("=", '=');
  1023. EXPECT_EQ(res.first, "");
  1024. EXPECT_EQ(res.second, "");
  1025. }
  1026. {
  1027. const auto res = divide(" ", '=');
  1028. EXPECT_EQ(res.first, " ");
  1029. EXPECT_EQ(res.second, "");
  1030. }
  1031. {
  1032. const auto res = divide("a", '=');
  1033. EXPECT_EQ(res.first, "a");
  1034. EXPECT_EQ(res.second, "");
  1035. }
  1036. {
  1037. const auto res = divide("a=", '=');
  1038. EXPECT_EQ(res.first, "a");
  1039. EXPECT_EQ(res.second, "");
  1040. }
  1041. {
  1042. const auto res = divide("=b", '=');
  1043. EXPECT_EQ(res.first, "");
  1044. EXPECT_EQ(res.second, "b");
  1045. }
  1046. {
  1047. const auto res = divide("a=b", '=');
  1048. EXPECT_EQ(res.first, "a");
  1049. EXPECT_EQ(res.second, "b");
  1050. }
  1051. {
  1052. const auto res = divide("a=b=", '=');
  1053. EXPECT_EQ(res.first, "a");
  1054. EXPECT_EQ(res.second, "b=");
  1055. }
  1056. {
  1057. const auto res = divide("a=b=c", '=');
  1058. EXPECT_EQ(res.first, "a");
  1059. EXPECT_EQ(res.second, "b=c");
  1060. }
  1061. }
  1062. TEST(SplitTest, ParseQueryString) {
  1063. string s = "key1=val1&key2=val2&key3=val3";
  1064. Params dic;
  1065. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1066. [&](const char *b, const char *e) {
  1067. string key, val;
  1068. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1069. if (key.empty()) {
  1070. key.assign(b2, e2);
  1071. } else {
  1072. val.assign(b2, e2);
  1073. }
  1074. });
  1075. dic.emplace(key, val);
  1076. });
  1077. EXPECT_EQ("val1", dic.find("key1")->second);
  1078. EXPECT_EQ("val2", dic.find("key2")->second);
  1079. EXPECT_EQ("val3", dic.find("key3")->second);
  1080. }
  1081. TEST(SplitTest, ParseInvalidQueryTests) {
  1082. {
  1083. string s = " ";
  1084. Params dict;
  1085. detail::parse_query_text(s, dict);
  1086. EXPECT_TRUE(dict.empty());
  1087. }
  1088. {
  1089. string s = " = =";
  1090. Params dict;
  1091. detail::parse_query_text(s, dict);
  1092. EXPECT_TRUE(dict.empty());
  1093. }
  1094. }
  1095. TEST(ParseQueryTest, ParseQueryString) {
  1096. {
  1097. std::string s = "key1=val1&key2=val2&key3=val3";
  1098. Params dic;
  1099. detail::parse_query_text(s, dic);
  1100. EXPECT_EQ("val1", dic.find("key1")->second);
  1101. EXPECT_EQ("val2", dic.find("key2")->second);
  1102. EXPECT_EQ("val3", dic.find("key3")->second);
  1103. }
  1104. {
  1105. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1106. Params dic;
  1107. detail::parse_query_text(s, dic);
  1108. EXPECT_EQ("", dic.find("key1")->second);
  1109. EXPECT_EQ("val1", dic.find("key2")->second);
  1110. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1111. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1112. }
  1113. }
  1114. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1115. Params dic;
  1116. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1117. dic.emplace("key1", "val1");
  1118. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1119. dic.emplace("key2", "val2");
  1120. dic.emplace("key3", "val3");
  1121. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1122. }
  1123. // Joins every entry of a Headers or Params into "key=value " so a whole
  1124. // traversal can be compared in one assertion. Both are instantiations of the
  1125. // same insertion-ordered container, so one helper serves both.
  1126. template <typename Map> static std::string entries_to_string(const Map &m) {
  1127. std::string s;
  1128. for (const auto &entry : m) {
  1129. s += entry.first + "=" + entry.second + " ";
  1130. }
  1131. return s;
  1132. }
  1133. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1134. // Params used to be a std::multimap, which sorted by name and handed the
  1135. // caller's query back alphabetised. A client signing its query string could
  1136. // not reproduce the order it asked for.
  1137. Params dic;
  1138. dic.emplace("zulu", "1");
  1139. dic.emplace("alpha", "2");
  1140. dic.emplace("mike", "3");
  1141. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1142. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1143. }
  1144. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1145. Params dic;
  1146. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1147. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1148. }
  1149. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1150. Request req;
  1151. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1152. req.params);
  1153. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1154. EXPECT_EQ("first", req.get_param_value("tag"));
  1155. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1156. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1157. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1158. EXPECT_EQ("", req.get_param_value("tag", 3));
  1159. }
  1160. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1161. // Params shares its container with Headers, which matches field names
  1162. // case-insensitively. Parameter names must not pick that up.
  1163. Params dic;
  1164. dic.emplace("Key", "upper");
  1165. dic.emplace("key", "lower");
  1166. EXPECT_EQ(2U, dic.size());
  1167. EXPECT_EQ(1U, dic.count("Key"));
  1168. EXPECT_EQ(1U, dic.count("key"));
  1169. EXPECT_EQ("upper", dic.find("Key")->second);
  1170. EXPECT_EQ("lower", dic.find("key")->second);
  1171. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1172. }
  1173. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1174. Server svr;
  1175. std::string order;
  1176. svr.Get("/order", [&](const Request &req, Response &res) {
  1177. order = entries_to_string(req.params);
  1178. res.set_content("ok", "text/plain");
  1179. });
  1180. auto port = svr.bind_to_any_port(HOST);
  1181. thread t = thread([&] { svr.listen_after_bind(); });
  1182. auto se = detail::scope_exit([&] {
  1183. svr.stop();
  1184. t.join();
  1185. ASSERT_FALSE(svr.is_running());
  1186. });
  1187. svr.wait_until_ready();
  1188. Client cli(HOST, port);
  1189. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1190. ASSERT_TRUE(res);
  1191. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1192. }
  1193. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1194. Server svr;
  1195. std::string field_order, file_order;
  1196. svr.Post("/order", [&](const Request &req, Response &res) {
  1197. for (const auto &field : req.form.fields) {
  1198. field_order += field.first + "=" + field.second.content + " ";
  1199. }
  1200. for (const auto &file : req.form.files) {
  1201. file_order += file.first + "=" + file.second.filename + " ";
  1202. }
  1203. res.set_content("ok", "text/plain");
  1204. });
  1205. auto port = svr.bind_to_any_port(HOST);
  1206. thread t = thread([&] { svr.listen_after_bind(); });
  1207. auto se = detail::scope_exit([&] {
  1208. svr.stop();
  1209. t.join();
  1210. ASSERT_FALSE(svr.is_running());
  1211. });
  1212. svr.wait_until_ready();
  1213. UploadFormDataItems items = {
  1214. {"zulu", "1", "", ""},
  1215. {"alpha", "2", "", ""},
  1216. {"mike", "3", "", ""},
  1217. {"zebra", "z", "z.txt", "text/plain"},
  1218. {"apple", "a", "a.txt", "text/plain"},
  1219. };
  1220. Client cli(HOST, port);
  1221. auto res = cli.Post("/order", items);
  1222. ASSERT_TRUE(res);
  1223. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1224. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1225. }
  1226. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1227. Server svr;
  1228. std::vector<std::string> values;
  1229. std::string first, second, out_of_range, order;
  1230. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1231. values = req.form.get_fields("tag");
  1232. first = req.form.get_field("tag", 0);
  1233. second = req.form.get_field("tag", 1);
  1234. out_of_range = req.form.get_field("tag", 2);
  1235. for (const auto &field : req.form.fields) {
  1236. order += field.first + "=" + field.second.content + " ";
  1237. }
  1238. res.set_content("ok", "text/plain");
  1239. });
  1240. auto port = svr.bind_to_any_port(HOST);
  1241. thread t = thread([&] { svr.listen_after_bind(); });
  1242. auto se = detail::scope_exit([&] {
  1243. svr.stop();
  1244. t.join();
  1245. ASSERT_FALSE(svr.is_running());
  1246. });
  1247. svr.wait_until_ready();
  1248. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1249. // not adjacent in the container.
  1250. UploadFormDataItems items = {
  1251. {"tag", "first", "", ""},
  1252. {"other", "x", "", ""},
  1253. {"tag", "second", "", ""},
  1254. };
  1255. Client cli(HOST, port);
  1256. auto res = cli.Post("/repeated", items);
  1257. ASSERT_TRUE(res);
  1258. ASSERT_EQ(2U, values.size());
  1259. EXPECT_EQ("first", values[0]);
  1260. EXPECT_EQ("second", values[1]);
  1261. EXPECT_EQ("first", first);
  1262. EXPECT_EQ("second", second);
  1263. // std::multimap already kept entries sharing a name in insertion order, so
  1264. // everything above passes without this change too. The whole traversal is
  1265. // what tells the two apart: sorting by name would hoist "other" to the front
  1266. // and the two "tag" parts would end up adjacent.
  1267. EXPECT_EQ("tag=first other=x tag=second ", order);
  1268. // Advancing past the last entry of a name used to run off the container;
  1269. // the container's saturating increment makes it return the default instead.
  1270. EXPECT_EQ("", out_of_range);
  1271. }
  1272. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1273. // Server::read_content() keeps a FormFields::iterator alive across the
  1274. // content callbacks that fill the part it points at. The container is
  1275. // vector-backed, so a later emplace can reallocate and invalidate an older
  1276. // iterator; 64 parts grow the vector through seven reallocations, which
  1277. // checks that every part's content still lands in its own entry.
  1278. const size_t part_count = 64;
  1279. // One formula for both the parts sent and the values expected back, so the
  1280. // two cannot drift apart.
  1281. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1282. auto content_of = [](size_t i) {
  1283. return std::string(64, static_cast<char>('a' + (i % 26)));
  1284. };
  1285. Server svr;
  1286. std::vector<std::pair<std::string, std::string>> received;
  1287. svr.Post("/many", [&](const Request &req, Response &res) {
  1288. for (const auto &field : req.form.fields) {
  1289. received.emplace_back(field.first, field.second.content);
  1290. }
  1291. res.set_content("ok", "text/plain");
  1292. });
  1293. auto port = svr.bind_to_any_port(HOST);
  1294. thread t = thread([&] { svr.listen_after_bind(); });
  1295. auto se = detail::scope_exit([&] {
  1296. svr.stop();
  1297. t.join();
  1298. ASSERT_FALSE(svr.is_running());
  1299. });
  1300. svr.wait_until_ready();
  1301. UploadFormDataItems items;
  1302. for (size_t i = 0; i < part_count; i++) {
  1303. items.push_back({name_of(i), content_of(i), "", ""});
  1304. }
  1305. Client cli(HOST, port);
  1306. auto res = cli.Post("/many", items);
  1307. ASSERT_TRUE(res);
  1308. ASSERT_EQ(part_count, received.size());
  1309. for (size_t i = 0; i < part_count; i++) {
  1310. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1311. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1312. }
  1313. }
  1314. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1315. string content_type = "multipart/form-data; boundary=something";
  1316. string boundary;
  1317. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1318. EXPECT_TRUE(ret);
  1319. EXPECT_EQ(boundary, "something");
  1320. }
  1321. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1322. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1323. string boundary;
  1324. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1325. EXPECT_TRUE(ret);
  1326. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1327. }
  1328. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1329. string content_type =
  1330. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1331. string boundary;
  1332. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1333. EXPECT_TRUE(ret);
  1334. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1335. }
  1336. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1337. string content_type =
  1338. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1339. string boundary;
  1340. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1341. EXPECT_TRUE(ret);
  1342. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1343. }
  1344. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1345. const string boundary(70, 'a');
  1346. string content_type = "multipart/form-data; boundary=" + boundary;
  1347. string parsed;
  1348. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1349. EXPECT_TRUE(ret);
  1350. EXPECT_EQ(parsed, boundary);
  1351. }
  1352. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1353. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1354. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1355. string parsed;
  1356. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1357. EXPECT_FALSE(ret);
  1358. }
  1359. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1360. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1361. // is 72 characters on the wire and still valid.
  1362. const string boundary(70, 'a');
  1363. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1364. string parsed;
  1365. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1366. EXPECT_EQ(parsed, boundary);
  1367. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1368. parsed.clear();
  1369. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1370. }
  1371. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1372. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1373. // The parameter parser must not treat that '=' as the key/value separator.
  1374. string content_type =
  1375. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1376. "charset=UTF-8";
  1377. string parsed;
  1378. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1379. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1380. }
  1381. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1382. // A ';' inside the quoted-string is part of the value, not a parameter
  1383. // separator, so it must not truncate the boundary.
  1384. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1385. string parsed;
  1386. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1387. EXPECT_EQ(parsed, "a;b");
  1388. }
  1389. TEST(ParseDispositionParamsTest, QuotedValues) {
  1390. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1391. // ';' and '=' are ordinary characters inside one.
  1392. struct {
  1393. const char *value;
  1394. std::vector<std::pair<const char *, const char *>> expected;
  1395. } cases[] = {
  1396. {"name=\"file1\"; filename=\"a.txt\"",
  1397. {{"name", "file1"}, {"filename", "a.txt"}}},
  1398. // Whitespace around '=' and ';' is still trimmed
  1399. {"name=\"file2\" ;filename = \"a.html\"",
  1400. {{"name", "file2"}, {"filename", "a.html"}}},
  1401. // '=' inside the value used to leave only the text after the last one
  1402. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1403. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1404. {"name=\"x=y\"", {{"name", "x=y"}}},
  1405. // ';' inside the value used to truncate the pair and leave a bogus one
  1406. {"name=\"file3\"; filename=\"a;b.txt\"",
  1407. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1408. // An unquoted value keeps working, and so does filename*
  1409. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1410. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1411. // A parameter with no key is dropped rather than turned into one whose
  1412. // key is the value
  1413. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1414. };
  1415. for (const auto &c : cases) {
  1416. Params params;
  1417. detail::parse_disposition_params(c.value, params);
  1418. for (const auto &kv : c.expected) {
  1419. auto it = params.find(kv.first);
  1420. ASSERT_NE(it, params.end())
  1421. << "value: " << c.value << ", key: " << kv.first;
  1422. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1423. }
  1424. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1425. }
  1426. }
  1427. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1428. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1429. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1430. Server svr;
  1431. std::string field_value, file_name, file_filename;
  1432. bool has_field = false, has_file = false;
  1433. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1434. has_field = req.form.has_field("x=y");
  1435. field_value = req.form.get_field("x=y");
  1436. has_file = req.form.has_file("file1");
  1437. const auto &file = req.form.get_file("file1");
  1438. file_name = file.name;
  1439. file_filename = file.filename;
  1440. res.set_content("ok", "text/plain");
  1441. });
  1442. auto port = svr.bind_to_any_port(HOST);
  1443. thread t = thread([&] { svr.listen_after_bind(); });
  1444. auto se = detail::scope_exit([&] {
  1445. svr.stop();
  1446. t.join();
  1447. ASSERT_FALSE(svr.is_running());
  1448. });
  1449. svr.wait_until_ready();
  1450. UploadFormDataItems items = {
  1451. {"x=y", "field-value", "", ""},
  1452. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1453. };
  1454. Client cli(HOST, port);
  1455. auto res = cli.Post("/quoted", items);
  1456. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1457. ASSERT_EQ(StatusCode::OK_200, res->status);
  1458. EXPECT_TRUE(has_field);
  1459. EXPECT_EQ("field-value", field_value);
  1460. EXPECT_TRUE(has_file);
  1461. EXPECT_EQ("file1", file_name);
  1462. EXPECT_EQ("a;b=report.pdf", file_filename);
  1463. }
  1464. TEST(GetHeaderValueTest, DefaultValue) {
  1465. Headers headers = {{"Dummy", "Dummy"}};
  1466. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1467. EXPECT_STREQ("text/plain", val);
  1468. }
  1469. TEST(GetHeaderValueTest, DefaultValueInt) {
  1470. Headers headers = {{"Dummy", "Dummy"}};
  1471. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1472. EXPECT_EQ(100ull, val);
  1473. }
  1474. TEST(GetHeaderValueTest, RegularValue) {
  1475. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1476. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1477. EXPECT_STREQ("text/html", val);
  1478. }
  1479. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1480. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1481. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1482. EXPECT_STREQ("text/html", val);
  1483. }
  1484. TEST(GetHeaderValueTest, SetContent) {
  1485. Response res;
  1486. res.set_content("html", "text/html");
  1487. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1488. res.set_content("text", "text/plain");
  1489. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1490. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1491. }
  1492. TEST(GetHeaderValueTest, RegularValueInt) {
  1493. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1494. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1495. EXPECT_EQ(100ull, val);
  1496. }
  1497. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1498. Headers headers = {{"Content-Length", "x"}};
  1499. auto is_invalid_value = false;
  1500. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1501. is_invalid_value);
  1502. EXPECT_EQ(0ull, val);
  1503. EXPECT_TRUE(is_invalid_value);
  1504. }
  1505. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1506. // An all-digit value that overflows size_t must be reported as invalid, not
  1507. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1508. // a large length to a small one on 32-bit builds, leaving the framing length
  1509. // wrong while is_invalid_value stayed false.
  1510. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1511. auto is_invalid_value = false;
  1512. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1513. is_invalid_value);
  1514. EXPECT_TRUE(is_invalid_value);
  1515. // A well-formed length is unaffected.
  1516. Headers ok = {{"Content-Length", "1234"}};
  1517. is_invalid_value = false;
  1518. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1519. is_invalid_value);
  1520. EXPECT_EQ(1234ull, val);
  1521. EXPECT_FALSE(is_invalid_value);
  1522. }
  1523. TEST(GetHeaderValueTest, Range) {
  1524. {
  1525. Headers headers = {make_range_header({{1, -1}})};
  1526. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1527. EXPECT_STREQ("bytes=1-", val);
  1528. }
  1529. {
  1530. Headers headers = {make_range_header({{-1, 1}})};
  1531. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1532. EXPECT_STREQ("bytes=-1", val);
  1533. }
  1534. {
  1535. Headers headers = {make_range_header({{1, 10}})};
  1536. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1537. EXPECT_STREQ("bytes=1-10", val);
  1538. }
  1539. {
  1540. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1541. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1542. EXPECT_STREQ("bytes=1-10, 100-", val);
  1543. }
  1544. {
  1545. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1546. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1547. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1548. }
  1549. {
  1550. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1551. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1552. EXPECT_STREQ("bytes=0-0, -1", val);
  1553. }
  1554. }
  1555. TEST(BearerTokenAuthTest, SchemeValidation) {
  1556. // A value shorter than "Bearer " must not throw from the fixed-length
  1557. // substr, and a non-Bearer scheme must not be reported as a token.
  1558. struct {
  1559. const char *value;
  1560. const char *expected;
  1561. } cases[] = {
  1562. {"x", ""},
  1563. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1564. {"Bearer abc123", "abc123"},
  1565. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1566. };
  1567. for (const auto &c : cases) {
  1568. Request req;
  1569. req.set_header("Authorization", c.value);
  1570. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1571. }
  1572. }
  1573. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1574. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1575. // to depend on the standard library (libstdc++ handed back duplicates in
  1576. // reverse insertion order, libc++ in insertion order).
  1577. Request req;
  1578. req.set_header("Accept-Encoding", "gzip");
  1579. req.set_header("Accept-Encoding", "deflate");
  1580. req.set_header("Accept-Encoding", "br");
  1581. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1582. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1583. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1584. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1585. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1586. }
  1587. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1588. Request req;
  1589. req.set_header("X-Test", "only");
  1590. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1591. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1592. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1593. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1594. }
  1595. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1596. Headers headers;
  1597. headers.emplace("Host", "example.com");
  1598. headers.emplace("Accept-Encoding", "gzip");
  1599. headers.emplace("User-Agent", "test");
  1600. headers.emplace("Accept-Encoding", "deflate");
  1601. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1602. "Accept-Encoding=deflate ",
  1603. entries_to_string(headers));
  1604. }
  1605. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1606. Headers headers = {{"Content-Type", "text/html"},
  1607. {"CONTENT-TYPE", "text/xml"}};
  1608. EXPECT_EQ(2U, headers.count("content-type"));
  1609. auto it = headers.find("content-type");
  1610. ASSERT_TRUE(it != headers.end());
  1611. EXPECT_EQ("text/html", it->second);
  1612. }
  1613. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1614. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1615. // drop only those fields and leave everything positioned between them.
  1616. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1617. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1618. auto rng = headers.equal_range("a");
  1619. headers.erase(rng.first, rng.second);
  1620. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1621. }
  1622. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1623. Headers headers = {
  1624. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1625. EXPECT_EQ(3U, headers.erase("A"));
  1626. EXPECT_EQ(0U, headers.count("A"));
  1627. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1628. }
  1629. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1630. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1631. headers.emplace_front("Host", "example.com");
  1632. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1633. entries_to_string(headers));
  1634. }
  1635. TEST(ParseHeaderValueTest, Range) {
  1636. {
  1637. Ranges ranges;
  1638. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1639. EXPECT_TRUE(ret);
  1640. EXPECT_EQ(1u, ranges.size());
  1641. EXPECT_EQ(1u, ranges[0].first);
  1642. EXPECT_EQ(-1, ranges[0].second);
  1643. }
  1644. {
  1645. Ranges ranges;
  1646. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1647. EXPECT_TRUE(ret);
  1648. EXPECT_EQ(1u, ranges.size());
  1649. EXPECT_EQ(-1, ranges[0].first);
  1650. EXPECT_EQ(1u, ranges[0].second);
  1651. }
  1652. {
  1653. Ranges ranges;
  1654. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1655. EXPECT_TRUE(ret);
  1656. EXPECT_EQ(1u, ranges.size());
  1657. EXPECT_EQ(1u, ranges[0].first);
  1658. EXPECT_EQ(10u, ranges[0].second);
  1659. }
  1660. {
  1661. Ranges ranges;
  1662. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1663. EXPECT_FALSE(ret);
  1664. }
  1665. {
  1666. Ranges ranges;
  1667. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1668. EXPECT_TRUE(ret);
  1669. EXPECT_EQ(2u, ranges.size());
  1670. EXPECT_EQ(1u, ranges[0].first);
  1671. EXPECT_EQ(10u, ranges[0].second);
  1672. EXPECT_EQ(100u, ranges[1].first);
  1673. EXPECT_EQ(-1, ranges[1].second);
  1674. }
  1675. {
  1676. Ranges ranges;
  1677. auto ret =
  1678. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1679. EXPECT_TRUE(ret);
  1680. EXPECT_EQ(3u, ranges.size());
  1681. EXPECT_EQ(1u, ranges[0].first);
  1682. EXPECT_EQ(10u, ranges[0].second);
  1683. EXPECT_EQ(100u, ranges[1].first);
  1684. EXPECT_EQ(200u, ranges[1].second);
  1685. EXPECT_EQ(300u, ranges[2].first);
  1686. EXPECT_EQ(400u, ranges[2].second);
  1687. }
  1688. {
  1689. Ranges ranges;
  1690. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1691. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1692. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1693. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1694. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1695. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1696. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1697. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1698. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1699. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1700. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1701. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1702. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1703. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  1704. EXPECT_FALSE(
  1705. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  1706. EXPECT_TRUE(ranges.empty());
  1707. }
  1708. {
  1709. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  1710. // remainder of the representation, so it stays accepted.
  1711. Ranges ranges;
  1712. auto ret =
  1713. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  1714. EXPECT_TRUE(ret);
  1715. ASSERT_EQ(1u, ranges.size());
  1716. EXPECT_EQ(0, ranges[0].first);
  1717. EXPECT_EQ(-1, ranges[0].second);
  1718. }
  1719. }
  1720. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  1721. Request req;
  1722. req.set_header("Accept-Encoding", "gzip");
  1723. Response res;
  1724. res.set_header("Content-Type", "text/plain");
  1725. auto ret = detail::encoding_type(req, res);
  1726. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1727. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1728. #else
  1729. EXPECT_TRUE(ret == detail::EncodingType::None);
  1730. #endif
  1731. }
  1732. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1733. Request req;
  1734. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  1735. Response res;
  1736. res.set_header("Content-Type", "text/plain");
  1737. auto ret = detail::encoding_type(req, res);
  1738. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1739. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1740. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1741. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1742. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1743. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1744. #else
  1745. EXPECT_TRUE(ret == detail::EncodingType::None);
  1746. #endif
  1747. }
  1748. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  1749. Request req;
  1750. req.set_header("Accept-Encoding",
  1751. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  1752. Response res;
  1753. res.set_header("Content-Type", "text/plain");
  1754. auto ret = detail::encoding_type(req, res);
  1755. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1756. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1757. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1758. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1759. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1760. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1761. #else
  1762. EXPECT_TRUE(ret == detail::EncodingType::None);
  1763. #endif
  1764. }
  1765. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  1766. // All supported encodings rejected with q=0 should return None
  1767. Request req;
  1768. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  1769. Response res;
  1770. res.set_header("Content-Type", "text/plain");
  1771. auto ret = detail::encoding_type(req, res);
  1772. EXPECT_TRUE(ret == detail::EncodingType::None);
  1773. }
  1774. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1775. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1776. Request req;
  1777. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1778. Response res;
  1779. res.set_header("Content-Type", "text/plain");
  1780. auto ret = detail::encoding_type(req, res);
  1781. EXPECT_TRUE(ret == detail::EncodingType::None);
  1782. }
  1783. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  1784. Request req;
  1785. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  1786. Response res;
  1787. res.set_header("Content-Type", "text/plain");
  1788. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  1789. }
  1790. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1791. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1792. Request req;
  1793. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1794. Response res;
  1795. res.set_header("Content-Type", "text/plain");
  1796. auto ret = detail::encoding_type(req, res);
  1797. EXPECT_TRUE(ret == detail::EncodingType::None);
  1798. }
  1799. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1800. // RFC 7231: Accept-Encoding values are case-insensitive
  1801. Request req;
  1802. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1803. Response res;
  1804. res.set_header("Content-Type", "text/plain");
  1805. auto ret = detail::encoding_type(req, res);
  1806. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1807. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1808. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1809. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1810. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1811. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1812. #else
  1813. EXPECT_TRUE(ret == detail::EncodingType::None);
  1814. #endif
  1815. }
  1816. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1817. // q value should determine priority, not hardcoded order
  1818. Request req;
  1819. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  1820. Response res;
  1821. res.set_header("Content-Type", "text/plain");
  1822. auto ret = detail::encoding_type(req, res);
  1823. // gzip has highest q=1.0, so it should be selected even though
  1824. // br and zstd are also supported
  1825. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1826. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1827. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1828. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1829. #elif CPPHTTPLIB_BROTLI_SUPPORT
  1830. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1831. #else
  1832. EXPECT_TRUE(ret == detail::EncodingType::None);
  1833. #endif
  1834. }
  1835. TEST(BufferStreamTest, read) {
  1836. detail::BufferStream strm1;
  1837. Stream &strm = strm1;
  1838. EXPECT_EQ(5, strm.write("hello"));
  1839. char buf[512];
  1840. EXPECT_EQ(2, strm.read(buf, 2));
  1841. EXPECT_EQ('h', buf[0]);
  1842. EXPECT_EQ('e', buf[1]);
  1843. EXPECT_EQ(2, strm.read(buf, 2));
  1844. EXPECT_EQ('l', buf[0]);
  1845. EXPECT_EQ('l', buf[1]);
  1846. EXPECT_EQ(1, strm.read(buf, 1));
  1847. EXPECT_EQ('o', buf[0]);
  1848. EXPECT_EQ(0, strm.read(buf, 1));
  1849. }
  1850. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1851. auto host = "www.httpwatch.com";
  1852. auto ip = hosted_at(host);
  1853. EXPECT_EQ("23.96.13.243", ip);
  1854. std::vector<std::string> addrs;
  1855. hosted_at(host, addrs);
  1856. EXPECT_EQ(1u, addrs.size());
  1857. }
  1858. #if 0 // It depends on each test environment...
  1859. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1860. auto host = "www.youtube.com";
  1861. std::vector<std::string> addrs;
  1862. hosted_at(host, addrs);
  1863. EXPECT_EQ(20u, addrs.size());
  1864. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1865. EXPECT_TRUE(it != addrs.end());
  1866. }
  1867. #endif
  1868. class ChunkedEncodingTest : public ::testing::Test {
  1869. protected:
  1870. ChunkedEncodingTest()
  1871. : cli_(HOST, PORT)
  1872. #ifdef CPPHTTPLIB_SSL_ENABLED
  1873. ,
  1874. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1875. #endif
  1876. {
  1877. cli_.set_connection_timeout(2);
  1878. #ifdef CPPHTTPLIB_SSL_ENABLED
  1879. cli_.enable_server_certificate_verification(false);
  1880. #endif
  1881. }
  1882. virtual void SetUp() {
  1883. read_file("./image.jpg", image_data_);
  1884. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1885. res.set_content("Hello World!", "text/plain");
  1886. });
  1887. svr_.Get(
  1888. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1889. res.set_chunked_content_provider(
  1890. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1891. size_t remaining = image_data_.size() - offset;
  1892. if (remaining == 0) {
  1893. sink.done();
  1894. } else {
  1895. constexpr size_t CHUNK_SIZE = 1024;
  1896. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1897. sink.write(&image_data_[offset], send_size);
  1898. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1899. }
  1900. return true;
  1901. });
  1902. });
  1903. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1904. svr_.wait_until_ready();
  1905. }
  1906. virtual void TearDown() {
  1907. svr_.stop();
  1908. if (!request_threads_.empty()) {
  1909. std::this_thread::sleep_for(std::chrono::seconds(1));
  1910. for (auto &t : request_threads_) {
  1911. t.join();
  1912. }
  1913. }
  1914. t_.join();
  1915. }
  1916. #ifdef CPPHTTPLIB_SSL_ENABLED
  1917. SSLClient cli_;
  1918. SSLServer svr_;
  1919. #else
  1920. Client cli_;
  1921. Server svr_;
  1922. #endif
  1923. thread t_;
  1924. std::vector<thread> request_threads_;
  1925. std::string image_data_;
  1926. };
  1927. TEST_F(ChunkedEncodingTest, NormalGet) {
  1928. auto res = cli_.Get("/chunked");
  1929. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1930. std::string out;
  1931. read_file("./image.jpg", out);
  1932. EXPECT_EQ(StatusCode::OK_200, res->status);
  1933. EXPECT_EQ(out, res->body);
  1934. }
  1935. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1936. std::string body;
  1937. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1938. body.append(data, data_length);
  1939. return true;
  1940. });
  1941. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1942. std::string out;
  1943. read_file("./image.jpg", out);
  1944. EXPECT_EQ(StatusCode::OK_200, res->status);
  1945. EXPECT_EQ(out, body);
  1946. }
  1947. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1948. std::string body;
  1949. auto res = cli_.Get(
  1950. "/chunked",
  1951. [&](const Response &response) {
  1952. EXPECT_EQ(StatusCode::OK_200, response.status);
  1953. return true;
  1954. },
  1955. [&](const char *data, size_t data_length) {
  1956. body.append(data, data_length);
  1957. return true;
  1958. });
  1959. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1960. std::string out;
  1961. read_file("./image.jpg", out);
  1962. EXPECT_EQ(StatusCode::OK_200, res->status);
  1963. EXPECT_EQ(out, body);
  1964. }
  1965. TEST(RangeTest, FromHTTPBin_Online) {
  1966. auto host = "httpbingo.org";
  1967. auto path = std::string{"/range/32"};
  1968. #ifdef CPPHTTPLIB_SSL_ENABLED
  1969. auto port = 443;
  1970. SSLClient cli(host, port);
  1971. #else
  1972. auto port = 80;
  1973. Client cli(host, port);
  1974. #endif
  1975. cli.set_connection_timeout(5);
  1976. {
  1977. auto res = cli.Get(path);
  1978. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1979. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1980. EXPECT_EQ(StatusCode::OK_200, res->status);
  1981. }
  1982. {
  1983. Headers headers = {make_range_header({{1, -1}})};
  1984. auto res = cli.Get(path, headers);
  1985. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1986. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1987. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1988. }
  1989. {
  1990. Headers headers = {make_range_header({{1, 10}})};
  1991. auto res = cli.Get(path, headers);
  1992. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1993. EXPECT_EQ("bcdefghijk", res->body);
  1994. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1995. }
  1996. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  1997. // entire resource, while the original httpbin returned 200. Both are
  1998. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  1999. {
  2000. Headers headers = {make_range_header({{0, 31}})};
  2001. auto res = cli.Get(path, headers);
  2002. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2003. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2004. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2005. res->status == StatusCode::PartialContent_206);
  2006. }
  2007. {
  2008. Headers headers = {make_range_header({{0, -1}})};
  2009. auto res = cli.Get(path, headers);
  2010. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2011. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2012. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2013. res->status == StatusCode::PartialContent_206);
  2014. }
  2015. // go-httpbin returns 206 with clamped range for over-range requests,
  2016. // while the original httpbin returned 416. Both behaviors are observed
  2017. // in real servers, so we only verify the request succeeds.
  2018. {
  2019. Headers headers = {make_range_header({{0, 32}})};
  2020. auto res = cli.Get(path, headers);
  2021. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2022. }
  2023. }
  2024. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2025. auto host = "unresolvableaddress.local";
  2026. auto path = std::string{"/"};
  2027. #ifdef CPPHTTPLIB_SSL_ENABLED
  2028. auto port = 443;
  2029. SSLClient cli(host, port);
  2030. #else
  2031. auto port = 80;
  2032. Client cli(host, port);
  2033. #endif
  2034. cli.set_connection_timeout(1);
  2035. {
  2036. auto res = cli.Get(path);
  2037. ASSERT_FALSE(res);
  2038. }
  2039. std::this_thread::sleep_for(std::chrono::seconds(8));
  2040. }
  2041. #if defined(__linux__) && defined(__GLIBC__) && \
  2042. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2043. // Forward declaration: in split builds split.py strips `inline` and moves the
  2044. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2045. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2046. // against the symbol in both header-only and split builds.
  2047. namespace httplib {
  2048. namespace detail {
  2049. int getaddrinfo_with_timeout(const char *node, const char *service,
  2050. const struct addrinfo *hints,
  2051. struct addrinfo **res, time_t timeout_sec);
  2052. } // namespace detail
  2053. } // namespace httplib
  2054. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2055. //
  2056. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2057. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2058. // gai_suspend() call hits the connection timeout the function calls
  2059. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2060. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2061. // still alive and still references the now-destroyed stack frame.
  2062. //
  2063. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2064. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2065. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2066. // and runs them in a container.
  2067. namespace {
  2068. bool should_run_issue_2431_tests() {
  2069. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2070. return v && *v && std::string(v) != "0";
  2071. }
  2072. std::string unique_unresolvable_host(int n) {
  2073. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2074. // glibc still asks the configured nameserver — which is exactly the path
  2075. // we want to exercise. A unique label per call avoids the resolver cache.
  2076. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2077. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2078. std::to_string(n) + ".invalid";
  2079. }
  2080. } // namespace
  2081. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2082. if (!should_run_issue_2431_tests()) {
  2083. GTEST_SKIP()
  2084. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2085. }
  2086. for (int i = 0; i < 8; ++i) {
  2087. struct addrinfo hints;
  2088. memset(&hints, 0, sizeof(hints));
  2089. hints.ai_family = AF_UNSPEC;
  2090. hints.ai_socktype = SOCK_STREAM;
  2091. auto host = unique_unresolvable_host(i);
  2092. struct addrinfo *result = nullptr;
  2093. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2094. &result, /*timeout_sec=*/1);
  2095. if (rc == 0 && result) { freeaddrinfo(result); }
  2096. }
  2097. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2098. // stack region they still believe holds their gaicb.
  2099. std::this_thread::sleep_for(std::chrono::seconds(3));
  2100. }
  2101. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2102. if (!should_run_issue_2431_tests()) {
  2103. GTEST_SKIP()
  2104. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2105. }
  2106. std::atomic<bool> stop{false};
  2107. std::vector<std::thread> threads;
  2108. for (int t = 0; t < 8; ++t) {
  2109. threads.emplace_back([t, &stop] {
  2110. int i = 0;
  2111. while (!stop.load(std::memory_order_relaxed)) {
  2112. struct addrinfo hints;
  2113. memset(&hints, 0, sizeof(hints));
  2114. hints.ai_family = AF_UNSPEC;
  2115. hints.ai_socktype = SOCK_STREAM;
  2116. auto host = unique_unresolvable_host(t * 100000 + i++);
  2117. struct addrinfo *result = nullptr;
  2118. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2119. &result, /*timeout_sec=*/1);
  2120. if (rc == 0 && result) { freeaddrinfo(result); }
  2121. }
  2122. });
  2123. }
  2124. std::this_thread::sleep_for(std::chrono::seconds(8));
  2125. stop.store(true, std::memory_order_relaxed);
  2126. for (auto &th : threads) {
  2127. th.join();
  2128. }
  2129. std::this_thread::sleep_for(std::chrono::seconds(3));
  2130. }
  2131. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2132. if (!should_run_issue_2431_tests()) {
  2133. GTEST_SKIP()
  2134. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2135. }
  2136. std::atomic<bool> stop{false};
  2137. std::vector<std::thread> threads;
  2138. for (int t = 0; t < 8; ++t) {
  2139. threads.emplace_back([t, &stop] {
  2140. int i = 0;
  2141. while (!stop.load(std::memory_order_relaxed)) {
  2142. auto host = unique_unresolvable_host(t * 100000 + i++);
  2143. Client cli(host, 80);
  2144. cli.set_connection_timeout(1, 0);
  2145. cli.set_read_timeout(1, 0);
  2146. cli.set_write_timeout(1, 0);
  2147. (void)cli.Get("/");
  2148. }
  2149. });
  2150. }
  2151. std::this_thread::sleep_for(std::chrono::seconds(8));
  2152. stop.store(true, std::memory_order_relaxed);
  2153. for (auto &th : threads) {
  2154. th.join();
  2155. }
  2156. std::this_thread::sleep_for(std::chrono::seconds(3));
  2157. }
  2158. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2159. TEST(ConnectionErrorTest, InvalidHost) {
  2160. auto host = "-abcde.com";
  2161. #ifdef CPPHTTPLIB_SSL_ENABLED
  2162. auto port = 443;
  2163. SSLClient cli(host, port);
  2164. #else
  2165. auto port = 80;
  2166. Client cli(host, port);
  2167. #endif
  2168. cli.set_connection_timeout(std::chrono::seconds(2));
  2169. auto res = cli.Get("/");
  2170. ASSERT_TRUE(!res);
  2171. EXPECT_EQ(Error::Connection, res.error());
  2172. }
  2173. TEST(ConnectionErrorTest, InvalidHost2) {
  2174. auto host = "httpcan.org/";
  2175. #ifdef CPPHTTPLIB_SSL_ENABLED
  2176. SSLClient cli(host);
  2177. #else
  2178. Client cli(host);
  2179. #endif
  2180. cli.set_connection_timeout(std::chrono::seconds(2));
  2181. auto res = cli.Get("/");
  2182. ASSERT_TRUE(!res);
  2183. EXPECT_EQ(Error::Connection, res.error());
  2184. }
  2185. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2186. auto host = "httpcan.org/";
  2187. #ifdef CPPHTTPLIB_SSL_ENABLED
  2188. SSLClient cli(host);
  2189. #else
  2190. Client cli(host);
  2191. #endif
  2192. cli.set_connection_timeout(std::chrono::seconds(2));
  2193. auto res = cli.Get("/");
  2194. ASSERT_TRUE(!res);
  2195. stringstream s;
  2196. s << "error code: " << res.error();
  2197. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2198. }
  2199. TEST(ConnectionErrorTest, InvalidPort) {
  2200. auto host = "localhost";
  2201. auto port = 44380;
  2202. #ifdef CPPHTTPLIB_SSL_ENABLED
  2203. SSLClient cli(host, port);
  2204. #else
  2205. Client cli(host, port);
  2206. #endif
  2207. cli.set_connection_timeout(std::chrono::seconds(2));
  2208. auto res = cli.Get("/");
  2209. ASSERT_TRUE(!res);
  2210. EXPECT_TRUE(Error::Connection == res.error() ||
  2211. Error::ConnectionTimeout == res.error());
  2212. }
  2213. TEST(ConnectionErrorTest, Timeout_Online) {
  2214. auto host = "google.com";
  2215. #ifdef CPPHTTPLIB_SSL_ENABLED
  2216. auto port = 44380;
  2217. SSLClient cli(host, port);
  2218. #else
  2219. auto port = 8080;
  2220. Client cli(host, port);
  2221. #endif
  2222. cli.set_connection_timeout(std::chrono::seconds(2));
  2223. // only probe one address type so that the error reason
  2224. // correlates to the timed-out IPv4, not the unsupported
  2225. // IPv6 connection attempt
  2226. cli.set_address_family(AF_INET);
  2227. auto res = cli.Get("/");
  2228. ASSERT_TRUE(!res);
  2229. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2230. }
  2231. TEST(CancelTest, NoCancel_Online) {
  2232. auto host = "httpbingo.org";
  2233. auto path = std::string{"/range/32"};
  2234. #ifdef CPPHTTPLIB_SSL_ENABLED
  2235. auto port = 443;
  2236. SSLClient cli(host, port);
  2237. #else
  2238. auto port = 80;
  2239. Client cli(host, port);
  2240. #endif
  2241. cli.set_connection_timeout(std::chrono::seconds(5));
  2242. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2244. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2245. EXPECT_EQ(StatusCode::OK_200, res->status);
  2246. }
  2247. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2248. // Use /bytes with a large payload so that the DownloadProgress callback
  2249. // (which only fires for Content-Length responses) is invoked before the
  2250. // entire body is received, giving cancellation a chance to fire.
  2251. auto host = "httpbingo.org";
  2252. auto path = std::string{"/bytes/524288"};
  2253. #ifdef CPPHTTPLIB_SSL_ENABLED
  2254. auto port = 443;
  2255. SSLClient cli(host, port);
  2256. #else
  2257. auto port = 80;
  2258. Client cli(host, port);
  2259. #endif
  2260. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2261. cli.set_connection_timeout(std::chrono::seconds(5));
  2262. ASSERT_TRUE(!res);
  2263. EXPECT_EQ(Error::Canceled, res.error());
  2264. }
  2265. TEST(CancelTest, WithCancelLargePayload_Online) {
  2266. auto host = "httpbingo.org";
  2267. auto path = std::string{"/bytes/524288"};
  2268. #ifdef CPPHTTPLIB_SSL_ENABLED
  2269. auto port = 443;
  2270. SSLClient cli(host, port);
  2271. #else
  2272. auto port = 80;
  2273. Client cli(host, port);
  2274. #endif
  2275. cli.set_connection_timeout(std::chrono::seconds(5));
  2276. uint32_t count = 0;
  2277. auto res =
  2278. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2279. ASSERT_TRUE(!res);
  2280. EXPECT_EQ(Error::Canceled, res.error());
  2281. }
  2282. TEST(CancelTest, NoCancelPost) {
  2283. Server svr;
  2284. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2285. res.set_content("Hello World!", "text/plain");
  2286. });
  2287. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2288. auto se = detail::scope_exit([&] {
  2289. svr.stop();
  2290. thread.join();
  2291. ASSERT_FALSE(svr.is_running());
  2292. });
  2293. svr.wait_until_ready();
  2294. Client cli(HOST, PORT);
  2295. cli.set_connection_timeout(std::chrono::seconds(5));
  2296. auto res =
  2297. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2298. "application/json", [](uint64_t, uint64_t) { return true; });
  2299. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2300. EXPECT_EQ("Hello World!", res->body);
  2301. EXPECT_EQ(StatusCode::OK_200, res->status);
  2302. }
  2303. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2304. Server svr;
  2305. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2306. res.set_content("Hello World!", "text/plain");
  2307. });
  2308. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2309. auto se = detail::scope_exit([&] {
  2310. svr.stop();
  2311. thread.join();
  2312. ASSERT_FALSE(svr.is_running());
  2313. });
  2314. svr.wait_until_ready();
  2315. Client cli(HOST, PORT);
  2316. cli.set_connection_timeout(std::chrono::seconds(5));
  2317. auto res =
  2318. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2319. "application/json", [](uint64_t, uint64_t) { return false; });
  2320. ASSERT_TRUE(!res);
  2321. EXPECT_EQ(Error::Canceled, res.error());
  2322. }
  2323. TEST(CancelTest, WithCancelLargePayloadPost) {
  2324. Server svr;
  2325. svr.set_payload_max_length(200 * 1024 * 1024);
  2326. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2327. res.set_content(LARGE_DATA, "text/plain");
  2328. });
  2329. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2330. auto se = detail::scope_exit([&] {
  2331. svr.stop();
  2332. thread.join();
  2333. ASSERT_FALSE(svr.is_running());
  2334. });
  2335. svr.wait_until_ready();
  2336. Client cli(HOST, PORT);
  2337. cli.set_payload_max_length(200 * 1024 * 1024);
  2338. cli.set_connection_timeout(std::chrono::seconds(5));
  2339. auto res =
  2340. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2341. "application/json", [](uint64_t, uint64_t) { return false; });
  2342. ASSERT_TRUE(!res);
  2343. EXPECT_EQ(Error::Canceled, res.error());
  2344. }
  2345. TEST(CancelTest, NoCancelPut) {
  2346. Server svr;
  2347. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2348. res.set_content("Hello World!", "text/plain");
  2349. });
  2350. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2351. auto se = detail::scope_exit([&] {
  2352. svr.stop();
  2353. thread.join();
  2354. ASSERT_FALSE(svr.is_running());
  2355. });
  2356. svr.wait_until_ready();
  2357. Client cli(HOST, PORT);
  2358. cli.set_connection_timeout(std::chrono::seconds(5));
  2359. auto res =
  2360. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2361. "application/json", [](uint64_t, uint64_t) { return true; });
  2362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2363. EXPECT_EQ("Hello World!", res->body);
  2364. EXPECT_EQ(StatusCode::OK_200, res->status);
  2365. }
  2366. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2367. Server svr;
  2368. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2369. res.set_content("Hello World!", "text/plain");
  2370. });
  2371. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2372. auto se = detail::scope_exit([&] {
  2373. svr.stop();
  2374. thread.join();
  2375. ASSERT_FALSE(svr.is_running());
  2376. });
  2377. svr.wait_until_ready();
  2378. Client cli(HOST, PORT);
  2379. cli.set_connection_timeout(std::chrono::seconds(5));
  2380. auto res =
  2381. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2382. "application/json", [](uint64_t, uint64_t) { return false; });
  2383. ASSERT_TRUE(!res);
  2384. EXPECT_EQ(Error::Canceled, res.error());
  2385. }
  2386. TEST(CancelTest, WithCancelLargePayloadPut) {
  2387. Server svr;
  2388. svr.set_payload_max_length(200 * 1024 * 1024);
  2389. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2390. res.set_content(LARGE_DATA, "text/plain");
  2391. });
  2392. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2393. auto se = detail::scope_exit([&] {
  2394. svr.stop();
  2395. thread.join();
  2396. ASSERT_FALSE(svr.is_running());
  2397. });
  2398. svr.wait_until_ready();
  2399. Client cli(HOST, PORT);
  2400. cli.set_payload_max_length(200 * 1024 * 1024);
  2401. cli.set_connection_timeout(std::chrono::seconds(5));
  2402. auto res =
  2403. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2404. "application/json", [](uint64_t, uint64_t) { return false; });
  2405. ASSERT_TRUE(!res);
  2406. EXPECT_EQ(Error::Canceled, res.error());
  2407. }
  2408. TEST(CancelTest, NoCancelPatch) {
  2409. Server svr;
  2410. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2411. res.set_content("Hello World!", "text/plain");
  2412. });
  2413. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2414. auto se = detail::scope_exit([&] {
  2415. svr.stop();
  2416. thread.join();
  2417. ASSERT_FALSE(svr.is_running());
  2418. });
  2419. svr.wait_until_ready();
  2420. Client cli(HOST, PORT);
  2421. cli.set_connection_timeout(std::chrono::seconds(5));
  2422. auto res =
  2423. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2424. "application/json", [](uint64_t, uint64_t) { return true; });
  2425. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2426. EXPECT_EQ("Hello World!", res->body);
  2427. EXPECT_EQ(StatusCode::OK_200, res->status);
  2428. }
  2429. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2430. Server svr;
  2431. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2432. res.set_content("Hello World!", "text/plain");
  2433. });
  2434. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2435. auto se = detail::scope_exit([&] {
  2436. svr.stop();
  2437. thread.join();
  2438. ASSERT_FALSE(svr.is_running());
  2439. });
  2440. svr.wait_until_ready();
  2441. Client cli(HOST, PORT);
  2442. cli.set_connection_timeout(std::chrono::seconds(5));
  2443. auto res =
  2444. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2445. "application/json", [](uint64_t, uint64_t) { return false; });
  2446. ASSERT_TRUE(!res);
  2447. EXPECT_EQ(Error::Canceled, res.error());
  2448. }
  2449. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2450. Server svr;
  2451. svr.set_payload_max_length(200 * 1024 * 1024);
  2452. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2453. res.set_content(LARGE_DATA, "text/plain");
  2454. });
  2455. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2456. auto se = detail::scope_exit([&] {
  2457. svr.stop();
  2458. thread.join();
  2459. ASSERT_FALSE(svr.is_running());
  2460. });
  2461. svr.wait_until_ready();
  2462. Client cli(HOST, PORT);
  2463. cli.set_payload_max_length(200 * 1024 * 1024);
  2464. cli.set_connection_timeout(std::chrono::seconds(5));
  2465. auto res =
  2466. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2467. "application/json", [](uint64_t, uint64_t) { return false; });
  2468. ASSERT_TRUE(!res);
  2469. EXPECT_EQ(Error::Canceled, res.error());
  2470. }
  2471. TEST(CancelTest, NoCancelDelete) {
  2472. Server svr;
  2473. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2474. res.set_content("Hello World!", "text/plain");
  2475. });
  2476. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2477. auto se = detail::scope_exit([&] {
  2478. svr.stop();
  2479. thread.join();
  2480. ASSERT_FALSE(svr.is_running());
  2481. });
  2482. svr.wait_until_ready();
  2483. Client cli(HOST, PORT);
  2484. cli.set_connection_timeout(std::chrono::seconds(5));
  2485. auto res =
  2486. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2487. "application/json", [](uint64_t, uint64_t) { return true; });
  2488. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2489. EXPECT_EQ("Hello World!", res->body);
  2490. EXPECT_EQ(StatusCode::OK_200, res->status);
  2491. }
  2492. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2493. Server svr;
  2494. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2495. res.set_content("Hello World!", "text/plain");
  2496. });
  2497. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2498. auto se = detail::scope_exit([&] {
  2499. svr.stop();
  2500. thread.join();
  2501. ASSERT_FALSE(svr.is_running());
  2502. });
  2503. svr.wait_until_ready();
  2504. Client cli(HOST, PORT);
  2505. cli.set_connection_timeout(std::chrono::seconds(5));
  2506. auto res =
  2507. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2508. "application/json", [](uint64_t, uint64_t) { return false; });
  2509. ASSERT_TRUE(!res);
  2510. EXPECT_EQ(Error::Canceled, res.error());
  2511. }
  2512. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2513. Server svr;
  2514. svr.set_payload_max_length(200 * 1024 * 1024);
  2515. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2516. res.set_content(LARGE_DATA, "text/plain");
  2517. });
  2518. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2519. auto se = detail::scope_exit([&] {
  2520. svr.stop();
  2521. thread.join();
  2522. ASSERT_FALSE(svr.is_running());
  2523. });
  2524. svr.wait_until_ready();
  2525. Client cli(HOST, PORT);
  2526. cli.set_payload_max_length(200 * 1024 * 1024);
  2527. cli.set_connection_timeout(std::chrono::seconds(5));
  2528. auto res =
  2529. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2530. "application/json", [](uint64_t, uint64_t) { return false; });
  2531. ASSERT_TRUE(!res);
  2532. EXPECT_EQ(Error::Canceled, res.error());
  2533. }
  2534. static std::string remove_whitespace(const std::string &input) {
  2535. std::string output;
  2536. output.reserve(input.size());
  2537. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2538. [](unsigned char c) { return !std::isspace(c); });
  2539. return output;
  2540. }
  2541. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2542. auto host = "httpbingo.org";
  2543. auto path = std::string{"/basic-auth/hello/world"};
  2544. #ifdef CPPHTTPLIB_SSL_ENABLED
  2545. auto port = 443;
  2546. SSLClient cli(host, port);
  2547. #else
  2548. auto port = 80;
  2549. Client cli(host, port);
  2550. #endif
  2551. {
  2552. auto res = cli.Get(path);
  2553. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2554. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2555. }
  2556. {
  2557. auto res = cli.Get(
  2558. path, Headers{make_basic_authentication_header("hello", "world")});
  2559. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2560. auto body = remove_whitespace(res->body);
  2561. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2562. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2563. EXPECT_EQ(StatusCode::OK_200, res->status);
  2564. }
  2565. {
  2566. cli.set_basic_auth("hello", "world");
  2567. auto res = cli.Get(path);
  2568. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2569. auto body = remove_whitespace(res->body);
  2570. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2571. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2572. EXPECT_EQ(StatusCode::OK_200, res->status);
  2573. }
  2574. {
  2575. cli.set_basic_auth("hello", "bad");
  2576. auto res = cli.Get(path);
  2577. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2578. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2579. }
  2580. {
  2581. cli.set_basic_auth("bad", "world");
  2582. auto res = cli.Get(path);
  2583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2584. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2585. }
  2586. }
  2587. #ifdef CPPHTTPLIB_SSL_ENABLED
  2588. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2589. auto host = "httpbingo.org";
  2590. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2591. auto paths = std::vector<std::string>{
  2592. "/digest-auth/auth/hello/world/MD5",
  2593. "/digest-auth/auth/hello/world/SHA-256",
  2594. };
  2595. auto port = 443;
  2596. SSLClient cli(host, port);
  2597. {
  2598. auto res = cli.Get(unauth_path);
  2599. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2600. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2601. }
  2602. {
  2603. cli.set_digest_auth("hello", "world");
  2604. for (const auto &path : paths) {
  2605. auto res = cli.Get(path.c_str());
  2606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2607. auto body = remove_whitespace(res->body);
  2608. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2609. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2610. EXPECT_EQ(StatusCode::OK_200, res->status);
  2611. }
  2612. cli.set_digest_auth("hello", "bad");
  2613. for (const auto &path : paths) {
  2614. auto res = cli.Get(path.c_str());
  2615. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2616. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2617. }
  2618. }
  2619. }
  2620. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2621. // comma-separated list of challenges, and each challenge may itself carry a
  2622. // comma-separated auth-param list, so a server can legally offer Basic
  2623. // before Digest, either as two field lines or packed into one. Runs one 401
  2624. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2625. // value() joins them in receipt order) and checks that the retry carries a
  2626. // well-formed Digest Authorization header naming expected_realm.
  2627. static void
  2628. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2629. const std::string &expected_realm) {
  2630. std::atomic<int> hits{0};
  2631. Server svr;
  2632. svr.Get("/x", [&](const Request &req, Response &res) {
  2633. if (++hits == 1) {
  2634. res.status = StatusCode::Unauthorized_401;
  2635. for (const auto &challenge : challenges) {
  2636. res.set_header("WWW-Authenticate", challenge);
  2637. }
  2638. } else {
  2639. auto authorization = req.get_header_value("Authorization");
  2640. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2641. EXPECT_NE(std::string::npos,
  2642. authorization.find("realm=\"" + expected_realm + "\""));
  2643. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2644. res.set_content("ok", "text/plain");
  2645. }
  2646. });
  2647. auto port = svr.bind_to_any_port(HOST);
  2648. std::thread t([&]() { svr.listen_after_bind(); });
  2649. auto se = detail::scope_exit([&] {
  2650. svr.stop();
  2651. t.join();
  2652. });
  2653. svr.wait_until_ready();
  2654. Client cli(HOST, port);
  2655. cli.set_digest_auth("hello", "world");
  2656. auto res = cli.Get("/x");
  2657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2658. EXPECT_EQ(2, hits.load());
  2659. }
  2660. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2661. static const char *kDigestChallenge =
  2662. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2663. "algorithm=MD5";
  2664. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2665. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2666. "testrealm");
  2667. }
  2668. // Same challenge list with the schemes in the opposite order, to make sure
  2669. // the fix above didn't just special-case "Basic first".
  2670. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2671. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2672. "testrealm");
  2673. }
  2674. // A comma inside a quoted auth-param value must not be mistaken for the
  2675. // separator between two challenges (or two auth-params).
  2676. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2677. run_digest_challenge_list_test(
  2678. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  2679. "algorithm=MD5"},
  2680. "test,realm");
  2681. }
  2682. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  2683. // make_digest_authentication_header() dereferences both unconditionally, so
  2684. // a server sending a challenge missing either one must not be treated as
  2685. // usable -- doing so used to crash the client with std::out_of_range.
  2686. static void run_digest_challenge_missing_field_test(const char *challenge) {
  2687. Server svr;
  2688. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  2689. res.status = StatusCode::Unauthorized_401;
  2690. res.set_header("WWW-Authenticate", challenge);
  2691. });
  2692. auto port = svr.bind_to_any_port(HOST);
  2693. std::thread t([&]() { svr.listen_after_bind(); });
  2694. auto se = detail::scope_exit([&] {
  2695. svr.stop();
  2696. t.join();
  2697. });
  2698. svr.wait_until_ready();
  2699. Client cli(HOST, port);
  2700. cli.set_digest_auth("hello", "world");
  2701. auto res = cli.Get("/x");
  2702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2703. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2704. }
  2705. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  2706. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  2707. }
  2708. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  2709. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  2710. }
  2711. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  2712. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  2713. }
  2714. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  2715. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  2716. // when storing the values, so the header builder has to re-escape them (and
  2717. // keep algorithm a bare token); otherwise the value breaks out of its
  2718. // quoted-string and injects extra auth-params into the client's Authorization.
  2719. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  2720. std::atomic<int> hits{0};
  2721. std::string authorization;
  2722. Server svr;
  2723. svr.Get("/x", [&](const Request &req, Response &res) {
  2724. if (++hits == 1) {
  2725. res.status = StatusCode::Unauthorized_401;
  2726. // On the wire the quotes embedded in the values are backslash-escaped.
  2727. res.set_header("WWW-Authenticate",
  2728. "Digest realm=\"testrealm\", "
  2729. "nonce=\"n\\\"; injected=\\\"x\", "
  2730. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  2731. } else {
  2732. authorization = req.get_header_value("Authorization");
  2733. res.set_content("ok", "text/plain");
  2734. }
  2735. });
  2736. auto port = svr.bind_to_any_port(HOST);
  2737. std::thread t([&]() { svr.listen_after_bind(); });
  2738. auto se = detail::scope_exit([&] {
  2739. svr.stop();
  2740. t.join();
  2741. });
  2742. svr.wait_until_ready();
  2743. Client cli(HOST, port);
  2744. cli.set_digest_auth("hello", "world");
  2745. auto res = cli.Get("/x");
  2746. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2747. EXPECT_EQ(2, hits.load());
  2748. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2749. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  2750. // inside its quoted-string rather than starting an "injected" auth-param.
  2751. EXPECT_NE(std::string::npos,
  2752. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  2753. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  2754. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  2755. }
  2756. #endif
  2757. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  2758. auto host = "google.com";
  2759. auto another_host = "example.com";
  2760. auto wrong_ip = "0.0.0.0";
  2761. #ifdef CPPHTTPLIB_SSL_ENABLED
  2762. SSLClient cli(host);
  2763. #else
  2764. Client cli(host);
  2765. #endif
  2766. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  2767. auto res = cli.Get("/");
  2768. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2769. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  2770. }
  2771. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  2772. auto host = "google.com";
  2773. auto wrong_ip = "0.0.0.0";
  2774. #ifdef CPPHTTPLIB_SSL_ENABLED
  2775. SSLClient cli(host);
  2776. #else
  2777. Client cli(host);
  2778. #endif
  2779. cli.set_hostname_addr_map({{host, wrong_ip}});
  2780. auto res = cli.Get("/");
  2781. ASSERT_TRUE(!res);
  2782. EXPECT_EQ(Error::Connection, res.error());
  2783. }
  2784. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  2785. // A mapped value that is not an IP literal must be resolved. "localhost"
  2786. // resolves from the hosts file, so this test needs no external DNS.
  2787. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  2788. auto host = "target.invalid";
  2789. Server svr;
  2790. std::string received_host;
  2791. svr.Get("/hi", [&](const Request &req, Response &res) {
  2792. received_host = req.get_header_value("Host");
  2793. res.set_content("Hello World!", "text/plain");
  2794. });
  2795. auto port = svr.bind_to_any_port(HOST);
  2796. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2797. auto se = detail::scope_exit([&] {
  2798. svr.stop();
  2799. thread.join();
  2800. ASSERT_FALSE(svr.is_running());
  2801. });
  2802. svr.wait_until_ready();
  2803. Client cli(host, port);
  2804. cli.set_hostname_addr_map({{host, HOST}});
  2805. auto res = cli.Get("/hi");
  2806. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2807. EXPECT_EQ(StatusCode::OK_200, res->status);
  2808. // The mapping only redirects the connection; the identity stays host_.
  2809. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  2810. }
  2811. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  2812. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  2813. auto host = "target.invalid";
  2814. Server svr;
  2815. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2816. res.set_content("Hello World!", "text/plain");
  2817. });
  2818. auto port = svr.bind_to_any_port("127.0.0.1");
  2819. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2820. auto se = detail::scope_exit([&] {
  2821. svr.stop();
  2822. thread.join();
  2823. ASSERT_FALSE(svr.is_running());
  2824. });
  2825. svr.wait_until_ready();
  2826. Client cli(host, port);
  2827. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  2828. auto res = cli.Get("/hi");
  2829. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2830. EXPECT_EQ(StatusCode::OK_200, res->status);
  2831. }
  2832. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  2833. // An empty mapped value must leave host_ as the connection target. Without
  2834. // that guard the empty value would become the host argument, getaddrinfo
  2835. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  2836. // loopback - silently connecting somewhere the caller never asked for.
  2837. // The server listens on loopback, so such a fallback would succeed and is
  2838. // therefore observable as a failure of this test.
  2839. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  2840. Server svr;
  2841. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2842. res.set_content("Hello World!", "text/plain");
  2843. });
  2844. auto port = svr.bind_to_any_port(HOST);
  2845. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2846. auto se = detail::scope_exit([&] {
  2847. svr.stop();
  2848. thread.join();
  2849. ASSERT_FALSE(svr.is_running());
  2850. });
  2851. svr.wait_until_ready();
  2852. Client cli(blackhole, port);
  2853. cli.set_hostname_addr_map({{blackhole, ""}});
  2854. cli.set_connection_timeout(1);
  2855. auto res = cli.Get("/hi");
  2856. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  2857. }
  2858. TEST(AbsoluteRedirectTest, Redirect_Online) {
  2859. auto host = "httpbingo.org";
  2860. auto path = std::string{"/absolute-redirect/3"};
  2861. #ifdef CPPHTTPLIB_SSL_ENABLED
  2862. SSLClient cli(host);
  2863. #else
  2864. Client cli(host);
  2865. #endif
  2866. cli.set_follow_location(true);
  2867. auto res = cli.Get(path);
  2868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2869. EXPECT_EQ(StatusCode::OK_200, res->status);
  2870. }
  2871. TEST(RedirectTest, Redirect_Online) {
  2872. auto host = "httpbingo.org";
  2873. auto path = std::string{"/redirect/3"};
  2874. #ifdef CPPHTTPLIB_SSL_ENABLED
  2875. SSLClient cli(host);
  2876. #else
  2877. Client cli(host);
  2878. #endif
  2879. cli.set_follow_location(true);
  2880. auto res = cli.Get(path);
  2881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2882. EXPECT_EQ(StatusCode::OK_200, res->status);
  2883. }
  2884. TEST(RelativeRedirectTest, Redirect_Online) {
  2885. auto host = "httpbingo.org";
  2886. auto path = std::string{"/relative-redirect/3"};
  2887. #ifdef CPPHTTPLIB_SSL_ENABLED
  2888. SSLClient cli(host);
  2889. #else
  2890. Client cli(host);
  2891. #endif
  2892. cli.set_follow_location(true);
  2893. auto res = cli.Get(path);
  2894. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2895. EXPECT_EQ(StatusCode::OK_200, res->status);
  2896. }
  2897. TEST(TooManyRedirectTest, Redirect_Online) {
  2898. auto host = "httpbingo.org";
  2899. auto path = std::string{"/redirect/21"};
  2900. #ifdef CPPHTTPLIB_SSL_ENABLED
  2901. SSLClient cli(host);
  2902. #else
  2903. Client cli(host);
  2904. #endif
  2905. cli.set_follow_location(true);
  2906. auto res = cli.Get(path);
  2907. ASSERT_TRUE(!res);
  2908. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  2909. }
  2910. #ifdef CPPHTTPLIB_SSL_ENABLED
  2911. TEST(YahooRedirectTest, Redirect_Online) {
  2912. Client cli("yahoo.com");
  2913. auto res = cli.Get("/");
  2914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2915. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  2916. cli.set_follow_location(true);
  2917. res = cli.Get("/");
  2918. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2919. EXPECT_EQ(StatusCode::OK_200, res->status);
  2920. EXPECT_EQ("https://www.yahoo.com/", res->location);
  2921. }
  2922. // Previously "nghttp2.org" "/httpbin/redirect-to"
  2923. #define REDIR_HOST "httpbingo.org"
  2924. #define REDIR_PATH "/redirect-to"
  2925. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  2926. SSLClient cli(REDIR_HOST);
  2927. cli.set_follow_location(true);
  2928. auto res =
  2929. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  2930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2931. EXPECT_EQ(StatusCode::OK_200, res->status);
  2932. }
  2933. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  2934. SSLClient cli(REDIR_HOST);
  2935. cli.set_follow_location(true);
  2936. Params params;
  2937. params.emplace("url", "http://example.com");
  2938. params.emplace("status_code", "302");
  2939. auto res = cli.Get(REDIR_PATH, params, Headers{});
  2940. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2941. EXPECT_EQ(StatusCode::OK_200, res->status);
  2942. }
  2943. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  2944. SSLClient cli(REDIR_HOST);
  2945. cli.set_follow_location(true);
  2946. Params params;
  2947. params.emplace("url", "http://example.com");
  2948. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  2949. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2950. EXPECT_EQ(StatusCode::OK_200, res->status);
  2951. }
  2952. TEST(UrlWithSpace, Redirect_Online) {
  2953. SSLClient cli("edge.forgecdn.net");
  2954. cli.set_follow_location(true);
  2955. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  2956. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2957. EXPECT_EQ(StatusCode::OK_200, res->status);
  2958. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  2959. }
  2960. #endif
  2961. #if !defined(_WIN32) && !defined(_WIN64)
  2962. TEST(ReceiveSignals, Signal) {
  2963. auto setupSignalHandlers = []() {
  2964. struct sigaction act;
  2965. sigemptyset(&act.sa_mask);
  2966. act.sa_flags = SA_SIGINFO;
  2967. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  2968. switch (sig) {
  2969. case SIGINT:
  2970. default: break;
  2971. }
  2972. };
  2973. ::sigaction(SIGINT, &act, nullptr);
  2974. };
  2975. Server svr;
  2976. int port = 0;
  2977. auto thread = std::thread([&]() {
  2978. setupSignalHandlers();
  2979. port = svr.bind_to_any_port(HOST);
  2980. svr.listen_after_bind();
  2981. });
  2982. auto se = detail::scope_exit([&] {
  2983. svr.stop();
  2984. thread.join();
  2985. ASSERT_FALSE(svr.is_running());
  2986. });
  2987. svr.wait_until_ready();
  2988. ASSERT_TRUE(svr.is_running());
  2989. pthread_kill(thread.native_handle(), SIGINT);
  2990. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  2991. ASSERT_TRUE(svr.is_running());
  2992. }
  2993. #endif
  2994. TEST(RedirectToDifferentPort, Redirect) {
  2995. Server svr1;
  2996. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  2997. res.set_content("Hello World!", "text/plain");
  2998. });
  2999. int svr1_port = 0;
  3000. auto thread1 = std::thread([&]() {
  3001. svr1_port = svr1.bind_to_any_port(HOST);
  3002. svr1.listen_after_bind();
  3003. });
  3004. Server svr2;
  3005. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3006. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3007. });
  3008. int svr2_port = 0;
  3009. auto thread2 = std::thread([&]() {
  3010. svr2_port = svr2.bind_to_any_port(HOST);
  3011. svr2.listen_after_bind();
  3012. });
  3013. auto se = detail::scope_exit([&] {
  3014. svr2.stop();
  3015. thread2.join();
  3016. svr1.stop();
  3017. thread1.join();
  3018. ASSERT_FALSE(svr2.is_running());
  3019. ASSERT_FALSE(svr1.is_running());
  3020. });
  3021. svr1.wait_until_ready();
  3022. svr2.wait_until_ready();
  3023. Client cli("localhost", svr2_port);
  3024. cli.set_follow_location(true);
  3025. auto res = cli.Get("/2");
  3026. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3027. EXPECT_EQ(StatusCode::OK_200, res->status);
  3028. EXPECT_EQ("Hello World!", res->body);
  3029. }
  3030. static void
  3031. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3032. Server svr1;
  3033. std::string captured_authorization;
  3034. svr1.Get("/target", [&](const Request &req, Response &res) {
  3035. captured_authorization = req.get_header_value("Authorization");
  3036. res.set_content("OK", "text/plain");
  3037. });
  3038. int svr1_port = 0;
  3039. auto thread1 = std::thread([&]() {
  3040. svr1_port = svr1.bind_to_any_port(HOST);
  3041. svr1.listen_after_bind();
  3042. });
  3043. Server svr2;
  3044. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3045. res.set_redirect(
  3046. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  3047. });
  3048. int svr2_port = 0;
  3049. auto thread2 = std::thread([&]() {
  3050. svr2_port = svr2.bind_to_any_port(HOST);
  3051. svr2.listen_after_bind();
  3052. });
  3053. auto se = detail::scope_exit([&] {
  3054. svr2.stop();
  3055. thread2.join();
  3056. svr1.stop();
  3057. thread1.join();
  3058. ASSERT_FALSE(svr2.is_running());
  3059. ASSERT_FALSE(svr1.is_running());
  3060. });
  3061. svr1.wait_until_ready();
  3062. svr2.wait_until_ready();
  3063. Client cli("localhost", svr2_port);
  3064. cli.set_follow_location(true);
  3065. set_auth(cli);
  3066. auto res = cli.Get("/redir");
  3067. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3068. EXPECT_EQ(StatusCode::OK_200, res->status);
  3069. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3070. EXPECT_TRUE(captured_authorization.empty());
  3071. }
  3072. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3073. TestDoNotForwardCredentialsOnRedirect(
  3074. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3075. }
  3076. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3077. TestDoNotForwardCredentialsOnRedirect(
  3078. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3079. }
  3080. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3081. Server svr1;
  3082. std::string captured_cookie;
  3083. bool target_hit = false;
  3084. svr1.Get("/target", [&](const Request &req, Response &res) {
  3085. captured_cookie = req.get_header_value("Cookie");
  3086. target_hit = true;
  3087. res.set_content("OK", "text/plain");
  3088. });
  3089. int svr1_port = 0;
  3090. auto thread1 = std::thread([&]() {
  3091. svr1_port = svr1.bind_to_any_port(HOST);
  3092. svr1.listen_after_bind();
  3093. });
  3094. Server svr2;
  3095. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3096. res.set_redirect(
  3097. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  3098. });
  3099. int svr2_port = 0;
  3100. auto thread2 = std::thread([&]() {
  3101. svr2_port = svr2.bind_to_any_port(HOST);
  3102. svr2.listen_after_bind();
  3103. });
  3104. auto se = detail::scope_exit([&] {
  3105. svr2.stop();
  3106. thread2.join();
  3107. svr1.stop();
  3108. thread1.join();
  3109. ASSERT_FALSE(svr2.is_running());
  3110. ASSERT_FALSE(svr1.is_running());
  3111. });
  3112. svr1.wait_until_ready();
  3113. svr2.wait_until_ready();
  3114. Client cli("localhost", svr2_port);
  3115. cli.set_follow_location(true);
  3116. Headers headers = {{"Cookie", "session_id=SECRET; auth=PRIVATE"}};
  3117. auto res = cli.Get("/redir", headers);
  3118. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3119. EXPECT_EQ(StatusCode::OK_200, res->status);
  3120. EXPECT_TRUE(target_hit);
  3121. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3122. EXPECT_TRUE(captured_cookie.empty());
  3123. }
  3124. TEST(RedirectToSamePort, ForwardCookie) {
  3125. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3126. // header so that ordinary session flows keep working.
  3127. Server svr;
  3128. std::string captured_cookie;
  3129. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3130. res.set_redirect("/target", 302);
  3131. });
  3132. svr.Get("/target", [&](const Request &req, Response &res) {
  3133. captured_cookie = req.get_header_value("Cookie");
  3134. res.set_content("OK", "text/plain");
  3135. });
  3136. auto port = svr.bind_to_any_port(HOST);
  3137. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3138. auto se = detail::scope_exit([&] {
  3139. svr.stop();
  3140. thread.join();
  3141. ASSERT_FALSE(svr.is_running());
  3142. });
  3143. svr.wait_until_ready();
  3144. Client cli(HOST, port);
  3145. cli.set_follow_location(true);
  3146. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3147. auto res = cli.Get("/redir", headers);
  3148. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3149. EXPECT_EQ(StatusCode::OK_200, res->status);
  3150. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3151. }
  3152. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3153. Server svr;
  3154. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3155. // Port number that overflows int — should not crash
  3156. res.set_redirect("http://localhost:99999999999999999999/target");
  3157. });
  3158. auto port = svr.bind_to_any_port(HOST);
  3159. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3160. auto se = detail::scope_exit([&] {
  3161. svr.stop();
  3162. thread.join();
  3163. ASSERT_FALSE(svr.is_running());
  3164. });
  3165. svr.wait_until_ready();
  3166. Client cli(HOST, port);
  3167. cli.set_follow_location(true);
  3168. auto res = cli.Get("/redir");
  3169. // Should fail gracefully, not crash (no valid response due to bad port)
  3170. EXPECT_FALSE(res);
  3171. }
  3172. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3173. Server svr;
  3174. auto port = svr.bind_to_any_port(HOST);
  3175. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3176. // The server's own port followed by junk must not be followed
  3177. res.set_redirect("http://" + std::string(HOST) + ":" +
  3178. std::to_string(port) + "junk/target");
  3179. });
  3180. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3181. res.set_content("target", "text/plain");
  3182. });
  3183. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3184. auto se = detail::scope_exit([&] {
  3185. svr.stop();
  3186. thread.join();
  3187. ASSERT_FALSE(svr.is_running());
  3188. });
  3189. svr.wait_until_ready();
  3190. Client cli(HOST, port);
  3191. cli.set_follow_location(true);
  3192. auto res = cli.Get("/redir");
  3193. EXPECT_FALSE(res);
  3194. }
  3195. TEST(RedirectFromPageWithContent, Redirect) {
  3196. Server svr;
  3197. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3198. res.set_content("___", "text/plain");
  3199. res.set_redirect("/2");
  3200. });
  3201. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3202. res.set_content("Hello World!", "text/plain");
  3203. });
  3204. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3205. auto se = detail::scope_exit([&] {
  3206. svr.stop();
  3207. th.join();
  3208. ASSERT_FALSE(svr.is_running());
  3209. });
  3210. svr.wait_until_ready();
  3211. {
  3212. Client cli("localhost", PORT);
  3213. cli.set_follow_location(true);
  3214. std::string body;
  3215. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3216. body.append(data, data_length);
  3217. return true;
  3218. });
  3219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3220. EXPECT_EQ(StatusCode::OK_200, res->status);
  3221. EXPECT_EQ("Hello World!", body);
  3222. }
  3223. {
  3224. Client cli("localhost", PORT);
  3225. std::string body;
  3226. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3227. body.append(data, data_length);
  3228. return true;
  3229. });
  3230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3231. EXPECT_EQ(StatusCode::Found_302, res->status);
  3232. EXPECT_EQ("___", body);
  3233. }
  3234. }
  3235. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3236. Server svr;
  3237. auto port_str = std::to_string(PORT);
  3238. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3239. auto expected_host = "[::1]:" + port_str;
  3240. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3241. res.set_content("___", "text/plain");
  3242. // res.set_redirect("/2");
  3243. res.set_redirect(redirect_url);
  3244. });
  3245. svr.Get("/2", [&](const Request &req, Response &res) {
  3246. auto host_header = req.headers.find("Host");
  3247. ASSERT_TRUE(host_header != req.headers.end());
  3248. EXPECT_EQ(expected_host, host_header->second);
  3249. res.set_content("Hello World!", "text/plain");
  3250. });
  3251. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3252. auto se = detail::scope_exit([&] {
  3253. svr.stop();
  3254. th.join();
  3255. ASSERT_FALSE(svr.is_running());
  3256. });
  3257. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3258. // actually starts anything, so the condition !svr.is_running() will
  3259. // always remain true, and the loop never stops.
  3260. // This basically counts how many milliseconds have passed since the
  3261. // call to svr.listen(), and if after 5 seconds nothing started yet
  3262. // aborts the test.
  3263. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3264. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3265. ASSERT_LT(milliseconds, 5000U);
  3266. }
  3267. {
  3268. Client cli("::1", PORT);
  3269. cli.set_follow_location(true);
  3270. std::string body;
  3271. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3272. body.append(data, data_length);
  3273. return true;
  3274. });
  3275. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3276. EXPECT_EQ(StatusCode::OK_200, res->status);
  3277. EXPECT_EQ("Hello World!", body);
  3278. }
  3279. {
  3280. Client cli("::1", PORT);
  3281. std::string body;
  3282. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3283. body.append(data, data_length);
  3284. return true;
  3285. });
  3286. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3287. EXPECT_EQ(StatusCode::Found_302, res->status);
  3288. EXPECT_EQ("___", body);
  3289. }
  3290. }
  3291. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3292. Server svr;
  3293. svr.Get("/foo", [](const Request &req, Response &res) {
  3294. auto a = req.params.find("a");
  3295. if (a != req.params.end()) {
  3296. res.set_content((*a).second, "text/plain");
  3297. res.status = StatusCode::OK_200;
  3298. } else {
  3299. res.status = StatusCode::BadRequest_400;
  3300. }
  3301. });
  3302. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3303. auto se = detail::scope_exit([&] {
  3304. svr.stop();
  3305. thread.join();
  3306. ASSERT_FALSE(svr.is_running());
  3307. });
  3308. svr.wait_until_ready();
  3309. {
  3310. Client cli(HOST, PORT);
  3311. cli.set_path_encode(false);
  3312. auto res = cli.Get("/foo?a=explicitly+encoded");
  3313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3314. EXPECT_EQ(StatusCode::OK_200, res->status);
  3315. // This expects it back with a space, as the `+` won't have been
  3316. // url-encoded, and server-side the params get decoded turning `+`
  3317. // into spaces.
  3318. EXPECT_EQ("explicitly encoded", res->body);
  3319. }
  3320. }
  3321. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3322. // When path encoding is disabled the client must transmit the supplied
  3323. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3324. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3325. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3326. // than a space (0x20). Assert on the raw wire target to catch this.
  3327. Server svr;
  3328. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3329. svr.Get("/foo", [&](const Request &req, Response &res) {
  3330. EXPECT_EQ(expected_target, req.target);
  3331. res.status = StatusCode::OK_200;
  3332. });
  3333. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3334. auto se = detail::scope_exit([&] {
  3335. svr.stop();
  3336. thread.join();
  3337. ASSERT_FALSE(svr.is_running());
  3338. });
  3339. svr.wait_until_ready();
  3340. {
  3341. Client cli(HOST, PORT);
  3342. cli.set_path_encode(false);
  3343. auto res = cli.Get(expected_target.c_str());
  3344. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3345. EXPECT_EQ(StatusCode::OK_200, res->status);
  3346. }
  3347. }
  3348. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3349. // `open_stream()` used to skip the path encoding that the buffered send
  3350. // path applies, so the same `path` produced different bytes in the request
  3351. // line depending on which API was used. Assert the two agree.
  3352. Server svr;
  3353. std::string target;
  3354. svr.Get(".*", [&](const Request &req, Response &res) {
  3355. target = req.target;
  3356. res.status = StatusCode::OK_200;
  3357. });
  3358. auto port = svr.bind_to_any_port(HOST);
  3359. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3360. auto se = detail::scope_exit([&] {
  3361. svr.stop();
  3362. thread.join();
  3363. ASSERT_FALSE(svr.is_running());
  3364. });
  3365. svr.wait_until_ready();
  3366. struct {
  3367. const char *path;
  3368. const char *expected;
  3369. } cases[] = {
  3370. {"/a b?x=1", "/a%20b?x=1"},
  3371. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3372. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3373. };
  3374. for (const auto &c : cases) {
  3375. Client cli(HOST, port);
  3376. target.clear();
  3377. auto res = cli.Get(c.path);
  3378. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3379. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3380. auto buffered_target = target;
  3381. target.clear();
  3382. auto handle = cli.open_stream("GET", c.path);
  3383. EXPECT_TRUE(handle.is_valid())
  3384. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3385. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3386. }
  3387. }
  3388. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3389. // The `set_path_encode(false)` contract — transmit the supplied target
  3390. // verbatim — must hold for the streaming API too.
  3391. Server svr;
  3392. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3393. std::string target;
  3394. svr.Get("/foo", [&](const Request &req, Response &res) {
  3395. target = req.target;
  3396. res.status = StatusCode::OK_200;
  3397. });
  3398. auto port = svr.bind_to_any_port(HOST);
  3399. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3400. auto se = detail::scope_exit([&] {
  3401. svr.stop();
  3402. thread.join();
  3403. ASSERT_FALSE(svr.is_running());
  3404. });
  3405. svr.wait_until_ready();
  3406. {
  3407. Client cli(HOST, port);
  3408. cli.set_path_encode(false);
  3409. auto handle = cli.open_stream("GET", expected_target);
  3410. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3411. EXPECT_EQ(expected_target, target);
  3412. }
  3413. }
  3414. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3415. // With path encoding enabled a CR/LF in the target is percent-encoded
  3416. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3417. // write_request_line still backstops `set_path_encode(false)`, which is
  3418. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3419. Server svr;
  3420. // Captured before routing: the decoded path contains a newline, which a
  3421. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3422. std::string target;
  3423. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3424. target = req.target;
  3425. res.status = StatusCode::OK_200;
  3426. return Server::HandlerResponse::Handled;
  3427. });
  3428. auto port = svr.bind_to_any_port(HOST);
  3429. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3430. auto se = detail::scope_exit([&] {
  3431. svr.stop();
  3432. thread.join();
  3433. ASSERT_FALSE(svr.is_running());
  3434. });
  3435. svr.wait_until_ready();
  3436. {
  3437. Client cli(HOST, port);
  3438. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3439. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3440. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3441. }
  3442. }
  3443. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  3444. // Every control character is percent-encoded, not just CR/LF, so the target
  3445. // passes the request-target check in write_request_line.
  3446. Server svr;
  3447. std::string target;
  3448. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3449. target = req.target;
  3450. res.status = StatusCode::OK_200;
  3451. return Server::HandlerResponse::Handled;
  3452. });
  3453. auto port = svr.bind_to_any_port(HOST);
  3454. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3455. auto se = detail::scope_exit([&] {
  3456. svr.stop();
  3457. thread.join();
  3458. ASSERT_FALSE(svr.is_running());
  3459. });
  3460. svr.wait_until_ready();
  3461. {
  3462. Client cli(HOST, port);
  3463. auto res = cli.Get("/a\tb\x1b\x7f");
  3464. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3465. EXPECT_EQ("/a%09b%1B%7F", target);
  3466. }
  3467. }
  3468. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3469. // Nothing may reach the wire: a raw CR/LF target would split the request
  3470. // line and inject headers.
  3471. Server svr;
  3472. // Pre-routing so that "not called" means nothing reached the server at all,
  3473. // rather than merely failing to match a handler pattern.
  3474. auto handler_called = false;
  3475. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3476. handler_called = true;
  3477. res.status = StatusCode::OK_200;
  3478. return Server::HandlerResponse::Handled;
  3479. });
  3480. auto port = svr.bind_to_any_port(HOST);
  3481. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3482. auto se = detail::scope_exit([&] {
  3483. svr.stop();
  3484. thread.join();
  3485. ASSERT_FALSE(svr.is_running());
  3486. });
  3487. svr.wait_until_ready();
  3488. {
  3489. Client cli(HOST, port);
  3490. cli.set_path_encode(false);
  3491. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3492. EXPECT_FALSE(handle.is_valid());
  3493. EXPECT_EQ(Error::Write, handle.error);
  3494. EXPECT_FALSE(handler_called);
  3495. }
  3496. }
  3497. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3498. // Which of the two branches runs is decided by whether the query component
  3499. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3500. // an empty query and must still fall back to building one from
  3501. // `req.params`, while a non-empty query must win over `req.params`.
  3502. Server svr;
  3503. std::string target;
  3504. svr.Get("/foo", [&](const Request &req, Response &res) {
  3505. target = req.target;
  3506. res.status = StatusCode::OK_200;
  3507. });
  3508. auto port = svr.bind_to_any_port(HOST);
  3509. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3510. auto se = detail::scope_exit([&] {
  3511. svr.stop();
  3512. thread.join();
  3513. ASSERT_FALSE(svr.is_running());
  3514. });
  3515. svr.wait_until_ready();
  3516. {
  3517. // Trailing `?` -> empty query component -> `req.params` is used.
  3518. Client cli(HOST, port);
  3519. Request req;
  3520. req.method = "GET";
  3521. req.path = "/foo?";
  3522. req.params.emplace("a", "1");
  3523. target.clear();
  3524. auto res = cli.send(req);
  3525. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3526. EXPECT_EQ("/foo?a=1", target);
  3527. }
  3528. {
  3529. // Non-empty query in `req.path` -> `req.params` is not appended.
  3530. Client cli(HOST, port);
  3531. Request req;
  3532. req.method = "GET";
  3533. req.path = "/foo?b=2";
  3534. req.params.emplace("a", "1");
  3535. target.clear();
  3536. auto res = cli.send(req);
  3537. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3538. EXPECT_EQ("/foo?b=2", target);
  3539. }
  3540. }
  3541. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3542. Server svr;
  3543. svr.Get("/", [](const Request &req, Response &) {
  3544. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3545. });
  3546. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3547. auto se = detail::scope_exit([&] {
  3548. svr.stop();
  3549. thread.join();
  3550. ASSERT_FALSE(svr.is_running());
  3551. });
  3552. svr.wait_until_ready();
  3553. {
  3554. Client cli(HOST, PORT);
  3555. cli.set_path_encode(false);
  3556. auto res = cli.Get("/?something=%0A");
  3557. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3558. EXPECT_EQ(StatusCode::OK_200, res->status);
  3559. }
  3560. }
  3561. TEST(BindServerTest, BindDualStack) {
  3562. Server svr;
  3563. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3564. res.set_content("Hello World!", "text/plain");
  3565. });
  3566. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3567. auto se = detail::scope_exit([&] {
  3568. svr.stop();
  3569. thread.join();
  3570. ASSERT_FALSE(svr.is_running());
  3571. });
  3572. svr.wait_until_ready();
  3573. {
  3574. Client cli("127.0.0.1", PORT);
  3575. auto res = cli.Get("/1");
  3576. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3577. EXPECT_EQ(StatusCode::OK_200, res->status);
  3578. EXPECT_EQ("Hello World!", res->body);
  3579. }
  3580. {
  3581. Client cli("::1", PORT);
  3582. auto res = cli.Get("/1");
  3583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3584. EXPECT_EQ(StatusCode::OK_200, res->status);
  3585. EXPECT_EQ("Hello World!", res->body);
  3586. }
  3587. }
  3588. TEST(BindServerTest, BindAndListenSeparately) {
  3589. Server svr;
  3590. int port = svr.bind_to_any_port("0.0.0.0");
  3591. ASSERT_TRUE(svr.is_valid());
  3592. ASSERT_TRUE(port > 0);
  3593. svr.stop();
  3594. }
  3595. // Reports whether anything is still listening on a loopback port. A plain
  3596. // connect() is used instead of a Client request because a socket left bound by
  3597. // mistake accepts the connection into its backlog and never answers, which
  3598. // would hang the test instead of failing it.
  3599. static bool is_loopback_port_accepting(int port) {
  3600. sockaddr_in addr{};
  3601. addr.sin_family = AF_INET;
  3602. addr.sin_port = htons(static_cast<uint16_t>(port));
  3603. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3604. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3605. EXPECT_NE(sock, INVALID_SOCKET);
  3606. if (sock == INVALID_SOCKET) { return false; }
  3607. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3608. static_cast<socklen_t>(sizeof(addr)));
  3609. detail::close_socket(sock);
  3610. return ret == 0;
  3611. }
  3612. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3613. Server svr;
  3614. auto port = svr.bind_to_any_port("127.0.0.1");
  3615. ASSERT_TRUE(port > 0);
  3616. svr.stop();
  3617. // bind_to_any_port() already called listen(2), so until stop() closed the
  3618. // descriptor the port kept accepting connections into the backlog. ASSERT
  3619. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3620. // below blocks forever in the accept loop.
  3621. ASSERT_FALSE(is_loopback_port_accepting(port));
  3622. // Nothing is left to accept on, so listen_after_bind() must report failure
  3623. // instead of returning success without ever serving.
  3624. EXPECT_FALSE(svr.listen_after_bind());
  3625. // The failed listen marks the server decommissioned, so a waiter returns
  3626. // instead of spinning forever.
  3627. svr.wait_until_ready();
  3628. }
  3629. #ifdef CPPHTTPLIB_SSL_ENABLED
  3630. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3631. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3632. CLIENT_CA_CERT_DIR);
  3633. int port = svr.bind_to_any_port("0.0.0.0");
  3634. ASSERT_TRUE(svr.is_valid());
  3635. ASSERT_TRUE(port > 0);
  3636. svr.stop();
  3637. }
  3638. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  3639. // or a rejected CustomRoute() registration would not stop the server binding.
  3640. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  3641. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3642. CLIENT_CA_CERT_DIR);
  3643. ASSERT_TRUE(svr.is_valid());
  3644. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  3645. EXPECT_FALSE(svr.is_valid());
  3646. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  3647. }
  3648. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  3649. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  3650. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  3651. int port = svr.bind_to_any_port("0.0.0.0");
  3652. ASSERT_TRUE(svr.is_valid());
  3653. ASSERT_TRUE(port > 0);
  3654. svr.stop();
  3655. }
  3656. TEST(BindServerTest, UpdateCertsPem) {
  3657. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3658. int port = svr.bind_to_any_port("0.0.0.0");
  3659. ASSERT_TRUE(svr.is_valid());
  3660. ASSERT_TRUE(port > 0);
  3661. // Read PEM files
  3662. std::string cert_pem, key_pem, ca_pem;
  3663. read_file(SERVER_CERT_FILE, cert_pem);
  3664. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3665. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3666. // Update server certificates using PEM API
  3667. ASSERT_TRUE(
  3668. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3669. ASSERT_TRUE(svr.is_valid());
  3670. svr.stop();
  3671. }
  3672. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  3673. // Start server with client CA (enables client auth)
  3674. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3675. ASSERT_TRUE(svr.is_valid());
  3676. bool handler_called = false;
  3677. svr.Get("/test", [&](const Request &req, Response &res) {
  3678. handler_called = true;
  3679. // Verify client certificate is present
  3680. auto cert = req.peer_cert();
  3681. EXPECT_TRUE(static_cast<bool>(cert));
  3682. res.set_content("ok", "text/plain");
  3683. });
  3684. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3685. auto se = detail::scope_exit([&] {
  3686. svr.stop();
  3687. t.join();
  3688. ASSERT_FALSE(svr.is_running());
  3689. });
  3690. svr.wait_until_ready();
  3691. // Read PEM files
  3692. std::string cert_pem, key_pem, ca_pem;
  3693. read_file(SERVER_CERT_FILE, cert_pem);
  3694. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3695. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3696. // Update server certificates and client CA using PEM API while server running
  3697. ASSERT_TRUE(
  3698. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3699. // Connect with client certificate
  3700. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3701. cli.enable_server_certificate_verification(false);
  3702. cli.set_connection_timeout(30);
  3703. auto res = cli.Get("/test");
  3704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3705. ASSERT_EQ(StatusCode::OK_200, res->status);
  3706. ASSERT_TRUE(handler_called);
  3707. EXPECT_EQ("ok", res->body);
  3708. }
  3709. #endif
  3710. TEST(ErrorHandlerTest, ContentLength) {
  3711. Server svr;
  3712. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3713. res.status = StatusCode::OK_200;
  3714. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3715. "text/html"); // <= Content-Length still 13
  3716. });
  3717. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3718. res.set_content("Hello World!\n", "text/plain");
  3719. res.status = 524;
  3720. });
  3721. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3722. auto se = detail::scope_exit([&] {
  3723. svr.stop();
  3724. thread.join();
  3725. ASSERT_FALSE(svr.is_running());
  3726. });
  3727. svr.wait_until_ready();
  3728. {
  3729. Client cli(HOST, PORT);
  3730. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3731. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3732. EXPECT_EQ(StatusCode::OK_200, res->status);
  3733. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3734. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3735. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3736. }
  3737. }
  3738. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3739. TEST(ExceptionTest, WithoutExceptionHandler) {
  3740. Server svr;
  3741. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  3742. throw std::runtime_error("exception...");
  3743. });
  3744. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  3745. throw std::runtime_error("exception\r\n...");
  3746. });
  3747. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3748. auto se = detail::scope_exit([&] {
  3749. svr.stop();
  3750. listen_thread.join();
  3751. ASSERT_FALSE(svr.is_running());
  3752. });
  3753. svr.wait_until_ready();
  3754. Client cli("localhost", PORT);
  3755. {
  3756. auto res = cli.Get("/exception");
  3757. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3758. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3759. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3760. }
  3761. {
  3762. auto res = cli.Get("/unknown");
  3763. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3764. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3765. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3766. }
  3767. }
  3768. TEST(ExceptionTest, WithExceptionHandler) {
  3769. Server svr;
  3770. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  3771. std::exception_ptr ep) {
  3772. EXPECT_FALSE(ep == nullptr);
  3773. try {
  3774. std::rethrow_exception(ep);
  3775. } catch (std::exception &e) {
  3776. EXPECT_EQ("abc", std::string(e.what()));
  3777. } catch (...) {}
  3778. res.status = StatusCode::InternalServerError_500;
  3779. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3780. "text/html"); // <= Content-Length still 13 at this point
  3781. });
  3782. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3783. res.set_content("Hello World!\n", "text/plain");
  3784. throw std::runtime_error("abc");
  3785. });
  3786. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3787. auto se = detail::scope_exit([&] {
  3788. svr.stop();
  3789. thread.join();
  3790. ASSERT_FALSE(svr.is_running());
  3791. });
  3792. svr.wait_until_ready();
  3793. for (size_t i = 0; i < 10; i++) {
  3794. Client cli(HOST, PORT);
  3795. for (size_t j = 0; j < 100; j++) {
  3796. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3797. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3798. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3799. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3800. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3801. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3802. }
  3803. cli.set_keep_alive(true);
  3804. for (size_t j = 0; j < 100; j++) {
  3805. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3806. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3807. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3808. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3809. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3810. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3811. }
  3812. }
  3813. }
  3814. TEST(ExceptionTest, AndErrorHandler) {
  3815. Server svr;
  3816. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3817. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  3818. });
  3819. svr.set_exception_handler(
  3820. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  3821. EXPECT_FALSE(ep == nullptr);
  3822. try {
  3823. std::rethrow_exception(ep);
  3824. } catch (std::exception &e) {
  3825. res.set_content(e.what(), "text/html");
  3826. } catch (...) {}
  3827. res.status = StatusCode::InternalServerError_500;
  3828. });
  3829. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  3830. throw std::runtime_error("EXCEPTION");
  3831. });
  3832. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  3833. res.set_content("ERROR", "text/html");
  3834. res.status = StatusCode::InternalServerError_500;
  3835. });
  3836. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3837. auto se = detail::scope_exit([&] {
  3838. svr.stop();
  3839. thread.join();
  3840. ASSERT_FALSE(svr.is_running());
  3841. });
  3842. svr.wait_until_ready();
  3843. Client cli(HOST, PORT);
  3844. {
  3845. auto res = cli.Get("/exception");
  3846. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3847. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3848. EXPECT_EQ("EXCEPTION", res->body);
  3849. }
  3850. {
  3851. auto res = cli.Get("/error");
  3852. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3853. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3854. EXPECT_EQ("ERROR", res->body);
  3855. }
  3856. {
  3857. auto res = cli.Get("/invalid");
  3858. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3859. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3860. EXPECT_EQ("NOT_FOUND", res->body);
  3861. }
  3862. }
  3863. #endif
  3864. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3865. // process_request() wraps only routing() in a try/catch, so an exception from
  3866. // any other user callback used to unwind into the task queue - which does not
  3867. // catch - and terminate the process. Each test below runs the server on a
  3868. // single worker thread: a guard that catches the exception but still loses the
  3869. // thread would otherwise be hidden by a spare worker serving the follow-up
  3870. // request. Note that a regression here aborts the whole test binary rather
  3871. // than failing one test.
  3872. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  3873. Server svr;
  3874. svr.new_task_queue = [] { return new ThreadPool(1); };
  3875. std::atomic<int> reported{0};
  3876. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  3877. if (err == Error::UserCallbackException) { reported++; }
  3878. });
  3879. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  3880. res.set_content_provider(
  3881. 1024, "text/plain",
  3882. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  3883. sink.write("hello", 5);
  3884. throw std::runtime_error("from the content provider");
  3885. });
  3886. });
  3887. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  3888. res.set_content("ok", "text/plain");
  3889. });
  3890. auto port = svr.bind_to_any_port(HOST);
  3891. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3892. auto se = detail::scope_exit([&] {
  3893. svr.stop();
  3894. listen_thread.join();
  3895. ASSERT_FALSE(svr.is_running());
  3896. });
  3897. svr.wait_until_ready();
  3898. {
  3899. Client cli(HOST, port);
  3900. cli.set_read_timeout(5, 0);
  3901. EXPECT_FALSE(cli.Get("/throw"));
  3902. }
  3903. EXPECT_TRUE(svr.is_running());
  3904. EXPECT_EQ(1, reported.load());
  3905. // A request on a fresh connection is still served.
  3906. {
  3907. Client cli(HOST, port);
  3908. auto res = cli.Get("/ok");
  3909. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3910. EXPECT_EQ(StatusCode::OK_200, res->status);
  3911. EXPECT_EQ("ok", res->body);
  3912. }
  3913. }
  3914. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  3915. Server svr;
  3916. svr.new_task_queue = [] { return new ThreadPool(1); };
  3917. std::atomic<bool> should_throw{true};
  3918. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3919. res.set_content("hi", "text/plain");
  3920. });
  3921. svr.set_post_routing_handler(
  3922. [&](const Request & /*req*/, Response & /*res*/) {
  3923. if (should_throw) {
  3924. throw std::runtime_error("from the post-routing handler");
  3925. }
  3926. });
  3927. auto port = svr.bind_to_any_port(HOST);
  3928. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3929. auto se = detail::scope_exit([&] {
  3930. svr.stop();
  3931. listen_thread.join();
  3932. ASSERT_FALSE(svr.is_running());
  3933. });
  3934. svr.wait_until_ready();
  3935. {
  3936. Client cli(HOST, port);
  3937. cli.set_read_timeout(5, 0);
  3938. EXPECT_FALSE(cli.Get("/hi"));
  3939. }
  3940. EXPECT_TRUE(svr.is_running());
  3941. should_throw = false;
  3942. {
  3943. Client cli(HOST, port);
  3944. auto res = cli.Get("/hi");
  3945. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3946. EXPECT_EQ(StatusCode::OK_200, res->status);
  3947. EXPECT_EQ("hi", res->body);
  3948. }
  3949. }
  3950. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  3951. // The guard reports the caught exception through the error logger, which is
  3952. // a user callback too. A logger that throws has to be contained as well, or
  3953. // the process would terminate from inside the catch.
  3954. Server svr;
  3955. svr.new_task_queue = [] { return new ThreadPool(1); };
  3956. std::atomic<int> reported{0};
  3957. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  3958. if (err == Error::UserCallbackException) {
  3959. reported++;
  3960. throw std::runtime_error("from the error logger");
  3961. }
  3962. });
  3963. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  3964. res.set_content_provider(
  3965. 1024, "text/plain",
  3966. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  3967. sink.write("hello", 5);
  3968. throw std::runtime_error("from the content provider");
  3969. });
  3970. });
  3971. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  3972. res.set_content("ok", "text/plain");
  3973. });
  3974. auto port = svr.bind_to_any_port(HOST);
  3975. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3976. auto se = detail::scope_exit([&] {
  3977. svr.stop();
  3978. listen_thread.join();
  3979. ASSERT_FALSE(svr.is_running());
  3980. });
  3981. svr.wait_until_ready();
  3982. {
  3983. Client cli(HOST, port);
  3984. cli.set_read_timeout(5, 0);
  3985. EXPECT_FALSE(cli.Get("/throw"));
  3986. }
  3987. EXPECT_TRUE(svr.is_running());
  3988. EXPECT_EQ(1, reported.load());
  3989. {
  3990. Client cli(HOST, port);
  3991. auto res = cli.Get("/ok");
  3992. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3993. EXPECT_EQ(StatusCode::OK_200, res->status);
  3994. EXPECT_EQ("ok", res->body);
  3995. }
  3996. }
  3997. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  3998. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  3999. // so the exception unwinds through the ws::WebSocket object on its way to
  4000. // the guard. None of the HTTP cases above cross that.
  4001. Server svr;
  4002. svr.new_task_queue = [] { return new ThreadPool(1); };
  4003. std::atomic<int> reported{0};
  4004. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4005. if (err == Error::UserCallbackException) { reported++; }
  4006. });
  4007. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  4008. throw std::runtime_error("from the WebSocket handler");
  4009. });
  4010. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4011. res.set_content("ok", "text/plain");
  4012. });
  4013. auto port = svr.bind_to_any_port(HOST);
  4014. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4015. auto se = detail::scope_exit([&] {
  4016. svr.stop();
  4017. listen_thread.join();
  4018. ASSERT_FALSE(svr.is_running());
  4019. });
  4020. svr.wait_until_ready();
  4021. {
  4022. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  4023. "/ws");
  4024. auto res = client.connect();
  4025. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4026. // The server dropped the connection instead of dying.
  4027. std::string msg;
  4028. EXPECT_FALSE(client.read(msg));
  4029. client.close();
  4030. }
  4031. EXPECT_TRUE(svr.is_running());
  4032. EXPECT_EQ(1, reported.load());
  4033. {
  4034. Client cli(HOST, port);
  4035. auto res = cli.Get("/ok");
  4036. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4037. EXPECT_EQ(StatusCode::OK_200, res->status);
  4038. EXPECT_EQ("ok", res->body);
  4039. }
  4040. }
  4041. #ifdef CPPHTTPLIB_SSL_ENABLED
  4042. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  4043. // SSLServer::process_and_close_socket() is a separate overload with its own
  4044. // guard, so it is exercised on its own.
  4045. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4046. ASSERT_TRUE(svr.is_valid());
  4047. svr.new_task_queue = [] { return new ThreadPool(1); };
  4048. std::atomic<int> reported{0};
  4049. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4050. if (err == Error::UserCallbackException) { reported++; }
  4051. });
  4052. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4053. res.set_content_provider(
  4054. 1024, "text/plain",
  4055. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4056. sink.write("hello", 5);
  4057. throw std::runtime_error("from the content provider");
  4058. });
  4059. });
  4060. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4061. res.set_content("ok", "text/plain");
  4062. });
  4063. auto port = svr.bind_to_any_port(HOST);
  4064. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4065. auto se = detail::scope_exit([&] {
  4066. svr.stop();
  4067. listen_thread.join();
  4068. ASSERT_FALSE(svr.is_running());
  4069. });
  4070. svr.wait_until_ready();
  4071. {
  4072. SSLClient cli(HOST, port);
  4073. cli.enable_server_certificate_verification(false);
  4074. cli.set_read_timeout(5, 0);
  4075. EXPECT_FALSE(cli.Get("/throw"));
  4076. }
  4077. EXPECT_TRUE(svr.is_running());
  4078. EXPECT_EQ(1, reported.load());
  4079. {
  4080. SSLClient cli(HOST, port);
  4081. cli.enable_server_certificate_verification(false);
  4082. auto res = cli.Get("/ok");
  4083. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4084. EXPECT_EQ(StatusCode::OK_200, res->status);
  4085. EXPECT_EQ("ok", res->body);
  4086. }
  4087. }
  4088. #endif
  4089. #endif
  4090. TEST(NoContentTest, ContentLength) {
  4091. Server svr;
  4092. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4093. res.status = StatusCode::NoContent_204;
  4094. });
  4095. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4096. auto se = detail::scope_exit([&] {
  4097. svr.stop();
  4098. thread.join();
  4099. ASSERT_FALSE(svr.is_running());
  4100. });
  4101. svr.wait_until_ready();
  4102. {
  4103. Client cli(HOST, PORT);
  4104. auto res = cli.Get("/hi");
  4105. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4106. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  4107. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4108. }
  4109. }
  4110. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  4111. #ifdef CPPHTTPLIB_SSL_ENABLED
  4112. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4113. ASSERT_TRUE(svr.is_valid());
  4114. #else
  4115. Server svr;
  4116. #endif
  4117. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  4118. if (req.path == "/routing_handler") {
  4119. res.set_header("PRE_ROUTING", "on");
  4120. res.set_content("Routing Handler", "text/plain");
  4121. return httplib::Server::HandlerResponse::Handled;
  4122. }
  4123. return httplib::Server::HandlerResponse::Unhandled;
  4124. });
  4125. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4126. res.set_content("Error", "text/html");
  4127. });
  4128. svr.set_post_routing_handler([](const Request &req, Response &res) {
  4129. if (req.path == "/routing_handler") {
  4130. res.set_header("POST_ROUTING", "on");
  4131. }
  4132. });
  4133. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4134. res.set_content("Hello World!\n", "text/plain");
  4135. });
  4136. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4137. auto se = detail::scope_exit([&] {
  4138. svr.stop();
  4139. thread.join();
  4140. ASSERT_FALSE(svr.is_running());
  4141. });
  4142. svr.wait_until_ready();
  4143. {
  4144. #ifdef CPPHTTPLIB_SSL_ENABLED
  4145. SSLClient cli(HOST, PORT);
  4146. cli.enable_server_certificate_verification(false);
  4147. #else
  4148. Client cli(HOST, PORT);
  4149. #endif
  4150. auto res = cli.Get("/routing_handler");
  4151. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4152. EXPECT_EQ(StatusCode::OK_200, res->status);
  4153. EXPECT_EQ("Routing Handler", res->body);
  4154. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  4155. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  4156. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  4157. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  4158. }
  4159. {
  4160. #ifdef CPPHTTPLIB_SSL_ENABLED
  4161. SSLClient cli(HOST, PORT);
  4162. cli.enable_server_certificate_verification(false);
  4163. #else
  4164. Client cli(HOST, PORT);
  4165. #endif
  4166. auto res = cli.Get("/hi");
  4167. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4168. EXPECT_EQ(StatusCode::OK_200, res->status);
  4169. EXPECT_EQ("Hello World!\n", res->body);
  4170. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4171. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4172. }
  4173. {
  4174. #ifdef CPPHTTPLIB_SSL_ENABLED
  4175. SSLClient cli(HOST, PORT);
  4176. cli.enable_server_certificate_verification(false);
  4177. #else
  4178. Client cli(HOST, PORT);
  4179. #endif
  4180. auto res = cli.Get("/aaa");
  4181. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4182. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4183. EXPECT_EQ("Error", res->body);
  4184. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4185. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4186. }
  4187. }
  4188. TEST(RequestHandlerTest, PreRequestHandler) {
  4189. auto route_path = "/user/:user";
  4190. Server svr;
  4191. svr.Get("/hi", [](const Request &, Response &res) {
  4192. res.set_content("hi", "text/plain");
  4193. });
  4194. svr.Get(route_path, [](const Request &req, Response &res) {
  4195. res.set_content(req.path_params.at("user"), "text/plain");
  4196. });
  4197. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  4198. if (req.matched_route == route_path) {
  4199. auto user = req.path_params.at("user");
  4200. if (user != "john") {
  4201. res.status = StatusCode::Forbidden_403;
  4202. res.set_content("error", "text/html");
  4203. return Server::HandlerResponse::Handled;
  4204. }
  4205. }
  4206. return Server::HandlerResponse::Unhandled;
  4207. });
  4208. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4209. auto se = detail::scope_exit([&] {
  4210. svr.stop();
  4211. thread.join();
  4212. ASSERT_FALSE(svr.is_running());
  4213. });
  4214. svr.wait_until_ready();
  4215. Client cli(HOST, PORT);
  4216. {
  4217. auto res = cli.Get("/hi");
  4218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4219. EXPECT_EQ(StatusCode::OK_200, res->status);
  4220. EXPECT_EQ("hi", res->body);
  4221. }
  4222. {
  4223. auto res = cli.Get("/user/john");
  4224. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4225. EXPECT_EQ(StatusCode::OK_200, res->status);
  4226. EXPECT_EQ("john", res->body);
  4227. }
  4228. {
  4229. auto res = cli.Get("/user/invalid-user");
  4230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4231. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4232. EXPECT_EQ("error", res->body);
  4233. }
  4234. }
  4235. // The pre-request handler must run before the request body is read, so a
  4236. // rejected request never forces the server to buffer a (potentially large)
  4237. // body. Here the posted body is larger than the payload limit: if the body
  4238. // were read first the server would answer 413, but because the pre-request
  4239. // handler runs first it answers 403 and the body is never read.
  4240. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  4241. Server svr;
  4242. svr.set_payload_max_length(8);
  4243. auto handler_ran = false;
  4244. svr.Post("/reject", [&](const Request &req, Response &res) {
  4245. handler_ran = true;
  4246. res.set_content(req.body, "text/plain");
  4247. });
  4248. svr.Post("/accept", [](const Request &req, Response &res) {
  4249. res.set_content(req.body, "text/plain");
  4250. });
  4251. svr.set_pre_request_handler([](const Request &req, Response &res) {
  4252. if (req.matched_route == "/reject") {
  4253. res.status = StatusCode::Forbidden_403;
  4254. res.set_content("denied", "text/plain");
  4255. return Server::HandlerResponse::Handled;
  4256. }
  4257. return Server::HandlerResponse::Unhandled;
  4258. });
  4259. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4260. auto se = detail::scope_exit([&] {
  4261. svr.stop();
  4262. thread.join();
  4263. ASSERT_FALSE(svr.is_running());
  4264. });
  4265. svr.wait_until_ready();
  4266. Client cli(HOST, PORT);
  4267. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  4268. // rejects with 403 before the body is read, so 413 is never reached.
  4269. {
  4270. auto res = cli.Post("/reject", "0123456789", "text/plain");
  4271. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4272. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4273. EXPECT_EQ("denied", res->body);
  4274. EXPECT_FALSE(handler_ran);
  4275. }
  4276. // An approved route still reads the body and enforces the payload limit.
  4277. {
  4278. auto res = cli.Post("/accept", "0123456789", "text/plain");
  4279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4280. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  4281. }
  4282. }
  4283. TEST(UserDataTest, BasicOperations) {
  4284. httplib::UserData ud;
  4285. // Initially empty
  4286. EXPECT_FALSE(ud.has("key"));
  4287. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4288. // set and get
  4289. ud.set("key", 42);
  4290. EXPECT_TRUE(ud.has("key"));
  4291. auto *p = ud.get<int>("key");
  4292. ASSERT_NE(nullptr, p);
  4293. EXPECT_EQ(42, *p);
  4294. // Type mismatch → nullptr
  4295. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  4296. // Overwrite with different type
  4297. ud.set("key", std::string("hello"));
  4298. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4299. auto *s = ud.get<std::string>("key");
  4300. ASSERT_NE(nullptr, s);
  4301. EXPECT_EQ("hello", *s);
  4302. // erase
  4303. ud.erase("key");
  4304. EXPECT_FALSE(ud.has("key"));
  4305. // clear
  4306. ud.set("a", 1);
  4307. ud.set("b", 2);
  4308. ud.clear();
  4309. EXPECT_FALSE(ud.has("a"));
  4310. EXPECT_FALSE(ud.has("b"));
  4311. }
  4312. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  4313. struct AuthCtx {
  4314. std::string user_id;
  4315. };
  4316. Server svr;
  4317. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  4318. res.user_data.set("auth", AuthCtx{"alice"});
  4319. return Server::HandlerResponse::Unhandled;
  4320. });
  4321. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  4322. auto *ctx = res.user_data.get<AuthCtx>("auth");
  4323. ASSERT_NE(nullptr, ctx);
  4324. res.set_content("Hello " + ctx->user_id, "text/plain");
  4325. });
  4326. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4327. auto se = detail::scope_exit([&] {
  4328. svr.stop();
  4329. thread.join();
  4330. ASSERT_FALSE(svr.is_running());
  4331. });
  4332. svr.wait_until_ready();
  4333. Client cli(HOST, PORT);
  4334. auto res = cli.Get("/me");
  4335. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4336. EXPECT_EQ(StatusCode::OK_200, res->status);
  4337. EXPECT_EQ("Hello alice", res->body);
  4338. }
  4339. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  4340. struct RoleCtx {
  4341. std::string role;
  4342. };
  4343. Server svr;
  4344. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  4345. res.user_data.set("role", RoleCtx{"admin"});
  4346. return Server::HandlerResponse::Unhandled;
  4347. });
  4348. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  4349. auto *ctx = res.user_data.get<RoleCtx>("role");
  4350. ASSERT_NE(nullptr, ctx);
  4351. res.set_content(ctx->role, "text/plain");
  4352. });
  4353. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4354. auto se = detail::scope_exit([&] {
  4355. svr.stop();
  4356. thread.join();
  4357. ASSERT_FALSE(svr.is_running());
  4358. });
  4359. svr.wait_until_ready();
  4360. Client cli(HOST, PORT);
  4361. auto res = cli.Get("/role");
  4362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4363. EXPECT_EQ(StatusCode::OK_200, res->status);
  4364. EXPECT_EQ("admin", res->body);
  4365. }
  4366. TEST(InvalidFormatTest, StatusCode) {
  4367. Server svr;
  4368. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4369. res.set_content("Hello World!\n", "text/plain");
  4370. res.status = 9999; // Status should be a three-digit code...
  4371. });
  4372. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4373. auto se = detail::scope_exit([&] {
  4374. svr.stop();
  4375. thread.join();
  4376. ASSERT_FALSE(svr.is_running());
  4377. });
  4378. svr.wait_until_ready();
  4379. {
  4380. Client cli(HOST, PORT);
  4381. auto res = cli.Get("/hi");
  4382. ASSERT_FALSE(res);
  4383. }
  4384. }
  4385. TEST(URLFragmentTest, WithFragment) {
  4386. Server svr;
  4387. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  4388. EXPECT_TRUE(req.target == "/hi");
  4389. });
  4390. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4391. auto se = detail::scope_exit([&] {
  4392. svr.stop();
  4393. thread.join();
  4394. ASSERT_FALSE(svr.is_running());
  4395. });
  4396. svr.wait_until_ready();
  4397. {
  4398. Client cli(HOST, PORT);
  4399. auto res = cli.Get("/hi#key1=val1=key2=val2");
  4400. EXPECT_TRUE(res);
  4401. EXPECT_EQ(StatusCode::OK_200, res->status);
  4402. res = cli.Get("/hi%23key1=val1=key2=val2");
  4403. EXPECT_TRUE(res);
  4404. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4405. }
  4406. }
  4407. TEST(HeaderWriter, SetHeaderWriter) {
  4408. Server svr;
  4409. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  4410. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  4411. return detail::write_headers(strm, hdrs);
  4412. });
  4413. svr.Get("/hi", [](const Request &req, Response &res) {
  4414. auto it = req.headers.find("CustomClientHeader");
  4415. EXPECT_TRUE(it != req.headers.end());
  4416. EXPECT_EQ(it->second, "CustomClientValue");
  4417. res.set_content("Hello World!\n", "text/plain");
  4418. });
  4419. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4420. auto se = detail::scope_exit([&] {
  4421. svr.stop();
  4422. thread.join();
  4423. ASSERT_FALSE(svr.is_running());
  4424. });
  4425. svr.wait_until_ready();
  4426. {
  4427. Client cli(HOST, PORT);
  4428. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  4429. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  4430. return detail::write_headers(strm, hdrs);
  4431. });
  4432. auto res = cli.Get("/hi");
  4433. EXPECT_TRUE(res);
  4434. EXPECT_EQ(StatusCode::OK_200, res->status);
  4435. auto it = res->headers.find("CustomServerHeader");
  4436. EXPECT_TRUE(it != res->headers.end());
  4437. EXPECT_EQ(it->second, "CustomServerValue");
  4438. }
  4439. }
  4440. class ServerTest : public ::testing::Test {
  4441. protected:
  4442. ServerTest()
  4443. : cli_(HOST, PORT)
  4444. #ifdef CPPHTTPLIB_SSL_ENABLED
  4445. ,
  4446. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  4447. #endif
  4448. {
  4449. #ifdef CPPHTTPLIB_SSL_ENABLED
  4450. cli_.enable_server_certificate_verification(false);
  4451. #endif
  4452. // Allow LARGE_DATA (100MB) responses
  4453. cli_.set_payload_max_length(200 * 1024 * 1024);
  4454. }
  4455. virtual void SetUp() {
  4456. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  4457. svr_.set_payload_max_length(200 * 1024 * 1024);
  4458. svr_.set_mount_point("/", "./www");
  4459. svr_.set_mount_point("/mount", "./www2");
  4460. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  4461. svr_.Get("/hi",
  4462. [&](const Request & /*req*/, Response &res) {
  4463. res.set_content("Hello World!", "text/plain");
  4464. })
  4465. .Get("/file_content",
  4466. [&](const Request & /*req*/, Response &res) {
  4467. res.set_file_content("./www/dir/test.html");
  4468. })
  4469. .Get("/file_content_with_content_type",
  4470. [&](const Request & /*req*/, Response &res) {
  4471. res.set_file_content("./www/file", "text/plain");
  4472. })
  4473. .Get("/invalid_file_content",
  4474. [&](const Request & /*req*/, Response &res) {
  4475. res.set_file_content("./www/dir/invalid_file_path");
  4476. })
  4477. .Get("/http_response_splitting",
  4478. [&](const Request & /*req*/, Response &res) {
  4479. res.set_header("a", "1\r\nSet-Cookie: a=1");
  4480. EXPECT_EQ(0U, res.headers.size());
  4481. EXPECT_FALSE(res.has_header("a"));
  4482. res.set_header("a", "1\nSet-Cookie: a=1");
  4483. EXPECT_EQ(0U, res.headers.size());
  4484. EXPECT_FALSE(res.has_header("a"));
  4485. res.set_header("a", "1\rSet-Cookie: a=1");
  4486. EXPECT_EQ(0U, res.headers.size());
  4487. EXPECT_FALSE(res.has_header("a"));
  4488. res.set_header("a\r\nb", "0");
  4489. EXPECT_EQ(0U, res.headers.size());
  4490. EXPECT_FALSE(res.has_header("a"));
  4491. res.set_header("a\rb", "0");
  4492. EXPECT_EQ(0U, res.headers.size());
  4493. EXPECT_FALSE(res.has_header("a"));
  4494. res.set_header("a\nb", "0");
  4495. EXPECT_EQ(0U, res.headers.size());
  4496. EXPECT_FALSE(res.has_header("a"));
  4497. res.set_redirect("1\r\nSet-Cookie: a=1");
  4498. EXPECT_EQ(0U, res.headers.size());
  4499. EXPECT_FALSE(res.has_header("Location"));
  4500. })
  4501. .Get("/slow",
  4502. [&](const Request & /*req*/, Response &res) {
  4503. std::this_thread::sleep_for(std::chrono::seconds(4));
  4504. res.set_content("slow", "text/plain");
  4505. })
  4506. #if 0
  4507. .Post("/slowpost",
  4508. [&](const Request & /*req*/, Response &res) {
  4509. std::this_thread::sleep_for(std::chrono::seconds(2));
  4510. res.set_content("slow", "text/plain");
  4511. })
  4512. #endif
  4513. .Get("/remote_addr",
  4514. [&](const Request &req, Response &res) {
  4515. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  4516. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  4517. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4518. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  4519. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  4520. #endif
  4521. res.set_content(req.remote_addr, "text/plain");
  4522. })
  4523. .Get("/local_addr",
  4524. [&](const Request &req, Response &res) {
  4525. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  4526. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  4527. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4528. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  4529. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  4530. #endif
  4531. auto local_addr = req.local_addr;
  4532. auto local_port = std::to_string(req.local_port);
  4533. res.set_content(local_addr.append(":").append(local_port),
  4534. "text/plain");
  4535. })
  4536. .Get("/endwith%",
  4537. [&](const Request & /*req*/, Response &res) {
  4538. res.set_content("Hello World!", "text/plain");
  4539. })
  4540. .Get("/a\\+\\+b",
  4541. [&](const Request &req, Response &res) {
  4542. ASSERT_TRUE(req.has_param("a +b"));
  4543. auto val = req.get_param_value("a +b");
  4544. res.set_content(val, "text/plain");
  4545. })
  4546. .Get("/", [&](const Request & /*req*/,
  4547. Response &res) { res.set_redirect("/hi"); })
  4548. .Post("/1",
  4549. [](const Request & /*req*/, Response &res) {
  4550. res.set_redirect("/2", StatusCode::SeeOther_303);
  4551. })
  4552. .Get("/2",
  4553. [](const Request & /*req*/, Response &res) {
  4554. res.set_content("redirected.", "text/plain");
  4555. res.status = StatusCode::OK_200;
  4556. })
  4557. .Post("/person",
  4558. [&](const Request &req, Response &res) {
  4559. if (req.has_param("name") && req.has_param("note")) {
  4560. persons_[req.get_param_value("name")] =
  4561. req.get_param_value("note");
  4562. } else {
  4563. res.status = StatusCode::BadRequest_400;
  4564. }
  4565. })
  4566. .Put("/person",
  4567. [&](const Request &req, Response &res) {
  4568. if (req.has_param("name") && req.has_param("note")) {
  4569. persons_[req.get_param_value("name")] =
  4570. req.get_param_value("note");
  4571. } else {
  4572. res.status = StatusCode::BadRequest_400;
  4573. }
  4574. })
  4575. .Get("/person/(.*)",
  4576. [&](const Request &req, Response &res) {
  4577. string name = req.matches[1];
  4578. if (persons_.find(name) != persons_.end()) {
  4579. auto note = persons_[name];
  4580. res.set_content(note, "text/plain");
  4581. } else {
  4582. res.status = StatusCode::NotFound_404;
  4583. }
  4584. })
  4585. .Delete("/person",
  4586. [&](const Request &req, Response &res) {
  4587. if (req.has_param("name")) {
  4588. string name = req.get_param_value("name");
  4589. if (persons_.find(name) != persons_.end()) {
  4590. persons_.erase(name);
  4591. res.set_content("DELETED", "text/plain");
  4592. } else {
  4593. res.status = StatusCode::NotFound_404;
  4594. }
  4595. } else {
  4596. res.status = StatusCode::BadRequest_400;
  4597. }
  4598. })
  4599. .Post("/x-www-form-urlencoded-json",
  4600. [&](const Request &req, Response &res) {
  4601. auto json = req.get_param_value("json");
  4602. ASSERT_EQ(JSON_DATA, json);
  4603. res.set_content(json, "appliation/json");
  4604. res.status = StatusCode::OK_200;
  4605. })
  4606. .Get("/streamed-chunked",
  4607. [&](const Request & /*req*/, Response &res) {
  4608. res.set_chunked_content_provider(
  4609. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  4610. sink.os << "123";
  4611. sink.os << "456";
  4612. sink.os << "789";
  4613. sink.done();
  4614. return true;
  4615. });
  4616. })
  4617. .Get("/streamed-chunked-with-prohibited-trailer",
  4618. [&](const Request & /*req*/, Response &res) {
  4619. auto i = new int(0);
  4620. // Declare both a prohibited trailer (Content-Length) and an
  4621. // allowed one
  4622. res.set_header("Trailer", "Content-Length, X-Allowed");
  4623. res.set_chunked_content_provider(
  4624. "text/plain",
  4625. [i](size_t /*offset*/, DataSink &sink) {
  4626. switch (*i) {
  4627. case 0: sink.os << "123"; break;
  4628. case 1: sink.os << "456"; break;
  4629. case 2: sink.os << "789"; break;
  4630. case 3: {
  4631. sink.done_with_trailer(
  4632. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  4633. } break;
  4634. }
  4635. (*i)++;
  4636. return true;
  4637. },
  4638. [i](bool success) {
  4639. EXPECT_TRUE(success);
  4640. delete i;
  4641. });
  4642. })
  4643. .Get("/streamed-chunked2",
  4644. [&](const Request & /*req*/, Response &res) {
  4645. auto i = new int(0);
  4646. res.set_chunked_content_provider(
  4647. "text/plain",
  4648. [i](size_t /*offset*/, DataSink &sink) {
  4649. switch (*i) {
  4650. case 0: sink.os << "123"; break;
  4651. case 1: sink.os << "456"; break;
  4652. case 2: sink.os << "789"; break;
  4653. case 3: sink.done(); break;
  4654. }
  4655. (*i)++;
  4656. return true;
  4657. },
  4658. [i](bool success) {
  4659. EXPECT_TRUE(success);
  4660. delete i;
  4661. });
  4662. })
  4663. .Get("/streamed-chunked-with-trailer",
  4664. [&](const Request & /*req*/, Response &res) {
  4665. auto i = new int(0);
  4666. res.set_header("Trailer", "Dummy1, Dummy2");
  4667. res.set_chunked_content_provider(
  4668. "text/plain",
  4669. [i](size_t /*offset*/, DataSink &sink) {
  4670. switch (*i) {
  4671. case 0: sink.os << "123"; break;
  4672. case 1: sink.os << "456"; break;
  4673. case 2: sink.os << "789"; break;
  4674. case 3: {
  4675. sink.done_with_trailer(
  4676. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  4677. } break;
  4678. }
  4679. (*i)++;
  4680. return true;
  4681. },
  4682. [i](bool success) {
  4683. EXPECT_TRUE(success);
  4684. delete i;
  4685. });
  4686. })
  4687. .Get("/streamed",
  4688. [&](const Request & /*req*/, Response &res) {
  4689. res.set_content_provider(
  4690. 6, "text/plain",
  4691. [](size_t offset, size_t /*length*/, DataSink &sink) {
  4692. sink.os << (offset < 3 ? "a" : "b");
  4693. return true;
  4694. });
  4695. })
  4696. .Get("/streamed-without-length",
  4697. [&](const Request & /*req*/, Response &res) {
  4698. auto data = new std::string("abcdefg");
  4699. res.set_content_provider(
  4700. "text/plain",
  4701. [data](size_t offset, DataSink &sink) {
  4702. if (offset < data->size()) {
  4703. sink.os << data->substr(offset);
  4704. }
  4705. sink.done();
  4706. return true;
  4707. },
  4708. [data](bool success) {
  4709. EXPECT_TRUE(success);
  4710. delete data;
  4711. });
  4712. })
  4713. .Get("/streamed-with-range",
  4714. [&](const Request &req, Response &res) {
  4715. auto data = new std::string("abcdefg");
  4716. // An explicit status keeps the server from picking the 206 it
  4717. // would otherwise choose for a ranged request, so the response
  4718. // is not a partial representation.
  4719. auto status = req.get_param_value("status");
  4720. if (status == "200") {
  4721. res.status = StatusCode::OK_200;
  4722. } else if (status == "403") {
  4723. res.status = StatusCode::Forbidden_403;
  4724. }
  4725. res.set_content_provider(
  4726. data->size(), "text/plain",
  4727. [data](size_t offset, size_t length, DataSink &sink) {
  4728. size_t DATA_CHUNK_SIZE = 4;
  4729. const auto &d = *data;
  4730. auto out_len =
  4731. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  4732. auto ret =
  4733. sink.write(&d[static_cast<size_t>(offset)], out_len);
  4734. EXPECT_TRUE(ret);
  4735. return true;
  4736. },
  4737. [data, &req](bool success) {
  4738. EXPECT_EQ(success, !req.has_param("error"));
  4739. delete data;
  4740. });
  4741. })
  4742. .Get("/streamed-cancel",
  4743. [&](const Request & /*req*/, Response &res) {
  4744. res.set_content_provider(
  4745. size_t(-1), "text/plain",
  4746. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4747. sink.os << "data_chunk";
  4748. return true;
  4749. });
  4750. })
  4751. .Get("/regex-with-delimiter",
  4752. [&](const Request &req, Response & /*res*/) {
  4753. ASSERT_TRUE(req.has_param("key"));
  4754. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  4755. })
  4756. .Get("/with-range",
  4757. [&](const Request & /*req*/, Response &res) {
  4758. res.set_content("abcdefg", "text/plain");
  4759. })
  4760. .Get("/test-start-time",
  4761. [&](const Request &req, Response & /*res*/) {
  4762. EXPECT_NE(req.start_time_,
  4763. std::chrono::steady_clock::time_point::min());
  4764. })
  4765. .Get("/with-range-customized-response",
  4766. [&](const Request & /*req*/, Response &res) {
  4767. res.status = StatusCode::BadRequest_400;
  4768. res.set_content(JSON_DATA, "application/json");
  4769. })
  4770. .Post("/chunked",
  4771. [&](const Request &req, Response & /*res*/) {
  4772. EXPECT_EQ(req.body, "dechunked post body");
  4773. })
  4774. .Post("/large-chunked",
  4775. [&](const Request &req, Response & /*res*/) {
  4776. std::string expected(6 * 30 * 1024u, 'a');
  4777. EXPECT_EQ(req.body, expected);
  4778. })
  4779. .Post("/multipart",
  4780. [&](const Request &req, Response & /*res*/) {
  4781. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  4782. req.form.get_field_count("text2") +
  4783. req.form.get_field_count("file3") +
  4784. req.form.get_field_count("file4"));
  4785. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  4786. req.form.get_file_count("file2"));
  4787. ASSERT_TRUE(!req.form.has_file("???"));
  4788. ASSERT_TRUE(!req.form.has_field("???"));
  4789. ASSERT_TRUE(req.body.empty());
  4790. {
  4791. const auto &text = req.form.get_field("text1");
  4792. EXPECT_EQ("text default", text);
  4793. }
  4794. {
  4795. const auto &text = req.form.get_field("text2");
  4796. EXPECT_EQ("aωb", text);
  4797. }
  4798. {
  4799. const auto &file = req.form.get_file("file1");
  4800. EXPECT_EQ("hello.txt", file.filename);
  4801. EXPECT_EQ("text/plain", file.content_type);
  4802. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  4803. }
  4804. {
  4805. const auto &file = req.form.get_file("file2");
  4806. EXPECT_EQ("world.json", file.filename);
  4807. EXPECT_EQ("application/json", file.content_type);
  4808. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  4809. }
  4810. {
  4811. const auto &text = req.form.get_field("file3");
  4812. EXPECT_EQ(0u, text.size());
  4813. }
  4814. {
  4815. const auto &text = req.form.get_field("file4");
  4816. EXPECT_EQ(0u, text.size());
  4817. }
  4818. })
  4819. .Post("/multipart/multi_file_values",
  4820. [&](const Request &req, Response & /*res*/) {
  4821. EXPECT_EQ(3u, req.form.get_field_count("text") +
  4822. req.form.get_field_count("multi_text1"));
  4823. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  4824. ASSERT_TRUE(!req.form.has_file("???"));
  4825. ASSERT_TRUE(!req.form.has_field("???"));
  4826. ASSERT_TRUE(req.body.empty());
  4827. {
  4828. const auto &text = req.form.get_field("text");
  4829. EXPECT_EQ("default text", text);
  4830. }
  4831. {
  4832. const auto &text1_values = req.form.get_fields("multi_text1");
  4833. EXPECT_EQ(2u, text1_values.size());
  4834. EXPECT_EQ("aaaaa", text1_values[0]);
  4835. EXPECT_EQ("bbbbb", text1_values[1]);
  4836. }
  4837. {
  4838. const auto &file1_values = req.form.get_files("multi_file1");
  4839. EXPECT_EQ(2u, file1_values.size());
  4840. auto file1 = file1_values[0];
  4841. EXPECT_EQ(file1.filename, "hello.txt");
  4842. EXPECT_EQ(file1.content_type, "text/plain");
  4843. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  4844. auto file2 = file1_values[1];
  4845. EXPECT_EQ(file2.filename, "world.json");
  4846. EXPECT_EQ(file2.content_type, "application/json");
  4847. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  4848. }
  4849. })
  4850. .Post("/empty",
  4851. [&](const Request &req, Response &res) {
  4852. EXPECT_EQ(req.body, "");
  4853. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  4854. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4855. res.set_content("empty", "text/plain");
  4856. })
  4857. .Post("/empty-no-content-type",
  4858. [&](const Request &req, Response &res) {
  4859. EXPECT_EQ(req.body, "");
  4860. EXPECT_FALSE(req.has_header("Content-Type"));
  4861. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4862. res.set_content("empty-no-content-type", "text/plain");
  4863. })
  4864. .Post("/path-only",
  4865. [&](const Request &req, Response &res) {
  4866. EXPECT_EQ(req.body, "");
  4867. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4868. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4869. res.set_content("path-only", "text/plain");
  4870. })
  4871. .Post("/path-headers-only",
  4872. [&](const Request &req, Response &res) {
  4873. EXPECT_EQ(req.body, "");
  4874. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4875. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4876. EXPECT_EQ("world", req.get_header_value("hello"));
  4877. EXPECT_EQ("world2", req.get_header_value("hello2"));
  4878. res.set_content("path-headers-only", "text/plain");
  4879. })
  4880. .Post("/post-large",
  4881. [&](const Request &req, Response &res) {
  4882. EXPECT_EQ(req.body, LARGE_DATA);
  4883. res.set_content(req.body, "text/plain");
  4884. })
  4885. .Post("/post-loopback",
  4886. [&](const Request &, Response &res,
  4887. ContentReader const &content_reader) {
  4888. std::string body;
  4889. content_reader([&](const char *data, size_t data_length) {
  4890. body.append(data, data_length);
  4891. return true;
  4892. });
  4893. res.set_content(body, "text/plain");
  4894. })
  4895. .Put("/put-loopback",
  4896. [&](const Request &, Response &res,
  4897. ContentReader const &content_reader) {
  4898. std::string body;
  4899. content_reader([&](const char *data, size_t data_length) {
  4900. body.append(data, data_length);
  4901. return true;
  4902. });
  4903. res.set_content(body, "text/plain");
  4904. })
  4905. .Patch("/patch-loopback",
  4906. [&](const Request &, Response &res,
  4907. ContentReader const &content_reader) {
  4908. std::string body;
  4909. content_reader([&](const char *data, size_t data_length) {
  4910. body.append(data, data_length);
  4911. return true;
  4912. });
  4913. res.set_content(body, "text/plain");
  4914. })
  4915. .Put("/empty-no-content-type",
  4916. [&](const Request &req, Response &res) {
  4917. EXPECT_EQ(req.body, "");
  4918. EXPECT_FALSE(req.has_header("Content-Type"));
  4919. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4920. res.set_content("empty-no-content-type", "text/plain");
  4921. })
  4922. .Put("/put",
  4923. [&](const Request &req, Response &res) {
  4924. EXPECT_EQ(req.body, "PUT");
  4925. res.set_content(req.body, "text/plain");
  4926. })
  4927. .Put("/put-large",
  4928. [&](const Request &req, Response &res) {
  4929. EXPECT_EQ(req.body, LARGE_DATA);
  4930. res.set_content(req.body, "text/plain");
  4931. })
  4932. .Patch("/patch",
  4933. [&](const Request &req, Response &res) {
  4934. EXPECT_EQ(req.body, "PATCH");
  4935. res.set_content(req.body, "text/plain");
  4936. })
  4937. .Delete("/delete",
  4938. [&](const Request & /*req*/, Response &res) {
  4939. res.set_content("DELETE", "text/plain");
  4940. })
  4941. .Delete("/delete-body",
  4942. [&](const Request &req, Response &res) {
  4943. EXPECT_EQ(req.body, "content");
  4944. res.set_content(req.body, "text/plain");
  4945. })
  4946. .Options(R"(\*)",
  4947. [&](const Request & /*req*/, Response &res) {
  4948. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  4949. })
  4950. .CustomRoute("PROPFIND", "/dav/:id",
  4951. [&](const Request &req, Response &res) {
  4952. res.set_header("x-body-size",
  4953. std::to_string(req.body.size()));
  4954. res.set_header("x-matched-route", req.matched_route);
  4955. res.set_header("x-dav-id", req.path_params.at("id"));
  4956. res.status = StatusCode::MultiStatus_207;
  4957. res.set_content(req.body, "application/xml");
  4958. })
  4959. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  4960. [&](const Request &req, Response &res) {
  4961. res.set_header("x-dav-match", req.matches[1]);
  4962. res.status = StatusCode::MultiStatus_207;
  4963. })
  4964. .CustomRoute("MKCOL", "/dav-mkcol",
  4965. [&](const Request &req, Response &res) {
  4966. EXPECT_TRUE(req.body.empty());
  4967. res.status = StatusCode::Created_201;
  4968. })
  4969. .CustomRoute(
  4970. "REPORT", "/dav-report",
  4971. [&](const Request & /*req*/, Response &res,
  4972. const ContentReader &content_reader) {
  4973. std::string body;
  4974. content_reader([&](const char *data, size_t data_length) {
  4975. body.append(data, data_length);
  4976. return true;
  4977. });
  4978. res.set_header("x-body-size", std::to_string(body.size()));
  4979. res.status = StatusCode::MultiStatus_207;
  4980. res.set_content(body, "application/xml");
  4981. })
  4982. .Get("/request-target",
  4983. [&](const Request &req, Response & /*res*/) {
  4984. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  4985. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  4986. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  4987. })
  4988. .Get("/long-query-value",
  4989. [&](const Request &req, Response & /*res*/) {
  4990. EXPECT_EQ(LONG_QUERY_URL, req.target);
  4991. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  4992. })
  4993. .Get("/too-long-query-value",
  4994. [&](const Request &req, Response & /*res*/) {
  4995. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  4996. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  4997. })
  4998. .Get("/array-param",
  4999. [&](const Request &req, Response & /*res*/) {
  5000. EXPECT_EQ(3u, req.get_param_value_count("array"));
  5001. EXPECT_EQ("value1", req.get_param_value("array", 0));
  5002. EXPECT_EQ("value2", req.get_param_value("array", 1));
  5003. EXPECT_EQ("value3", req.get_param_value("array", 2));
  5004. })
  5005. .Get("/array-param-values",
  5006. [&](const Request &req, Response & /*res*/) {
  5007. auto values = req.get_param_values("array");
  5008. EXPECT_EQ(3u, values.size());
  5009. EXPECT_EQ("value1", values[0]);
  5010. EXPECT_EQ("value2", values[1]);
  5011. EXPECT_EQ("value3", values[2]);
  5012. auto empty = req.get_param_values("nonexistent");
  5013. EXPECT_TRUE(empty.empty());
  5014. })
  5015. .Post("/validate-no-multiple-headers",
  5016. [&](const Request &req, Response & /*res*/) {
  5017. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  5018. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  5019. })
  5020. .Post("/content_receiver",
  5021. [&](const Request &req, Response &res,
  5022. const ContentReader &content_reader) {
  5023. if (req.is_multipart_form_data()) {
  5024. std::vector<FormData> items;
  5025. content_reader(
  5026. [&](const FormData &file) {
  5027. items.push_back(file);
  5028. return true;
  5029. },
  5030. [&](const char *data, size_t data_length) {
  5031. items.back().content.append(data, data_length);
  5032. return true;
  5033. });
  5034. EXPECT_EQ(5u, items.size());
  5035. {
  5036. const auto &file = get_file_value(items, "text1");
  5037. EXPECT_TRUE(file.filename.empty());
  5038. EXPECT_EQ("text default", file.content);
  5039. }
  5040. {
  5041. const auto &file = get_file_value(items, "text2");
  5042. EXPECT_TRUE(file.filename.empty());
  5043. EXPECT_EQ("aωb", file.content);
  5044. }
  5045. {
  5046. const auto &file = get_file_value(items, "file1");
  5047. EXPECT_EQ("hello.txt", file.filename);
  5048. EXPECT_EQ("text/plain", file.content_type);
  5049. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5050. }
  5051. {
  5052. const auto &file = get_file_value(items, "file2");
  5053. EXPECT_EQ("world.json", file.filename);
  5054. EXPECT_EQ("application/json", file.content_type);
  5055. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  5056. }
  5057. {
  5058. const auto &file = get_file_value(items, "file3");
  5059. EXPECT_TRUE(file.filename.empty());
  5060. EXPECT_EQ("application/octet-stream", file.content_type);
  5061. EXPECT_EQ(0u, file.content.size());
  5062. }
  5063. } else {
  5064. std::string body;
  5065. content_reader([&](const char *data, size_t data_length) {
  5066. EXPECT_EQ(7U, data_length);
  5067. body.append(data, data_length);
  5068. return true;
  5069. });
  5070. EXPECT_EQ(body, "content");
  5071. res.set_content(body, "text/plain");
  5072. }
  5073. })
  5074. .Put("/content_receiver",
  5075. [&](const Request & /*req*/, Response &res,
  5076. const ContentReader &content_reader) {
  5077. std::string body;
  5078. content_reader([&](const char *data, size_t data_length) {
  5079. body.append(data, data_length);
  5080. return true;
  5081. });
  5082. EXPECT_EQ(body, "content");
  5083. res.set_content(body, "text/plain");
  5084. })
  5085. .Patch("/content_receiver",
  5086. [&](const Request & /*req*/, Response &res,
  5087. const ContentReader &content_reader) {
  5088. std::string body;
  5089. content_reader([&](const char *data, size_t data_length) {
  5090. body.append(data, data_length);
  5091. return true;
  5092. });
  5093. EXPECT_EQ(body, "content");
  5094. res.set_content(body, "text/plain");
  5095. })
  5096. .Post("/query-string-and-body",
  5097. [&](const Request &req, Response & /*res*/) {
  5098. ASSERT_TRUE(req.has_param("key"));
  5099. EXPECT_EQ(req.get_param_value("key"), "value");
  5100. EXPECT_EQ(req.body, "content");
  5101. })
  5102. .Get("/last-request",
  5103. [&](const Request &req, Response & /*res*/) {
  5104. EXPECT_EQ("close", req.get_header_value("Connection"));
  5105. })
  5106. .Get(R"(/redirect/(\d+))",
  5107. [&](const Request &req, Response &res) {
  5108. auto num = std::stoi(req.matches[1]) + 1;
  5109. std::string url = "/redirect/" + std::to_string(num);
  5110. res.set_redirect(url);
  5111. })
  5112. .Post("/binary",
  5113. [&](const Request &req, Response &res) {
  5114. EXPECT_EQ(4U, req.body.size());
  5115. EXPECT_EQ("application/octet-stream",
  5116. req.get_header_value("Content-Type"));
  5117. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5118. res.set_content(req.body, "application/octet-stream");
  5119. })
  5120. .Put("/binary",
  5121. [&](const Request &req, Response &res) {
  5122. EXPECT_EQ(4U, req.body.size());
  5123. EXPECT_EQ("application/octet-stream",
  5124. req.get_header_value("Content-Type"));
  5125. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5126. res.set_content(req.body, "application/octet-stream");
  5127. })
  5128. .Patch("/binary",
  5129. [&](const Request &req, Response &res) {
  5130. EXPECT_EQ(4U, req.body.size());
  5131. EXPECT_EQ("application/octet-stream",
  5132. req.get_header_value("Content-Type"));
  5133. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5134. res.set_content(req.body, "application/octet-stream");
  5135. })
  5136. .Delete("/binary",
  5137. [&](const Request &req, Response &res) {
  5138. EXPECT_EQ(4U, req.body.size());
  5139. EXPECT_EQ("application/octet-stream",
  5140. req.get_header_value("Content-Type"));
  5141. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5142. res.set_content(req.body, "application/octet-stream");
  5143. })
  5144. .Get("/issue1772",
  5145. [&](const Request & /*req*/, Response &res) {
  5146. res.status = 401;
  5147. res.set_header("WWW-Authenticate", "Basic realm=123456");
  5148. })
  5149. .Delete("/issue609",
  5150. [](const httplib::Request &, httplib::Response &res,
  5151. const httplib::ContentReader &) {
  5152. res.set_content("ok", "text/plain");
  5153. })
  5154. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  5155. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5156. .Get("/compress",
  5157. [&](const Request & /*req*/, Response &res) {
  5158. res.set_content(
  5159. "12345678901234567890123456789012345678901234567890123456789"
  5160. "01234567890123456789012345678901234567890",
  5161. "text/plain");
  5162. })
  5163. .Get("/compress-with-charset",
  5164. [&](const Request & /*req*/, Response &res) {
  5165. res.set_content(
  5166. "12345678901234567890123456789012345678901234567890123456789"
  5167. "01234567890123456789012345678901234567890",
  5168. "application/json; charset=utf-8");
  5169. })
  5170. .Get("/nocompress",
  5171. [&](const Request & /*req*/, Response &res) {
  5172. res.set_content(
  5173. "12345678901234567890123456789012345678901234567890123456789"
  5174. "01234567890123456789012345678901234567890",
  5175. "application/octet-stream");
  5176. })
  5177. .Post("/compress-multipart",
  5178. [&](const Request &req, Response & /*res*/) {
  5179. EXPECT_EQ(2u, req.form.fields.size());
  5180. ASSERT_TRUE(!req.form.has_field("???"));
  5181. {
  5182. const auto &text = req.form.get_field("key1");
  5183. EXPECT_EQ("test", text);
  5184. }
  5185. {
  5186. const auto &text = req.form.get_field("key2");
  5187. EXPECT_EQ("--abcdefg123", text);
  5188. }
  5189. })
  5190. #endif
  5191. ;
  5192. persons_["john"] = "programmer";
  5193. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  5194. svr_.wait_until_ready();
  5195. }
  5196. virtual void TearDown() {
  5197. svr_.stop();
  5198. if (!request_threads_.empty()) {
  5199. std::this_thread::sleep_for(std::chrono::seconds(1));
  5200. for (auto &t : request_threads_) {
  5201. t.join();
  5202. }
  5203. }
  5204. t_.join();
  5205. }
  5206. map<string, string> persons_;
  5207. #ifdef CPPHTTPLIB_SSL_ENABLED
  5208. SSLClient cli_;
  5209. SSLServer svr_;
  5210. #else
  5211. Client cli_;
  5212. Server svr_;
  5213. #endif
  5214. thread t_;
  5215. std::vector<thread> request_threads_;
  5216. };
  5217. TEST_F(ServerTest, GetMethod200) {
  5218. auto res = cli_.Get("/hi");
  5219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5220. EXPECT_EQ("HTTP/1.1", res->version);
  5221. EXPECT_EQ(StatusCode::OK_200, res->status);
  5222. EXPECT_EQ("OK", res->reason);
  5223. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5224. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5225. EXPECT_EQ("Hello World!", res->body);
  5226. }
  5227. TEST_F(ServerTest, GetEmptyFile) {
  5228. auto res = cli_.Get("/empty_file");
  5229. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5230. EXPECT_EQ(StatusCode::OK_200, res->status);
  5231. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5232. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  5233. EXPECT_EQ("", res->body);
  5234. }
  5235. TEST_F(ServerTest, GetFileContent) {
  5236. auto res = cli_.Get("/file_content");
  5237. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5238. EXPECT_EQ(StatusCode::OK_200, res->status);
  5239. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5240. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  5241. EXPECT_EQ("test.html", res->body);
  5242. }
  5243. TEST_F(ServerTest, GetFileContentWithRange) {
  5244. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  5245. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5246. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5247. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5248. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  5249. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  5250. EXPECT_EQ("est", res->body);
  5251. }
  5252. TEST_F(ServerTest, GetFileContentWithContentType) {
  5253. auto res = cli_.Get("/file_content_with_content_type");
  5254. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5255. EXPECT_EQ(StatusCode::OK_200, res->status);
  5256. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5257. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  5258. EXPECT_EQ("file\n", res->body);
  5259. }
  5260. TEST_F(ServerTest, GetInvalidFileContent) {
  5261. auto res = cli_.Get("/invalid_file_content");
  5262. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5263. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5264. }
  5265. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  5266. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  5267. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5268. EXPECT_EQ("HTTP/1.1", res->version);
  5269. EXPECT_EQ(StatusCode::OK_200, res->status);
  5270. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5271. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5272. EXPECT_EQ("Hello World!", res->body);
  5273. }
  5274. TEST_F(ServerTest, GetMethod302) {
  5275. auto res = cli_.Get("/");
  5276. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5277. EXPECT_EQ(StatusCode::Found_302, res->status);
  5278. EXPECT_EQ("/hi", res->get_header_value("Location"));
  5279. }
  5280. TEST_F(ServerTest, GetMethod302Redirect) {
  5281. cli_.set_follow_location(true);
  5282. auto res = cli_.Get("/");
  5283. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5284. EXPECT_EQ(StatusCode::OK_200, res->status);
  5285. EXPECT_EQ("Hello World!", res->body);
  5286. EXPECT_EQ("/hi", res->location);
  5287. }
  5288. TEST_F(ServerTest, GetMethod404) {
  5289. auto res = cli_.Get("/invalid");
  5290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5291. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5292. }
  5293. TEST_F(ServerTest, HeadMethod200) {
  5294. auto res = cli_.Head("/hi");
  5295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5296. EXPECT_EQ(StatusCode::OK_200, res->status);
  5297. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5298. EXPECT_TRUE(res->body.empty());
  5299. }
  5300. TEST_F(ServerTest, HeadMethod200Static) {
  5301. auto res = cli_.Head("/mount/dir/index.html");
  5302. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5303. EXPECT_EQ(StatusCode::OK_200, res->status);
  5304. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5305. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  5306. EXPECT_TRUE(res->body.empty());
  5307. }
  5308. TEST_F(ServerTest, HeadMethod404) {
  5309. auto res = cli_.Head("/invalid");
  5310. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5311. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5312. EXPECT_TRUE(res->body.empty());
  5313. }
  5314. TEST_F(ServerTest, GetMethodPersonJohn) {
  5315. auto res = cli_.Get("/person/john");
  5316. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5317. EXPECT_EQ(StatusCode::OK_200, res->status);
  5318. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5319. EXPECT_EQ("programmer", res->body);
  5320. }
  5321. TEST_F(ServerTest, PostMethod1) {
  5322. auto res = cli_.Get("/person/john1");
  5323. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5324. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5325. res = cli_.Post("/person", "name=john1&note=coder",
  5326. "application/x-www-form-urlencoded");
  5327. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5328. ASSERT_EQ(StatusCode::OK_200, res->status);
  5329. res = cli_.Get("/person/john1");
  5330. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5331. ASSERT_EQ(StatusCode::OK_200, res->status);
  5332. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5333. ASSERT_EQ("coder", res->body);
  5334. }
  5335. TEST_F(ServerTest, PostMethod2) {
  5336. auto res = cli_.Get("/person/john2");
  5337. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5338. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5339. Params params;
  5340. params.emplace("name", "john2");
  5341. params.emplace("note", "coder");
  5342. res = cli_.Post("/person", params);
  5343. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5344. ASSERT_EQ(StatusCode::OK_200, res->status);
  5345. res = cli_.Get("/person/john2");
  5346. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5347. ASSERT_EQ(StatusCode::OK_200, res->status);
  5348. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5349. ASSERT_EQ("coder", res->body);
  5350. }
  5351. TEST_F(ServerTest, PutMethod3) {
  5352. auto res = cli_.Get("/person/john3");
  5353. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5354. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5355. Params params;
  5356. params.emplace("name", "john3");
  5357. params.emplace("note", "coder");
  5358. res = cli_.Put("/person", params);
  5359. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5360. ASSERT_EQ(StatusCode::OK_200, res->status);
  5361. res = cli_.Get("/person/john3");
  5362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5363. ASSERT_EQ(StatusCode::OK_200, res->status);
  5364. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5365. ASSERT_EQ("coder", res->body);
  5366. }
  5367. TEST_F(ServerTest, DeleteMethod1) {
  5368. auto res = cli_.Get("/person/john4");
  5369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5370. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5371. Params params;
  5372. params.emplace("name", "john4");
  5373. params.emplace("note", "coder");
  5374. res = cli_.Post("/person", params);
  5375. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5376. ASSERT_EQ(StatusCode::OK_200, res->status);
  5377. res = cli_.Get("/person/john4");
  5378. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5379. ASSERT_EQ(StatusCode::OK_200, res->status);
  5380. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5381. ASSERT_EQ("coder", res->body);
  5382. Params delete_params;
  5383. delete_params.emplace("name", "john4");
  5384. res = cli_.Delete("/person", delete_params);
  5385. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5386. ASSERT_EQ(StatusCode::OK_200, res->status);
  5387. ASSERT_EQ("DELETED", res->body);
  5388. res = cli_.Get("/person/john4");
  5389. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5390. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5391. }
  5392. TEST_F(ServerTest, DeleteMethod2) {
  5393. auto res = cli_.Get("/person/john5");
  5394. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5395. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5396. Params params;
  5397. params.emplace("name", "john5");
  5398. params.emplace("note", "developer");
  5399. res = cli_.Post("/person", params);
  5400. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5401. ASSERT_EQ(StatusCode::OK_200, res->status);
  5402. res = cli_.Get("/person/john5");
  5403. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5404. ASSERT_EQ(StatusCode::OK_200, res->status);
  5405. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5406. ASSERT_EQ("developer", res->body);
  5407. Params delete_params;
  5408. delete_params.emplace("name", "john5");
  5409. Headers headers;
  5410. headers.emplace("Custom-Header", "test-value");
  5411. res = cli_.Delete("/person", headers, delete_params);
  5412. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5413. ASSERT_EQ(StatusCode::OK_200, res->status);
  5414. ASSERT_EQ("DELETED", res->body);
  5415. res = cli_.Get("/person/john5");
  5416. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5417. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5418. }
  5419. TEST_F(ServerTest, DeleteMethod3) {
  5420. auto res = cli_.Get("/person/john6");
  5421. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5422. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5423. Params params;
  5424. params.emplace("name", "john6");
  5425. params.emplace("note", "tester");
  5426. res = cli_.Post("/person", params);
  5427. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5428. ASSERT_EQ(StatusCode::OK_200, res->status);
  5429. res = cli_.Get("/person/john6");
  5430. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5431. ASSERT_EQ(StatusCode::OK_200, res->status);
  5432. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5433. ASSERT_EQ("tester", res->body);
  5434. Params delete_params;
  5435. delete_params.emplace("name", "john6");
  5436. Headers headers;
  5437. headers.emplace("Custom-Header", "test-value");
  5438. res = cli_.Delete("/person", headers, delete_params, nullptr);
  5439. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5440. ASSERT_EQ(StatusCode::OK_200, res->status);
  5441. ASSERT_EQ("DELETED", res->body);
  5442. res = cli_.Get("/person/john6");
  5443. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5444. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5445. }
  5446. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  5447. Params params;
  5448. params.emplace("json", JSON_DATA);
  5449. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  5450. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5451. ASSERT_EQ(StatusCode::OK_200, res->status);
  5452. ASSERT_EQ(JSON_DATA, res->body);
  5453. }
  5454. TEST_F(ServerTest, PostEmptyContent) {
  5455. auto res = cli_.Post("/empty", "", "text/plain");
  5456. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5457. ASSERT_EQ(StatusCode::OK_200, res->status);
  5458. ASSERT_EQ("empty", res->body);
  5459. }
  5460. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  5461. auto res = cli_.Post("/empty-no-content-type");
  5462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5463. ASSERT_EQ(StatusCode::OK_200, res->status);
  5464. ASSERT_EQ("empty-no-content-type", res->body);
  5465. }
  5466. TEST_F(ServerTest, PostPathOnly) {
  5467. auto res = cli_.Post("/path-only");
  5468. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5469. ASSERT_EQ(StatusCode::OK_200, res->status);
  5470. ASSERT_EQ("path-only", res->body);
  5471. }
  5472. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  5473. auto res = cli_.Post("/path-headers-only",
  5474. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  5475. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5476. ASSERT_EQ(StatusCode::OK_200, res->status);
  5477. ASSERT_EQ("path-headers-only", res->body);
  5478. }
  5479. TEST_F(ServerTest, PostLarge) {
  5480. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  5481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5482. ASSERT_EQ(StatusCode::OK_200, res->status);
  5483. EXPECT_EQ(LARGE_DATA, res->body);
  5484. }
  5485. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  5486. auto res = cli_.Put("/empty-no-content-type");
  5487. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5488. ASSERT_EQ(StatusCode::OK_200, res->status);
  5489. ASSERT_EQ("empty-no-content-type", res->body);
  5490. }
  5491. TEST_F(ServerTest, GetMethodDir) {
  5492. auto res = cli_.Get("/dir/");
  5493. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5494. EXPECT_EQ(StatusCode::OK_200, res->status);
  5495. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5496. auto body = R"(<html>
  5497. <head>
  5498. </head>
  5499. <body>
  5500. <a href="/dir/test.html">Test</a>
  5501. <a href="/hi">hi</a>
  5502. </body>
  5503. </html>
  5504. )";
  5505. EXPECT_EQ(body, res->body);
  5506. }
  5507. TEST_F(ServerTest, GetMethodDirTest) {
  5508. auto res = cli_.Get("/dir/test.html");
  5509. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5510. EXPECT_EQ(StatusCode::OK_200, res->status);
  5511. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5512. EXPECT_EQ("test.html", res->body);
  5513. }
  5514. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  5515. auto res = cli_.Get("/dir/../dir/test.html");
  5516. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5517. EXPECT_EQ(StatusCode::OK_200, res->status);
  5518. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5519. EXPECT_EQ("test.html", res->body);
  5520. }
  5521. TEST_F(ServerTest, GetMethodInvalidPath) {
  5522. auto res = cli_.Get("/dir/../test.html");
  5523. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5524. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5525. }
  5526. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  5527. auto res = cli_.Get("/../www/dir/test.html");
  5528. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5529. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5530. }
  5531. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  5532. auto res = cli_.Get("/dir/../../www/dir/test.html");
  5533. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5534. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5535. }
  5536. TEST_F(ServerTest, GetMethodDirMountTest) {
  5537. auto res = cli_.Get("/mount/dir/test.html");
  5538. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5539. EXPECT_EQ(StatusCode::OK_200, res->status);
  5540. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5541. EXPECT_EQ("test.html", res->body);
  5542. }
  5543. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  5544. auto res = cli_.Get("/mount/dir/../dir/test.html");
  5545. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5546. EXPECT_EQ(StatusCode::OK_200, res->status);
  5547. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5548. EXPECT_EQ("test.html", res->body);
  5549. }
  5550. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  5551. auto res = cli_.Get("/mount/dir/../test.html");
  5552. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5553. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5554. }
  5555. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  5556. auto res = cli_.Get("/mount/dir/test.html%00.js");
  5557. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5558. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5559. }
  5560. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  5561. auto res = cli_.Get("/mount/../www2/dir/test.html");
  5562. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5563. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5564. }
  5565. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  5566. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  5567. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5568. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5569. }
  5570. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  5571. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  5572. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5573. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5574. }
  5575. TEST_F(ServerTest, PostMethod303) {
  5576. auto res = cli_.Post("/1", "body", "text/plain");
  5577. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5578. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  5579. EXPECT_EQ("/2", res->get_header_value("Location"));
  5580. }
  5581. TEST_F(ServerTest, PostMethod303Redirect) {
  5582. cli_.set_follow_location(true);
  5583. auto res = cli_.Post("/1", "body", "text/plain");
  5584. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5585. EXPECT_EQ(StatusCode::OK_200, res->status);
  5586. EXPECT_EQ("redirected.", res->body);
  5587. EXPECT_EQ("/2", res->location);
  5588. }
  5589. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  5590. auto res = cli_.Get("/dir/test.abcde");
  5591. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5592. EXPECT_EQ(StatusCode::OK_200, res->status);
  5593. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5594. EXPECT_EQ("abcde", res->body);
  5595. }
  5596. TEST_F(ServerTest, StaticFileRange) {
  5597. auto res =
  5598. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  5599. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5600. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5601. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5602. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5603. EXPECT_EQ(true, res->has_header("Content-Range"));
  5604. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5605. EXPECT_EQ(std::string("cd"), res->body);
  5606. }
  5607. TEST_F(ServerTest, StaticFileRanges) {
  5608. auto res = cli_.Get("/dir/test.abcde",
  5609. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  5610. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5611. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5612. EXPECT_TRUE(
  5613. res->get_header_value("Content-Type")
  5614. .find(
  5615. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  5616. 0);
  5617. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  5618. }
  5619. TEST_F(ServerTest, StaticFileRangeHead) {
  5620. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  5621. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5622. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5623. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5624. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5625. EXPECT_EQ(true, res->has_header("Content-Range"));
  5626. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5627. }
  5628. TEST_F(ServerTest, StaticFileRangeBigFile) {
  5629. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  5630. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5631. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5632. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5633. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  5634. EXPECT_EQ(true, res->has_header("Content-Range"));
  5635. EXPECT_EQ("bytes 1048571-1048575/1048576",
  5636. res->get_header_value("Content-Range"));
  5637. EXPECT_EQ("LAST\n", res->body);
  5638. }
  5639. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  5640. auto res =
  5641. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  5642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5643. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5644. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5645. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  5646. EXPECT_EQ(true, res->has_header("Content-Range"));
  5647. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  5648. }
  5649. TEST_F(ServerTest, StaticFileBigFile) {
  5650. auto res = cli_.Get("/dir/1MB.txt");
  5651. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5652. EXPECT_EQ(StatusCode::OK_200, res->status);
  5653. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5654. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  5655. }
  5656. TEST_F(ServerTest, InvalidBaseDirMount) {
  5657. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  5658. }
  5659. TEST_F(ServerTest, Binary) {
  5660. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  5661. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  5662. "application/octet-stream");
  5663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5664. ASSERT_EQ(StatusCode::OK_200, res->status);
  5665. ASSERT_EQ(4U, res->body.size());
  5666. res = cli_.Put("/binary", binary.data(), binary.size(),
  5667. "application/octet-stream");
  5668. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5669. ASSERT_EQ(StatusCode::OK_200, res->status);
  5670. ASSERT_EQ(4U, res->body.size());
  5671. res = cli_.Patch("/binary", binary.data(), binary.size(),
  5672. "application/octet-stream");
  5673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5674. ASSERT_EQ(StatusCode::OK_200, res->status);
  5675. ASSERT_EQ(4U, res->body.size());
  5676. res = cli_.Delete("/binary", binary.data(), binary.size(),
  5677. "application/octet-stream");
  5678. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5679. ASSERT_EQ(StatusCode::OK_200, res->status);
  5680. ASSERT_EQ(4U, res->body.size());
  5681. }
  5682. TEST_F(ServerTest, BinaryString) {
  5683. auto binary = std::string("\x00\x01\x02\x03", 4);
  5684. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  5685. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5686. ASSERT_EQ(StatusCode::OK_200, res->status);
  5687. ASSERT_EQ(4U, res->body.size());
  5688. res = cli_.Put("/binary", binary, "application/octet-stream");
  5689. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5690. ASSERT_EQ(StatusCode::OK_200, res->status);
  5691. ASSERT_EQ(4U, res->body.size());
  5692. res = cli_.Patch("/binary", binary, "application/octet-stream");
  5693. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5694. ASSERT_EQ(StatusCode::OK_200, res->status);
  5695. ASSERT_EQ(4U, res->body.size());
  5696. res = cli_.Delete("/binary", binary, "application/octet-stream");
  5697. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5698. ASSERT_EQ(StatusCode::OK_200, res->status);
  5699. ASSERT_EQ(4U, res->body.size());
  5700. }
  5701. TEST_F(ServerTest, EmptyRequest) {
  5702. auto res = cli_.Get("");
  5703. ASSERT_TRUE(!res);
  5704. EXPECT_EQ(Error::Connection, res.error());
  5705. }
  5706. TEST_F(ServerTest, LongRequest) {
  5707. std::string request;
  5708. for (size_t i = 0; i < 545; i++) {
  5709. request += "/TooLongRequest";
  5710. }
  5711. request += "OK";
  5712. auto res = cli_.Get(request.c_str());
  5713. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5714. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5715. }
  5716. TEST_F(ServerTest, TooLongRequest) {
  5717. std::string request;
  5718. for (size_t i = 0; i < 546; i++) {
  5719. request += "/TooLongRequest";
  5720. }
  5721. request += "_NG";
  5722. auto start = std::chrono::high_resolution_clock::now();
  5723. cli_.set_keep_alive(true);
  5724. auto res = cli_.Get(request.c_str());
  5725. auto end = std::chrono::high_resolution_clock::now();
  5726. auto elapsed =
  5727. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5728. .count();
  5729. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5730. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5731. EXPECT_LE(elapsed, 1000);
  5732. EXPECT_EQ("close", res->get_header_value("Connection"));
  5733. EXPECT_FALSE(cli_.is_socket_open());
  5734. }
  5735. TEST_F(ServerTest, AlmostTooLongRequest) {
  5736. // test for #2046 - URI length check shouldn't include other content on req
  5737. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  5738. // leading /, space, HTTP/1.1)
  5739. std::string request =
  5740. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  5741. auto res = cli_.Get(request.c_str());
  5742. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5743. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5744. }
  5745. TEST_F(ServerTest, LongHeader) {
  5746. Request req;
  5747. req.method = "GET";
  5748. req.path = "/hi";
  5749. std::string host_and_port;
  5750. host_and_port += HOST;
  5751. host_and_port += ":";
  5752. host_and_port += std::to_string(PORT);
  5753. req.headers.emplace("Host", host_and_port.c_str());
  5754. req.headers.emplace("Accept", "*/*");
  5755. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5756. req.headers.emplace(
  5757. "Header-Name",
  5758. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5759. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5760. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5761. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5762. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5763. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5764. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5765. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5766. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5767. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5768. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5769. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5770. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5771. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5772. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5773. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5774. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5775. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5776. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5777. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5778. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5779. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5780. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5781. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5782. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5783. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5784. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5785. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5786. "@@@@@@@@@@@@@@@@");
  5787. auto res = std::make_shared<Response>();
  5788. auto error = Error::Success;
  5789. auto ret = cli_.send(req, *res, error);
  5790. ASSERT_TRUE(ret);
  5791. EXPECT_EQ(StatusCode::OK_200, res->status);
  5792. }
  5793. TEST_F(ServerTest, LongQueryValue) {
  5794. auto start = std::chrono::high_resolution_clock::now();
  5795. cli_.set_keep_alive(true);
  5796. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  5797. auto end = std::chrono::high_resolution_clock::now();
  5798. auto elapsed =
  5799. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5800. .count();
  5801. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5802. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5803. EXPECT_LE(elapsed, 1000);
  5804. EXPECT_EQ("close", res->get_header_value("Connection"));
  5805. EXPECT_FALSE(cli_.is_socket_open());
  5806. }
  5807. TEST_F(ServerTest, TooLongQueryValue) {
  5808. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  5809. ASSERT_FALSE(res);
  5810. EXPECT_EQ(Error::Read, res.error());
  5811. }
  5812. TEST_F(ServerTest, TooLongHeader) {
  5813. Request req;
  5814. req.method = "GET";
  5815. req.path = "/hi";
  5816. std::string host_and_port;
  5817. host_and_port += HOST;
  5818. host_and_port += ":";
  5819. host_and_port += std::to_string(PORT);
  5820. req.headers.emplace("Host", host_and_port.c_str());
  5821. req.headers.emplace("Accept", "*/*");
  5822. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5823. req.headers.emplace(
  5824. "Header-Name",
  5825. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5826. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5827. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5828. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5829. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5830. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5831. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5832. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5833. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5834. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5835. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5836. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5837. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5838. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5839. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5840. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5841. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5842. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5843. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5844. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5845. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5846. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5847. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5848. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5849. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5850. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5851. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5852. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5853. "@@@@@@@@@@@@@@@@@");
  5854. auto res = std::make_shared<Response>();
  5855. auto error = Error::Success;
  5856. auto ret = cli_.send(req, *res, error);
  5857. ASSERT_TRUE(ret);
  5858. EXPECT_EQ(StatusCode::OK_200, res->status);
  5859. }
  5860. TEST_F(ServerTest, HeaderCountAtLimit) {
  5861. // Test with headers just under the 100 limit
  5862. httplib::Headers headers;
  5863. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  5864. // This should keep us just under the 100 header limit
  5865. for (int i = 0; i < 95; i++) {
  5866. std::string name = "X-Test-Header-" + std::to_string(i);
  5867. std::string value = "value" + std::to_string(i);
  5868. headers.emplace(name, value);
  5869. }
  5870. // This should work fine as we're under the limit
  5871. auto res = cli_.Get("/hi", headers);
  5872. EXPECT_TRUE(res);
  5873. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  5874. }
  5875. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  5876. // Test with many headers to exceed the 100 limit
  5877. httplib::Headers headers;
  5878. // Add 150 headers to definitely exceed the 100 limit
  5879. for (int i = 0; i < 150; i++) {
  5880. std::string name = "X-Test-Header-" + std::to_string(i);
  5881. std::string value = "value" + std::to_string(i);
  5882. headers.emplace(name, value);
  5883. }
  5884. // This should fail due to exceeding header count limit
  5885. cli_.set_keep_alive(true);
  5886. auto res = cli_.Get("/hi", headers);
  5887. // The server should respond with 400 Bad Request
  5888. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5889. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5890. EXPECT_EQ("close", res->get_header_value("Connection"));
  5891. EXPECT_FALSE(cli_.is_socket_open());
  5892. }
  5893. TEST_F(ServerTest, PercentEncoding) {
  5894. auto res = cli_.Get("/e%6edwith%");
  5895. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5896. EXPECT_EQ(StatusCode::OK_200, res->status);
  5897. }
  5898. TEST_F(ServerTest, PercentEncodingUnicode) {
  5899. auto res = cli_.Get("/e%u006edwith%");
  5900. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5901. EXPECT_EQ(StatusCode::OK_200, res->status);
  5902. }
  5903. TEST_F(ServerTest, InvalidPercentEncoding) {
  5904. auto res = cli_.Get("/%endwith%");
  5905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5906. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5907. }
  5908. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  5909. auto res = cli_.Get("/%uendwith%");
  5910. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5911. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5912. }
  5913. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  5914. auto res = cli_.Get("/hello?aaa=bbb%");
  5915. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5916. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5917. }
  5918. TEST_F(ServerTest, PlusSignEncoding) {
  5919. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  5920. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5921. EXPECT_EQ(StatusCode::OK_200, res->status);
  5922. EXPECT_EQ("a +b", res->body);
  5923. }
  5924. TEST_F(ServerTest, HeaderCountSecurityTest) {
  5925. // This test simulates a potential DoS attack using many headers
  5926. // to verify our security fix prevents memory exhaustion
  5927. httplib::Headers attack_headers;
  5928. // Attempt to add many headers like an attacker would (200 headers to far
  5929. // exceed limit)
  5930. for (int i = 0; i < 200; i++) {
  5931. std::string name = "X-Attack-Header-" + std::to_string(i);
  5932. std::string value = "attack_payload_" + std::to_string(i);
  5933. attack_headers.emplace(name, value);
  5934. }
  5935. // Try to POST with excessive headers
  5936. cli_.set_keep_alive(true);
  5937. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  5938. // Should either fail or return 400 Bad Request due to security limit
  5939. if (res) {
  5940. // If we get a response, it should be 400 Bad Request
  5941. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5942. EXPECT_EQ("close", res->get_header_value("Connection"));
  5943. }
  5944. EXPECT_FALSE(cli_.is_socket_open());
  5945. }
  5946. TEST_F(ServerTest, MultipartFormData) {
  5947. UploadFormDataItems items = {
  5948. {"text1", "text default", "", ""},
  5949. {"text2", "aωb", "", ""},
  5950. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5951. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  5952. {"file3", "", "", "application/octet-stream"},
  5953. {"file4", "", "", " application/json tmp-string "}};
  5954. auto res = cli_.Post("/multipart", items);
  5955. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5956. EXPECT_EQ(StatusCode::OK_200, res->status);
  5957. }
  5958. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  5959. UploadFormDataItems items = {
  5960. {"text", "default text", "", ""},
  5961. {"multi_text1", "aaaaa", "", ""},
  5962. {"multi_text1", "bbbbb", "", ""},
  5963. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5964. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  5965. "application/json"},
  5966. };
  5967. auto res = cli_.Post("/multipart/multi_file_values", items);
  5968. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5969. EXPECT_EQ(StatusCode::OK_200, res->status);
  5970. }
  5971. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  5972. auto res = cli_.Get("/hi");
  5973. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5974. EXPECT_EQ(StatusCode::OK_200, res->status);
  5975. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  5976. EXPECT_EQ("Hello World!", res->body);
  5977. }
  5978. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  5979. Request req;
  5980. req.method = "POST";
  5981. req.path = "/chunked";
  5982. std::string host_and_port;
  5983. host_and_port += HOST;
  5984. host_and_port += ":";
  5985. host_and_port += std::to_string(PORT);
  5986. req.headers.emplace("Host", host_and_port.c_str());
  5987. req.headers.emplace("Accept", "*/*");
  5988. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5989. req.headers.emplace("Content-Type", "text/plain");
  5990. req.headers.emplace("Content-Length", "0");
  5991. req.headers.emplace(
  5992. "Transfer-Encoding",
  5993. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  5994. // Client does not chunk, so make a chunked body manually.
  5995. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  5996. auto res = std::make_shared<Response>();
  5997. auto error = Error::Success;
  5998. auto ret = cli_.send(req, *res, error);
  5999. ASSERT_TRUE(ret);
  6000. EXPECT_EQ(StatusCode::OK_200, res->status);
  6001. }
  6002. template <typename ClientT>
  6003. static void expect_chunked_body_status(ClientT &cli, const char *body,
  6004. int expected_status) {
  6005. Request req;
  6006. req.method = "POST";
  6007. req.path = "/chunked";
  6008. std::string host_and_port;
  6009. host_and_port += HOST;
  6010. host_and_port += ":";
  6011. host_and_port += std::to_string(PORT);
  6012. req.headers.emplace("Host", host_and_port.c_str());
  6013. req.headers.emplace("Content-Length", "0");
  6014. req.headers.emplace("Transfer-Encoding", "chunked");
  6015. req.body = body;
  6016. auto res = std::make_shared<Response>();
  6017. auto error = Error::Success;
  6018. ASSERT_TRUE(cli.send(req, *res, error));
  6019. EXPECT_EQ(expected_status, res->status);
  6020. }
  6021. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  6022. // rather than treat them as valid lengths.
  6023. template <typename ClientT>
  6024. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  6025. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  6026. }
  6027. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  6028. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  6029. }
  6030. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  6031. expect_chunked_body_rejected(
  6032. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6033. }
  6034. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  6035. // chunk-size line carries no CR, LF or other control character ahead of its
  6036. // terminator. Such a line must be refused rather than read as extension text.
  6037. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  6038. expect_chunked_body_rejected(
  6039. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6040. }
  6041. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  6042. expect_chunked_body_rejected(
  6043. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6044. }
  6045. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  6046. expect_chunked_body_rejected(
  6047. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6048. }
  6049. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  6050. // The literal stays split: a hex escape consumes every hex digit that
  6051. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  6052. expect_chunked_body_rejected(
  6053. cli_, "4;a\x01"
  6054. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6055. }
  6056. TEST_F(ServerTest, AcceptsChunkExtension) {
  6057. expect_chunked_body_status(cli_,
  6058. "4;name=value\r\ndech\r\n"
  6059. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  6060. "0;last\r\n\r\n",
  6061. StatusCode::OK_200);
  6062. }
  6063. TEST_F(ServerTest, GetStreamed2) {
  6064. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  6065. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6066. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6067. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6068. EXPECT_EQ(true, res->has_header("Content-Range"));
  6069. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  6070. EXPECT_EQ(std::string("ab"), res->body);
  6071. }
  6072. TEST_F(ServerTest, GetStreamed) {
  6073. auto res = cli_.Get("/streamed");
  6074. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6075. EXPECT_EQ(StatusCode::OK_200, res->status);
  6076. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6077. EXPECT_EQ(std::string("aaabbb"), res->body);
  6078. }
  6079. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  6080. auto res = cli_.Get("/streamed-without-length",
  6081. Headers{make_range_header({{0, -1}})});
  6082. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6083. EXPECT_EQ(StatusCode::OK_200, res->status);
  6084. EXPECT_EQ(false, res->has_header("Content-Length"));
  6085. EXPECT_EQ(false, res->has_header("Content-Range"));
  6086. EXPECT_EQ(std::string("abcdefg"), res->body);
  6087. }
  6088. TEST_F(ServerTest, GetStreamedWithRange1) {
  6089. auto res =
  6090. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  6091. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6092. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6093. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6094. EXPECT_EQ(true, res->has_header("Content-Range"));
  6095. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6096. EXPECT_EQ(std::string("def"), res->body);
  6097. }
  6098. TEST_F(ServerTest, GetStreamedWithRange2) {
  6099. auto res =
  6100. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  6101. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6102. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6103. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6104. EXPECT_EQ(true, res->has_header("Content-Range"));
  6105. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6106. EXPECT_EQ(std::string("bcdefg"), res->body);
  6107. }
  6108. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  6109. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  6110. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6111. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6112. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6113. EXPECT_EQ(true, res->has_header("Content-Range"));
  6114. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  6115. EXPECT_EQ(std::string("efg"), res->body);
  6116. }
  6117. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  6118. auto res =
  6119. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-9999"}});
  6120. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6121. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6122. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6123. EXPECT_EQ(false, res->has_header("Content-Range"));
  6124. EXPECT_EQ(0U, res->body.size());
  6125. }
  6126. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  6127. // Only a 206 is served as a partial representation. Under any other status
  6128. // `apply_ranges()` reported the full content length, so the body must match
  6129. // that header, and the content provider must never be asked for an offset
  6130. // outside the representation.
  6131. auto check = [&](int status, const char *range) {
  6132. auto path =
  6133. std::string("/streamed-with-range?status=") + std::to_string(status);
  6134. auto ctx = path + " Range: " + range;
  6135. auto res = cli_.Get(path, Headers{{"Range", range}});
  6136. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  6137. EXPECT_EQ(status, res->status) << ctx;
  6138. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  6139. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  6140. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  6141. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  6142. };
  6143. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  6144. check(403, "bytes=3-5");
  6145. // The offset is far past the representation.
  6146. check(403, "bytes=100000-100200");
  6147. // `first_pos` is still -1 here, and the bounds asserts in
  6148. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  6149. check(403, "bytes=-3");
  6150. // `apply_ranges()` makes no boundary for a non-206 response, so the
  6151. // multipart branch would have written one that is empty.
  6152. check(403, "bytes=1-2, 4-5");
  6153. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  6154. // covers the whole representation.
  6155. check(200, "bytes=3-5");
  6156. check(200, "bytes=1-2, 4-5");
  6157. }
  6158. TEST_F(ServerTest, GetStreamedWithRangeError) {
  6159. auto res =
  6160. cli_.Get("/streamed-with-range",
  6161. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  6162. "92233720368547758079223372036854775807"}});
  6163. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6164. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6165. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6166. EXPECT_EQ(false, res->has_header("Content-Range"));
  6167. EXPECT_EQ(0U, res->body.size());
  6168. }
  6169. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  6170. auto res = cli_.Get(
  6171. "/with-range",
  6172. Headers{{"Range",
  6173. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  6174. {"Accept-Encoding", ""}});
  6175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6176. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6177. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6178. EXPECT_EQ(true, res->has_header("Content-Range"));
  6179. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6180. EXPECT_EQ(std::string("abcdefg"), res->body);
  6181. }
  6182. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  6183. auto res = cli_.Get("/with-range", Headers{
  6184. {"Range", "bytes=0-"},
  6185. {"Accept-Encoding", ""},
  6186. });
  6187. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6188. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6189. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6190. EXPECT_EQ(true, res->has_header("Content-Range"));
  6191. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6192. EXPECT_EQ(std::string("abcdefg"), res->body);
  6193. }
  6194. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  6195. auto res = cli_.Get("/streamed-with-range",
  6196. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6197. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6198. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6199. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6200. EXPECT_EQ(false, res->has_header("Content-Range"));
  6201. EXPECT_EQ(267U, res->body.size());
  6202. // Check that both range contents are present
  6203. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  6204. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6205. // Check that Content-Range headers are present for both ranges
  6206. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  6207. std::string::npos);
  6208. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6209. std::string::npos);
  6210. }
  6211. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  6212. Ranges ranges;
  6213. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  6214. ranges.emplace_back(0, -1);
  6215. }
  6216. auto res = cli_.Get("/streamed-with-range?error",
  6217. Headers{{make_range_header(ranges)}});
  6218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6219. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6220. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6221. EXPECT_EQ(false, res->has_header("Content-Range"));
  6222. EXPECT_EQ(0U, res->body.size());
  6223. }
  6224. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  6225. auto res = cli_.Get("/streamed-with-range",
  6226. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  6227. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6228. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6229. EXPECT_EQ(5U, res->body.size());
  6230. // Check that overlapping ranges are coalesced into a single range
  6231. EXPECT_EQ("bcdef", res->body);
  6232. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  6233. // Should be single range, not multipart
  6234. EXPECT_TRUE(res->has_header("Content-Range"));
  6235. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6236. }
  6237. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  6238. auto res = cli_.Get("/streamed-with-range",
  6239. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  6240. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6241. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6242. EXPECT_EQ(268U, res->body.size());
  6243. // Check that both range contents are present
  6244. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6245. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  6246. // Check that Content-Range headers are present for both ranges
  6247. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6248. std::string::npos);
  6249. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  6250. std::string::npos);
  6251. }
  6252. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  6253. auto res = cli_.Get("/streamed-with-range",
  6254. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  6255. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6256. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6257. EXPECT_EQ(269U, res->body.size());
  6258. // Check that both duplicate range contents are present
  6259. size_t first_abc = res->body.find("abc\r\n");
  6260. EXPECT_TRUE(first_abc != std::string::npos);
  6261. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  6262. EXPECT_TRUE(second_abc != std::string::npos);
  6263. // Check that Content-Range headers are present for both ranges
  6264. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  6265. EXPECT_TRUE(first_range != std::string::npos);
  6266. size_t second_range =
  6267. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  6268. EXPECT_TRUE(second_range != std::string::npos);
  6269. }
  6270. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  6271. auto res =
  6272. cli_.Get("/streamed-with-range?error",
  6273. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  6274. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6275. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6276. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6277. EXPECT_EQ(false, res->has_header("Content-Range"));
  6278. EXPECT_EQ(0U, res->body.size());
  6279. }
  6280. TEST_F(ServerTest, GetStreamedEndless) {
  6281. uint64_t offset = 0;
  6282. auto res = cli_.Get("/streamed-cancel",
  6283. [&](const char * /*data*/, uint64_t data_length) {
  6284. if (offset < 100) {
  6285. offset += data_length;
  6286. return true;
  6287. }
  6288. return false;
  6289. });
  6290. ASSERT_TRUE(!res);
  6291. EXPECT_EQ(Error::Canceled, res.error());
  6292. }
  6293. TEST_F(ServerTest, ClientStop) {
  6294. std::atomic_size_t count{4};
  6295. std::vector<std::thread> threads;
  6296. for (auto i = count.load(); i != 0; --i) {
  6297. threads.emplace_back([&]() {
  6298. auto res = cli_.Get("/streamed-cancel",
  6299. [&](const char *, uint64_t) { return true; });
  6300. --count;
  6301. ASSERT_TRUE(!res);
  6302. EXPECT_TRUE(res.error() == Error::Canceled ||
  6303. res.error() == Error::Read || res.error() == Error::Write);
  6304. });
  6305. }
  6306. std::this_thread::sleep_for(std::chrono::seconds(2));
  6307. while (count != 0) {
  6308. cli_.stop();
  6309. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  6310. }
  6311. for (auto &t : threads) {
  6312. t.join();
  6313. }
  6314. }
  6315. TEST_F(ServerTest, GetWithRange1) {
  6316. auto res = cli_.Get("/with-range", Headers{
  6317. make_range_header({{3, 5}}),
  6318. {"Accept-Encoding", ""},
  6319. });
  6320. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6321. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6322. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6323. EXPECT_EQ(true, res->has_header("Content-Range"));
  6324. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6325. EXPECT_EQ(std::string("def"), res->body);
  6326. }
  6327. TEST_F(ServerTest, GetWithRange2) {
  6328. auto res = cli_.Get("/with-range", Headers{
  6329. make_range_header({{1, -1}}),
  6330. {"Accept-Encoding", ""},
  6331. });
  6332. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6333. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6334. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6335. EXPECT_EQ(true, res->has_header("Content-Range"));
  6336. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6337. EXPECT_EQ(std::string("bcdefg"), res->body);
  6338. }
  6339. TEST_F(ServerTest, GetWithRange3) {
  6340. auto res = cli_.Get("/with-range", Headers{
  6341. make_range_header({{0, 0}}),
  6342. {"Accept-Encoding", ""},
  6343. });
  6344. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6345. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6346. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  6347. EXPECT_EQ(true, res->has_header("Content-Range"));
  6348. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  6349. EXPECT_EQ(std::string("a"), res->body);
  6350. }
  6351. TEST_F(ServerTest, GetWithRange4) {
  6352. auto res = cli_.Get("/with-range", Headers{
  6353. make_range_header({{-1, 2}}),
  6354. {"Accept-Encoding", ""},
  6355. });
  6356. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6357. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6358. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6359. EXPECT_EQ(true, res->has_header("Content-Range"));
  6360. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  6361. EXPECT_EQ(std::string("fg"), res->body);
  6362. }
  6363. TEST_F(ServerTest, GetWithRange5) {
  6364. auto res = cli_.Get("/with-range", Headers{
  6365. make_range_header({{0, 5}}),
  6366. {"Accept-Encoding", ""},
  6367. });
  6368. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6369. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6370. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6371. EXPECT_EQ(true, res->has_header("Content-Range"));
  6372. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  6373. EXPECT_EQ(std::string("abcdef"), res->body);
  6374. }
  6375. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  6376. auto res =
  6377. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  6378. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6379. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6380. }
  6381. TEST_F(ServerTest, GetWithRangeMultipart) {
  6382. auto res =
  6383. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6384. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6385. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6386. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6387. EXPECT_EQ(false, res->has_header("Content-Range"));
  6388. EXPECT_EQ(267U, res->body.size());
  6389. }
  6390. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  6391. auto res = cli_.Get("/with-range",
  6392. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  6393. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6394. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6395. }
  6396. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  6397. auto res = cli_.Get("/with-range-customized-response",
  6398. Headers{{make_range_header({{1, 2}})}});
  6399. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6400. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6401. EXPECT_EQ(true, res->has_header("Content-Length"));
  6402. EXPECT_EQ(false, res->has_header("Content-Range"));
  6403. EXPECT_EQ(JSON_DATA, res->body);
  6404. }
  6405. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  6406. auto res = cli_.Get("/with-range-customized-response",
  6407. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6408. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6409. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6410. EXPECT_EQ(true, res->has_header("Content-Length"));
  6411. EXPECT_EQ(false, res->has_header("Content-Range"));
  6412. EXPECT_EQ(JSON_DATA, res->body);
  6413. }
  6414. TEST_F(ServerTest, Issue1772) {
  6415. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  6416. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6417. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  6418. }
  6419. TEST_F(ServerTest, Issue609) {
  6420. auto res = cli_.Delete("/issue609");
  6421. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6422. EXPECT_EQ(StatusCode::OK_200, res->status);
  6423. EXPECT_EQ(std::string("ok"), res->body);
  6424. }
  6425. TEST_F(ServerTest, GetStreamedChunked) {
  6426. auto res = cli_.Get("/streamed-chunked");
  6427. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6428. EXPECT_EQ(StatusCode::OK_200, res->status);
  6429. EXPECT_EQ(std::string("123456789"), res->body);
  6430. }
  6431. TEST_F(ServerTest, GetStreamedChunked2) {
  6432. auto res = cli_.Get("/streamed-chunked2");
  6433. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6434. EXPECT_EQ(StatusCode::OK_200, res->status);
  6435. EXPECT_EQ(std::string("123456789"), res->body);
  6436. }
  6437. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  6438. auto res = cli_.Get("/streamed-chunked-with-trailer");
  6439. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6440. EXPECT_EQ(StatusCode::OK_200, res->status);
  6441. EXPECT_EQ(std::string("123456789"), res->body);
  6442. EXPECT_TRUE(res->has_header("Trailer"));
  6443. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  6444. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  6445. // Trailers are now stored separately from headers (security fix)
  6446. EXPECT_EQ(2U, res->trailers.size());
  6447. EXPECT_TRUE(res->has_trailer("Dummy1"));
  6448. EXPECT_TRUE(res->has_trailer("Dummy2"));
  6449. EXPECT_FALSE(res->has_trailer("Dummy3"));
  6450. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  6451. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  6452. // Verify trailers are NOT in headers (security verification)
  6453. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  6454. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  6455. }
  6456. TEST_F(ServerTest, LargeChunkedPost) {
  6457. Request req;
  6458. req.method = "POST";
  6459. req.path = "/large-chunked";
  6460. std::string host_and_port;
  6461. host_and_port += HOST;
  6462. host_and_port += ":";
  6463. host_and_port += std::to_string(PORT);
  6464. req.headers.emplace("Host", host_and_port.c_str());
  6465. req.headers.emplace("Accept", "*/*");
  6466. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6467. req.headers.emplace("Content-Type", "text/plain");
  6468. req.headers.emplace("Content-Length", "0");
  6469. req.headers.emplace("Transfer-Encoding", "chunked");
  6470. std::string long_string(30 * 1024u, 'a');
  6471. std::string chunk = "7800\r\n" + long_string + "\r\n";
  6472. // Attempt to make a large enough post to exceed OS buffers, to test that
  6473. // the server handles short reads if the full chunk data isn't available.
  6474. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  6475. auto res = std::make_shared<Response>();
  6476. auto error = Error::Success;
  6477. auto ret = cli_.send(req, *res, error);
  6478. ASSERT_TRUE(ret);
  6479. EXPECT_EQ(StatusCode::OK_200, res->status);
  6480. }
  6481. TEST_F(ServerTest, GetMethodRemoteAddr) {
  6482. auto res = cli_.Get("/remote_addr");
  6483. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6484. EXPECT_EQ(StatusCode::OK_200, res->status);
  6485. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6486. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  6487. }
  6488. TEST_F(ServerTest, GetMethodLocalAddr) {
  6489. auto res = cli_.Get("/local_addr");
  6490. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6491. EXPECT_EQ(StatusCode::OK_200, res->status);
  6492. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6493. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  6494. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  6495. }
  6496. TEST_F(ServerTest, HTTPResponseSplitting) {
  6497. auto res = cli_.Get("/http_response_splitting");
  6498. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6499. EXPECT_EQ(StatusCode::OK_200, res->status);
  6500. }
  6501. TEST_F(ServerTest, SlowRequest) {
  6502. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6503. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6504. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6505. }
  6506. #if 0
  6507. TEST_F(ServerTest, SlowPost) {
  6508. char buffer[64 * 1024];
  6509. memset(buffer, 0x42, sizeof(buffer));
  6510. auto res = cli_.Post(
  6511. "/slowpost", 64 * 1024 * 1024,
  6512. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6513. auto ret = sink.write(buffer, sizeof(buffer));
  6514. EXPECT_TRUE(ret);
  6515. return true;
  6516. },
  6517. "text/plain");
  6518. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6519. EXPECT_EQ(StatusCode::OK_200, res->status);
  6520. }
  6521. TEST_F(ServerTest, SlowPostFail) {
  6522. char buffer[64 * 1024];
  6523. memset(buffer, 0x42, sizeof(buffer));
  6524. cli_.set_write_timeout(std::chrono::seconds(0));
  6525. auto res = cli_.Post(
  6526. "/slowpost", 64 * 1024 * 1024,
  6527. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6528. sink.write(buffer, sizeof(buffer));
  6529. return true;
  6530. },
  6531. "text/plain");
  6532. ASSERT_TRUE(!res);
  6533. EXPECT_EQ(Error::Write, res.error());
  6534. }
  6535. #endif
  6536. TEST_F(ServerTest, Put) {
  6537. auto res = cli_.Put("/put", "PUT", "text/plain");
  6538. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6539. EXPECT_EQ(StatusCode::OK_200, res->status);
  6540. EXPECT_EQ("PUT", res->body);
  6541. }
  6542. TEST_F(ServerTest, PutWithContentProvider) {
  6543. auto res = cli_.Put(
  6544. "/put", 3,
  6545. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6546. sink.os << "PUT";
  6547. return true;
  6548. },
  6549. "text/plain");
  6550. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6551. EXPECT_EQ(StatusCode::OK_200, res->status);
  6552. EXPECT_EQ("PUT", res->body);
  6553. }
  6554. TEST_F(ServerTest, PostWithContentProviderAbort) {
  6555. auto res = cli_.Post(
  6556. "/post", 42,
  6557. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6558. return false;
  6559. },
  6560. "text/plain");
  6561. ASSERT_TRUE(!res);
  6562. EXPECT_EQ(Error::Canceled, res.error());
  6563. }
  6564. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  6565. auto res = cli_.Put(
  6566. "/put",
  6567. [](size_t /*offset*/, DataSink &sink) {
  6568. sink.os << "PUT";
  6569. sink.done();
  6570. return true;
  6571. },
  6572. "text/plain");
  6573. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6574. EXPECT_EQ(StatusCode::OK_200, res->status);
  6575. EXPECT_EQ("PUT", res->body);
  6576. }
  6577. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  6578. auto res = cli_.Post(
  6579. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6580. "text/plain");
  6581. ASSERT_TRUE(!res);
  6582. EXPECT_EQ(Error::Canceled, res.error());
  6583. }
  6584. TEST_F(ServerTest, PostLoopBack) {
  6585. std::string body;
  6586. auto res = cli_.Post(
  6587. "/post-loopback", 9,
  6588. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6589. EXPECT_EQ(9u, length);
  6590. sink.write("123", 3);
  6591. sink.write("456", 3);
  6592. sink.write("789", 3);
  6593. return true;
  6594. },
  6595. "text/plain",
  6596. [&body](const char *data, size_t data_length) {
  6597. body.append(data, data_length);
  6598. return true;
  6599. });
  6600. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6601. EXPECT_EQ(StatusCode::OK_200, res->status);
  6602. EXPECT_EQ("123456789", body);
  6603. }
  6604. TEST_F(ServerTest, PutLoopBack) {
  6605. std::string body;
  6606. auto res = cli_.Put(
  6607. "/put-loopback", 9,
  6608. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6609. EXPECT_EQ(9u, length);
  6610. sink.write("123", 3);
  6611. sink.write("456", 3);
  6612. sink.write("789", 3);
  6613. return true;
  6614. },
  6615. "text/plain",
  6616. [&body](const char *data, size_t data_length) {
  6617. body.append(data, data_length);
  6618. return true;
  6619. });
  6620. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6621. EXPECT_EQ(StatusCode::OK_200, res->status);
  6622. EXPECT_EQ("123456789", body);
  6623. }
  6624. TEST_F(ServerTest, PatchLoopBack) {
  6625. std::string body;
  6626. auto res = cli_.Patch(
  6627. "/patch-loopback", 9,
  6628. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6629. EXPECT_EQ(9u, length);
  6630. sink.write("123", 3);
  6631. sink.write("456", 3);
  6632. sink.write("789", 3);
  6633. return true;
  6634. },
  6635. "text/plain",
  6636. [&body](const char *data, size_t data_length) {
  6637. body.append(data, data_length);
  6638. return true;
  6639. });
  6640. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6641. EXPECT_EQ(StatusCode::OK_200, res->status);
  6642. EXPECT_EQ("123456789", body);
  6643. }
  6644. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  6645. std::string body;
  6646. auto res = cli_.Post(
  6647. "/post-loopback",
  6648. [](size_t /*offset*/, DataSink &sink) {
  6649. sink.write("123", 3);
  6650. sink.write("456", 3);
  6651. sink.write("789", 3);
  6652. sink.done();
  6653. return true;
  6654. },
  6655. "text/plain",
  6656. [&body](const char *data, size_t data_length) {
  6657. body.append(data, data_length);
  6658. return true;
  6659. });
  6660. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6661. EXPECT_EQ(StatusCode::OK_200, res->status);
  6662. EXPECT_EQ("123456789", body);
  6663. }
  6664. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6665. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  6666. cli_.set_compress(true);
  6667. auto res = cli_.Put(
  6668. "/put", 3,
  6669. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6670. sink.os << "PUT";
  6671. return true;
  6672. },
  6673. "text/plain");
  6674. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6675. EXPECT_EQ(StatusCode::OK_200, res->status);
  6676. EXPECT_EQ("PUT", res->body);
  6677. }
  6678. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  6679. cli_.set_compress(true);
  6680. auto res = cli_.Post(
  6681. "/post", 42,
  6682. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6683. return false;
  6684. },
  6685. "text/plain");
  6686. ASSERT_TRUE(!res);
  6687. EXPECT_EQ(Error::Canceled, res.error());
  6688. }
  6689. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  6690. cli_.set_compress(true);
  6691. auto res = cli_.Put(
  6692. "/put",
  6693. [](size_t /*offset*/, DataSink &sink) {
  6694. sink.os << "PUT";
  6695. sink.done();
  6696. return true;
  6697. },
  6698. "text/plain");
  6699. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6700. EXPECT_EQ(StatusCode::OK_200, res->status);
  6701. EXPECT_EQ("PUT", res->body);
  6702. }
  6703. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  6704. cli_.set_compress(true);
  6705. auto res = cli_.Post(
  6706. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6707. "text/plain");
  6708. ASSERT_TRUE(!res);
  6709. EXPECT_EQ(Error::Canceled, res.error());
  6710. }
  6711. TEST_F(ServerTest, PutLargeFileWithGzip) {
  6712. cli_.set_compress(true);
  6713. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6714. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6715. EXPECT_EQ(StatusCode::OK_200, res->status);
  6716. EXPECT_EQ(LARGE_DATA, res->body);
  6717. }
  6718. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  6719. #ifdef CPPHTTPLIB_SSL_ENABLED
  6720. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  6721. Client cli(s.c_str());
  6722. cli.enable_server_certificate_verification(false);
  6723. #else
  6724. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  6725. Client cli(s.c_str());
  6726. #endif
  6727. cli.set_compress(true);
  6728. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  6729. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6730. EXPECT_EQ(StatusCode::OK_200, res->status);
  6731. EXPECT_EQ(LARGE_DATA, res->body);
  6732. // The compressed size should be less than a 10th of the original. May vary
  6733. // depending on the zlib library.
  6734. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  6735. static_cast<uint64_t>(10 * 1024 * 1024));
  6736. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6737. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6738. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  6739. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  6740. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  6741. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  6742. #endif
  6743. }
  6744. TEST_F(ServerTest, PutContentWithDeflate) {
  6745. cli_.set_compress(false);
  6746. Headers headers;
  6747. headers.emplace("Content-Encoding", "deflate");
  6748. // PUT in deflate format:
  6749. auto res = cli_.Put("/put", headers,
  6750. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  6751. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6752. EXPECT_EQ(StatusCode::OK_200, res->status);
  6753. EXPECT_EQ("PUT", res->body);
  6754. }
  6755. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  6756. Headers headers;
  6757. headers.emplace("Accept-Encoding", "gzip, deflate");
  6758. auto res = cli_.Get("/streamed-chunked", headers);
  6759. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6760. EXPECT_EQ(StatusCode::OK_200, res->status);
  6761. EXPECT_EQ(std::string("123456789"), res->body);
  6762. }
  6763. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  6764. Headers headers;
  6765. headers.emplace("Accept-Encoding", "gzip, deflate");
  6766. auto res = cli_.Get("/streamed-chunked2", headers);
  6767. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6768. EXPECT_EQ(StatusCode::OK_200, res->status);
  6769. EXPECT_EQ(std::string("123456789"), res->body);
  6770. }
  6771. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  6772. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  6773. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6774. EXPECT_EQ(StatusCode::OK_200, res->status);
  6775. }
  6776. TEST(GzipDecompressor, ChunkedDecompression) {
  6777. std::string data;
  6778. for (size_t i = 0; i < 32 * 1024; ++i) {
  6779. data.push_back(static_cast<char>('a' + i % 26));
  6780. }
  6781. std::string compressed_data;
  6782. {
  6783. httplib::detail::gzip_compressor compressor;
  6784. bool result = compressor.compress(
  6785. data.data(), data.size(),
  6786. /*last=*/true,
  6787. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  6788. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  6789. compressed_data_size);
  6790. return true;
  6791. });
  6792. ASSERT_TRUE(result);
  6793. }
  6794. std::string decompressed_data;
  6795. {
  6796. httplib::detail::gzip_decompressor decompressor;
  6797. // Chunk size is chosen specifically to have a decompressed chunk size equal
  6798. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  6799. size_t chunk_size = 130;
  6800. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  6801. chunk_begin += chunk_size) {
  6802. size_t current_chunk_size =
  6803. std::min(compressed_data.size() - chunk_begin, chunk_size);
  6804. bool result = decompressor.decompress(
  6805. compressed_data.data() + chunk_begin, current_chunk_size,
  6806. [&](const char *decompressed_data_chunk,
  6807. size_t decompressed_data_chunk_size) {
  6808. decompressed_data.insert(decompressed_data.size(),
  6809. decompressed_data_chunk,
  6810. decompressed_data_chunk_size);
  6811. return true;
  6812. });
  6813. ASSERT_TRUE(result);
  6814. }
  6815. }
  6816. ASSERT_EQ(data, decompressed_data);
  6817. }
  6818. TEST(GzipDecompressor, DeflateDecompression) {
  6819. std::string original_text = "Raw deflate without gzip";
  6820. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6821. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6822. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6823. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  6824. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6825. std::string decompressed_data;
  6826. {
  6827. httplib::detail::gzip_decompressor decompressor;
  6828. bool result = decompressor.decompress(
  6829. compressed_data.data(), compressed_data.size(),
  6830. [&](const char *decompressed_data_chunk,
  6831. size_t decompressed_data_chunk_size) {
  6832. decompressed_data.insert(decompressed_data.size(),
  6833. decompressed_data_chunk,
  6834. decompressed_data_chunk_size);
  6835. return true;
  6836. });
  6837. ASSERT_TRUE(result);
  6838. }
  6839. ASSERT_EQ(original_text, decompressed_data);
  6840. }
  6841. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  6842. std::string original_text = "Raw deflate without gzip";
  6843. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6844. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6845. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6846. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  6847. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  6848. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6849. std::string decompressed_data;
  6850. {
  6851. httplib::detail::gzip_decompressor decompressor;
  6852. bool result = decompressor.decompress(
  6853. compressed_data.data(), compressed_data.size(),
  6854. [&](const char *decompressed_data_chunk,
  6855. size_t decompressed_data_chunk_size) {
  6856. decompressed_data.insert(decompressed_data.size(),
  6857. decompressed_data_chunk,
  6858. decompressed_data_chunk_size);
  6859. return true;
  6860. });
  6861. ASSERT_TRUE(result);
  6862. }
  6863. ASSERT_EQ(original_text, decompressed_data);
  6864. }
  6865. #endif
  6866. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6867. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  6868. Headers headers;
  6869. headers.emplace("Accept-Encoding", "br");
  6870. auto res = cli_.Get("/streamed-chunked", headers);
  6871. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6872. EXPECT_EQ(StatusCode::OK_200, res->status);
  6873. EXPECT_EQ(std::string("123456789"), res->body);
  6874. }
  6875. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  6876. Headers headers;
  6877. headers.emplace("Accept-Encoding", "br");
  6878. auto res = cli_.Get("/streamed-chunked2", headers);
  6879. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6880. EXPECT_EQ(StatusCode::OK_200, res->status);
  6881. EXPECT_EQ(std::string("123456789"), res->body);
  6882. }
  6883. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  6884. cli_.set_compress(true);
  6885. auto res = cli_.Put(
  6886. "/put", 3,
  6887. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6888. sink.os << "PUT";
  6889. return true;
  6890. },
  6891. "text/plain");
  6892. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6893. EXPECT_EQ(StatusCode::OK_200, res->status);
  6894. EXPECT_EQ("PUT", res->body);
  6895. }
  6896. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  6897. cli_.set_compress(true);
  6898. auto res = cli_.Put(
  6899. "/put",
  6900. [](size_t /*offset*/, DataSink &sink) {
  6901. sink.os << "PUT";
  6902. sink.done();
  6903. return true;
  6904. },
  6905. "text/plain");
  6906. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6907. EXPECT_EQ(StatusCode::OK_200, res->status);
  6908. EXPECT_EQ("PUT", res->body);
  6909. }
  6910. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  6911. cli_.set_compress(true);
  6912. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6913. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6914. EXPECT_EQ(StatusCode::OK_200, res->status);
  6915. EXPECT_EQ(LARGE_DATA, res->body);
  6916. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6917. }
  6918. #endif
  6919. TEST_F(ServerTest, Patch) {
  6920. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  6921. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6922. EXPECT_EQ(StatusCode::OK_200, res->status);
  6923. EXPECT_EQ("PATCH", res->body);
  6924. }
  6925. TEST_F(ServerTest, Delete) {
  6926. auto res = cli_.Delete("/delete");
  6927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6928. EXPECT_EQ(StatusCode::OK_200, res->status);
  6929. EXPECT_EQ("DELETE", res->body);
  6930. }
  6931. TEST_F(ServerTest, DeleteContentReceiver) {
  6932. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  6933. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6934. EXPECT_EQ(StatusCode::OK_200, res->status);
  6935. EXPECT_EQ("content", res->body);
  6936. }
  6937. TEST_F(ServerTest, Options) {
  6938. auto res = cli_.Options("*");
  6939. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6940. EXPECT_EQ(StatusCode::OK_200, res->status);
  6941. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  6942. EXPECT_TRUE(res->body.empty());
  6943. }
  6944. TEST_F(ServerTest, URL) {
  6945. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  6946. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6947. EXPECT_EQ(StatusCode::OK_200, res->status);
  6948. }
  6949. TEST_F(ServerTest, ArrayParam) {
  6950. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  6951. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6952. EXPECT_EQ(StatusCode::OK_200, res->status);
  6953. }
  6954. TEST_F(ServerTest, ArrayParamValues) {
  6955. auto res =
  6956. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  6957. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6958. EXPECT_EQ(StatusCode::OK_200, res->status);
  6959. }
  6960. TEST_F(ServerTest, NoMultipleHeaders) {
  6961. Headers headers = {{"Content-Length", "5"}};
  6962. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  6963. "text/plain");
  6964. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6965. EXPECT_EQ(StatusCode::OK_200, res->status);
  6966. }
  6967. TEST_F(ServerTest, PostContentReceiver) {
  6968. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  6969. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6970. ASSERT_EQ(StatusCode::OK_200, res->status);
  6971. ASSERT_EQ("content", res->body);
  6972. }
  6973. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  6974. UploadFormDataItems items = {
  6975. {"text1", "text default", "", ""},
  6976. {"text2", "aωb", "", ""},
  6977. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6978. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  6979. {"file3", "", "", "application/octet-stream"},
  6980. };
  6981. auto res = cli_.Post("/content_receiver", items);
  6982. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6983. EXPECT_EQ(StatusCode::OK_200, res->status);
  6984. }
  6985. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  6986. UploadFormDataItems items = {
  6987. {"text1", "text default", "", ""},
  6988. {"text2", "aωb", "", ""},
  6989. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6990. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  6991. {"file3", "", "", "application/octet-stream"},
  6992. };
  6993. auto boundary = std::string("+++++");
  6994. std::string body;
  6995. for (const auto &item : items) {
  6996. body += "--" + boundary + "\r\n";
  6997. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  6998. if (!item.filename.empty()) {
  6999. body += "; filename=\"" + item.filename + "\"";
  7000. }
  7001. body += "\r\n";
  7002. if (!item.content_type.empty()) {
  7003. body += "Content-Type: " + item.content_type + "\r\n";
  7004. }
  7005. body += "\r\n";
  7006. body += item.content + "\r\n";
  7007. }
  7008. body += "--" + boundary + "--\r\n";
  7009. std::string content_type = "multipart/form-data; boundary=" + boundary;
  7010. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  7011. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7012. EXPECT_EQ(StatusCode::OK_200, res->status);
  7013. }
  7014. TEST(MultipartFormDataTest, FieldEscaping) {
  7015. Server svr;
  7016. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7017. const ContentReader &content_reader) {
  7018. ASSERT_TRUE(req.is_multipart_form_data());
  7019. std::vector<FormData> received;
  7020. content_reader(
  7021. [&](const FormData &file) {
  7022. received.push_back(file);
  7023. return true;
  7024. },
  7025. [&](const char *data, size_t data_length) {
  7026. received.back().content.append(data, data_length);
  7027. return true;
  7028. });
  7029. // '"', CR and LF in names and filenames are escaped following the
  7030. // WHATWG HTML standard, so each part still parses as a single part
  7031. // with no injected headers. Content types get CR/LF escaped too,
  7032. // while '"' (legal there, e.g. quoted charset) is preserved.
  7033. ASSERT_EQ(4U, received.size());
  7034. EXPECT_EQ("na%22me", received[0].name);
  7035. EXPECT_EQ("quoted name", received[0].content);
  7036. EXPECT_EQ("file", received[1].name);
  7037. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  7038. received[1].filename);
  7039. EXPECT_EQ("application/octet-stream", received[1].content_type);
  7040. EXPECT_EQ("injected", received[1].content);
  7041. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  7042. EXPECT_EQ("my%22file.txt", received[2].filename);
  7043. EXPECT_EQ("cr lf name", received[2].content);
  7044. EXPECT_EQ("typed", received[3].name);
  7045. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  7046. received[3].content_type);
  7047. EXPECT_EQ("typed content", received[3].content);
  7048. });
  7049. auto port = svr.bind_to_any_port("localhost");
  7050. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7051. auto se = detail::scope_exit([&] {
  7052. svr.stop();
  7053. t.join();
  7054. ASSERT_FALSE(svr.is_running());
  7055. });
  7056. svr.wait_until_ready();
  7057. Client cli("localhost", port);
  7058. UploadFormDataItems items = {
  7059. {"na\"me", "quoted name", "", ""},
  7060. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  7061. "application/octet-stream"},
  7062. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  7063. {"typed", "typed content", "",
  7064. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  7065. };
  7066. auto res = cli.Post("/post", items);
  7067. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7068. EXPECT_EQ(StatusCode::OK_200, res->status);
  7069. }
  7070. TEST(MultipartFormDataTest, PublicWriterAPI) {
  7071. const UploadFormDataItems items = {
  7072. {"name1", "Content 1", "", ""},
  7073. {"name2", "Content 2", "file2.txt", "text/plain"},
  7074. };
  7075. Server svr;
  7076. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7077. const ContentReader &content_reader) {
  7078. ASSERT_TRUE(req.is_multipart_form_data());
  7079. std::vector<FormData> received;
  7080. content_reader(
  7081. [&](const FormData &file) {
  7082. received.push_back(file);
  7083. return true;
  7084. },
  7085. [&](const char *data, size_t data_length) {
  7086. received.back().content.append(data, data_length);
  7087. return true;
  7088. });
  7089. ASSERT_EQ(2U, received.size());
  7090. EXPECT_EQ("name1", received[0].name);
  7091. EXPECT_EQ("Content 1", received[0].content);
  7092. EXPECT_EQ("name2", received[1].name);
  7093. EXPECT_EQ("Content 2", received[1].content);
  7094. EXPECT_EQ("file2.txt", received[1].filename);
  7095. EXPECT_EQ("text/plain", received[1].content_type);
  7096. });
  7097. auto port = svr.bind_to_any_port("localhost");
  7098. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7099. auto se = detail::scope_exit([&] {
  7100. svr.stop();
  7101. t.join();
  7102. ASSERT_FALSE(svr.is_running());
  7103. });
  7104. svr.wait_until_ready();
  7105. Client cli("localhost", port);
  7106. // Whole-body serialization with a generated boundary
  7107. {
  7108. MultipartFormDataWriter writer;
  7109. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  7110. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  7111. writer.content_type());
  7112. auto body = writer.serialize(items);
  7113. EXPECT_EQ(body.size(), writer.content_length(items));
  7114. auto res = cli.Post("/post", body, writer.content_type());
  7115. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7116. EXPECT_EQ(StatusCode::OK_200, res->status);
  7117. }
  7118. // Per-part framing with a custom boundary via a content provider
  7119. {
  7120. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  7121. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  7122. MultipartFormDataWriter writer("custom-boundary_123");
  7123. EXPECT_EQ("custom-boundary_123", writer.boundary());
  7124. std::string body;
  7125. for (const auto &item : items) {
  7126. body += writer.item_begin(item);
  7127. body += item.content;
  7128. body += MultipartFormDataWriter::item_end();
  7129. }
  7130. body += writer.finish();
  7131. EXPECT_EQ(body.size(), writer.content_length(items));
  7132. auto res = cli.Post(
  7133. "/post", body.size(),
  7134. [&](size_t offset, size_t length, DataSink &sink) {
  7135. sink.write(body.data() + offset, length);
  7136. return true;
  7137. },
  7138. writer.content_type());
  7139. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7140. EXPECT_EQ(StatusCode::OK_200, res->status);
  7141. }
  7142. }
  7143. TEST_F(ServerTest, PostContentReceiverGzip) {
  7144. cli_.set_compress(true);
  7145. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7146. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7147. ASSERT_EQ(StatusCode::OK_200, res->status);
  7148. ASSERT_EQ("content", res->body);
  7149. }
  7150. TEST_F(ServerTest, PutContentReceiver) {
  7151. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  7152. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7153. ASSERT_EQ(StatusCode::OK_200, res->status);
  7154. ASSERT_EQ("content", res->body);
  7155. }
  7156. TEST_F(ServerTest, PatchContentReceiver) {
  7157. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  7158. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7159. ASSERT_EQ(StatusCode::OK_200, res->status);
  7160. ASSERT_EQ("content", res->body);
  7161. }
  7162. template <typename ClientType>
  7163. void TestWithHeadersAndContentReceiver(
  7164. ClientType &cli,
  7165. std::function<Result(ClientType &, const std::string &, const Headers &,
  7166. const std::string &, const std::string &,
  7167. ContentReceiver, DownloadProgress)>
  7168. request_func) {
  7169. Headers headers;
  7170. headers.emplace("X-Custom-Header", "test-value");
  7171. std::string received_body;
  7172. auto res = request_func(
  7173. cli, "/content_receiver", headers, "content", "application/json",
  7174. [&](const char *data, size_t data_length) {
  7175. received_body.append(data, data_length);
  7176. return true;
  7177. },
  7178. nullptr);
  7179. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7180. EXPECT_EQ(StatusCode::OK_200, res->status);
  7181. EXPECT_EQ("content", received_body);
  7182. }
  7183. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  7184. #ifdef CPPHTTPLIB_SSL_ENABLED
  7185. using ClientT = SSLClient;
  7186. #else
  7187. using ClientT = Client;
  7188. #endif
  7189. TestWithHeadersAndContentReceiver<ClientT>(
  7190. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7191. const std::string &body, const std::string &content_type,
  7192. ContentReceiver receiver, DownloadProgress progress) {
  7193. return cli.Post(path, headers, body, content_type, receiver, progress);
  7194. });
  7195. }
  7196. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  7197. #ifdef CPPHTTPLIB_SSL_ENABLED
  7198. using ClientT = SSLClient;
  7199. #else
  7200. using ClientT = Client;
  7201. #endif
  7202. TestWithHeadersAndContentReceiver<ClientT>(
  7203. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7204. const std::string &body, const std::string &content_type,
  7205. ContentReceiver receiver, DownloadProgress progress) {
  7206. return cli.Put(path, headers, body, content_type, receiver, progress);
  7207. });
  7208. }
  7209. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  7210. #ifdef CPPHTTPLIB_SSL_ENABLED
  7211. using ClientT = SSLClient;
  7212. #else
  7213. using ClientT = Client;
  7214. #endif
  7215. TestWithHeadersAndContentReceiver<ClientT>(
  7216. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7217. const std::string &body, const std::string &content_type,
  7218. ContentReceiver receiver, DownloadProgress progress) {
  7219. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7220. });
  7221. }
  7222. template <typename ClientType>
  7223. void TestWithHeadersAndContentReceiverWithProgress(
  7224. ClientType &cli,
  7225. std::function<Result(ClientType &, const std::string &, const Headers &,
  7226. const std::string &, const std::string &,
  7227. ContentReceiver, DownloadProgress)>
  7228. request_func) {
  7229. Headers headers;
  7230. headers.emplace("X-Test-Header", "progress-test");
  7231. std::string received_body;
  7232. auto progress_called = false;
  7233. auto res = request_func(
  7234. cli, "/content_receiver", headers, "content", "text/plain",
  7235. [&](const char *data, size_t data_length) {
  7236. received_body.append(data, data_length);
  7237. return true;
  7238. },
  7239. [&](uint64_t /*current*/, uint64_t /*total*/) {
  7240. progress_called = true;
  7241. return true;
  7242. });
  7243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7244. EXPECT_EQ(StatusCode::OK_200, res->status);
  7245. EXPECT_EQ("content", received_body);
  7246. EXPECT_TRUE(progress_called);
  7247. }
  7248. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  7249. #ifdef CPPHTTPLIB_SSL_ENABLED
  7250. using ClientT = SSLClient;
  7251. #else
  7252. using ClientT = Client;
  7253. #endif
  7254. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7255. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7256. const std::string &body, const std::string &content_type,
  7257. ContentReceiver receiver, DownloadProgress progress) {
  7258. return cli.Post(path, headers, body, content_type, receiver, progress);
  7259. });
  7260. }
  7261. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  7262. #ifdef CPPHTTPLIB_SSL_ENABLED
  7263. using ClientT = SSLClient;
  7264. #else
  7265. using ClientT = Client;
  7266. #endif
  7267. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7268. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7269. const std::string &body, const std::string &content_type,
  7270. ContentReceiver receiver, DownloadProgress progress) {
  7271. return cli.Put(path, headers, body, content_type, receiver, progress);
  7272. });
  7273. }
  7274. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  7275. #ifdef CPPHTTPLIB_SSL_ENABLED
  7276. using ClientT = SSLClient;
  7277. #else
  7278. using ClientT = Client;
  7279. #endif
  7280. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7281. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7282. const std::string &body, const std::string &content_type,
  7283. ContentReceiver receiver, DownloadProgress progress) {
  7284. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7285. });
  7286. }
  7287. template <typename ClientType>
  7288. void TestWithHeadersAndContentReceiverError(
  7289. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  7290. const Headers &, const std::string &,
  7291. const std::string &, ContentReceiver)>
  7292. request_func) {
  7293. Headers headers;
  7294. headers.emplace("X-Error-Test", "true");
  7295. std::string received_body;
  7296. auto receiver_failed = false;
  7297. auto res =
  7298. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  7299. [&](const char *data, size_t data_length) {
  7300. received_body.append(data, data_length);
  7301. receiver_failed = true;
  7302. return false;
  7303. });
  7304. ASSERT_FALSE(res);
  7305. EXPECT_TRUE(receiver_failed);
  7306. }
  7307. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  7308. #ifdef CPPHTTPLIB_SSL_ENABLED
  7309. using ClientT = SSLClient;
  7310. #else
  7311. using ClientT = Client;
  7312. #endif
  7313. TestWithHeadersAndContentReceiverError<ClientT>(
  7314. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7315. const std::string &body, const std::string &content_type,
  7316. ContentReceiver receiver) {
  7317. return cli.Post(path, headers, body, content_type, receiver);
  7318. });
  7319. }
  7320. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  7321. #ifdef CPPHTTPLIB_SSL_ENABLED
  7322. using ClientT = SSLClient;
  7323. #else
  7324. using ClientT = Client;
  7325. #endif
  7326. TestWithHeadersAndContentReceiverError<ClientT>(
  7327. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7328. const std::string &body, const std::string &content_type,
  7329. ContentReceiver receiver) {
  7330. return cli.Put(path, headers, body, content_type, receiver);
  7331. });
  7332. }
  7333. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  7334. #ifdef CPPHTTPLIB_SSL_ENABLED
  7335. using ClientT = SSLClient;
  7336. #else
  7337. using ClientT = Client;
  7338. #endif
  7339. TestWithHeadersAndContentReceiverError<ClientT>(
  7340. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7341. const std::string &body, const std::string &content_type,
  7342. ContentReceiver receiver) {
  7343. return cli.Patch(path, headers, body, content_type, receiver);
  7344. });
  7345. }
  7346. TEST_F(ServerTest, PostQueryStringAndBody) {
  7347. auto res =
  7348. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  7349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7350. ASSERT_EQ(StatusCode::OK_200, res->status);
  7351. }
  7352. TEST_F(ServerTest, HTTP2Magic) {
  7353. Request req;
  7354. req.method = "PRI";
  7355. req.path = "*";
  7356. req.body = "SM";
  7357. auto res = std::make_shared<Response>();
  7358. auto error = Error::Success;
  7359. auto ret = cli_.send(req, *res, error);
  7360. ASSERT_TRUE(ret);
  7361. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7362. }
  7363. TEST_F(ServerTest, KeepAlive) {
  7364. auto res = cli_.Get("/hi");
  7365. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7366. EXPECT_EQ(StatusCode::OK_200, res->status);
  7367. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7368. EXPECT_EQ("Hello World!", res->body);
  7369. res = cli_.Get("/hi");
  7370. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7371. EXPECT_EQ(StatusCode::OK_200, res->status);
  7372. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7373. EXPECT_EQ("Hello World!", res->body);
  7374. res = cli_.Get("/hi");
  7375. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7376. EXPECT_EQ(StatusCode::OK_200, res->status);
  7377. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7378. EXPECT_EQ("Hello World!", res->body);
  7379. res = cli_.Get("/not-exist");
  7380. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7381. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7382. res = cli_.Post("/empty", "", "text/plain");
  7383. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7384. EXPECT_EQ(StatusCode::OK_200, res->status);
  7385. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7386. EXPECT_EQ("empty", res->body);
  7387. EXPECT_EQ("close", res->get_header_value("Connection"));
  7388. res = cli_.Post(
  7389. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  7390. "text/plain");
  7391. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7392. EXPECT_EQ(StatusCode::OK_200, res->status);
  7393. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7394. EXPECT_EQ("empty", res->body);
  7395. cli_.set_keep_alive(false);
  7396. res = cli_.Get("/last-request");
  7397. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7398. EXPECT_EQ(StatusCode::OK_200, res->status);
  7399. EXPECT_EQ("close", res->get_header_value("Connection"));
  7400. }
  7401. TEST_F(ServerTest, TooManyRedirect) {
  7402. cli_.set_follow_location(true);
  7403. auto res = cli_.Get("/redirect/0");
  7404. ASSERT_TRUE(!res);
  7405. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  7406. }
  7407. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  7408. Request req;
  7409. req.method = "FOOBAR";
  7410. req.path = "/hi";
  7411. cli_.set_keep_alive(true);
  7412. auto res = cli_.send(req);
  7413. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7414. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7415. EXPECT_EQ("close", res->get_header_value("Connection"));
  7416. EXPECT_FALSE(cli_.is_socket_open());
  7417. }
  7418. TEST_F(ServerTest, CustomRouteReadsBody) {
  7419. const std::string xml =
  7420. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  7421. Request req;
  7422. req.method = "PROPFIND";
  7423. req.path = "/dav/dir";
  7424. req.set_header("Depth", "1");
  7425. req.body = xml;
  7426. auto res = cli_.send(req);
  7427. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7428. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7429. EXPECT_EQ(xml, res->body);
  7430. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  7431. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  7432. }
  7433. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  7434. Request req;
  7435. req.method = "PROPFIND";
  7436. req.path = "/dav/42";
  7437. auto res = cli_.send(req);
  7438. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7439. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7440. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  7441. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  7442. }
  7443. TEST_F(ServerTest, CustomRouteRegexPattern) {
  7444. Request req;
  7445. req.method = "PROPFIND";
  7446. req.path = "/dav-re/123";
  7447. auto res = cli_.send(req);
  7448. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7449. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7450. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  7451. }
  7452. TEST_F(ServerTest, CustomRouteWithoutBody) {
  7453. Request req;
  7454. req.method = "MKCOL";
  7455. req.path = "/dav-mkcol";
  7456. auto res = cli_.send(req);
  7457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7458. EXPECT_EQ(StatusCode::Created_201, res->status);
  7459. }
  7460. TEST_F(ServerTest, CustomRouteWithContentReader) {
  7461. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  7462. Request req;
  7463. req.method = "REPORT";
  7464. req.path = "/dav-report";
  7465. req.body = xml;
  7466. auto res = cli_.send(req);
  7467. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7468. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7469. EXPECT_EQ(xml, res->body);
  7470. }
  7471. // A content reader route must fire even when the request carries no body,
  7472. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  7473. // Without that, a body-less PROPFIND-style request would fall through to 404.
  7474. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  7475. Request req;
  7476. req.method = "REPORT";
  7477. req.path = "/dav-report";
  7478. auto res = cli_.send(req);
  7479. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7480. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7481. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  7482. }
  7483. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  7484. Request req;
  7485. req.method = "PROPFIND";
  7486. req.path = "/not-dav";
  7487. auto res = cli_.send(req);
  7488. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7489. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7490. }
  7491. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  7492. Request req;
  7493. req.method = "UNLOCK";
  7494. req.path = "/dav/dir";
  7495. cli_.set_keep_alive(true);
  7496. auto res = cli_.send(req);
  7497. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7498. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7499. EXPECT_EQ("close", res->get_header_value("Connection"));
  7500. EXPECT_FALSE(cli_.is_socket_open());
  7501. }
  7502. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  7503. // The mount point serves this path, but only for GET and HEAD.
  7504. auto get_res = cli_.Get("/dir/index.html");
  7505. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  7506. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  7507. Request req;
  7508. req.method = "PROPFIND";
  7509. req.path = "/dir/index.html";
  7510. auto res = cli_.send(req);
  7511. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7512. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7513. }
  7514. TEST_F(ServerTest, CustomRouteKeepAlive) {
  7515. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7516. cli_.set_keep_alive(true);
  7517. for (auto i = 0; i < 2; i++) {
  7518. Request req;
  7519. req.method = "PROPFIND";
  7520. req.path = "/dav/dir";
  7521. req.body = xml;
  7522. auto res = cli_.send(req);
  7523. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7524. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7525. EXPECT_EQ(xml, res->body);
  7526. EXPECT_TRUE(cli_.is_socket_open());
  7527. }
  7528. // A built-in method must still be served on the same connection.
  7529. cli_.set_keep_alive(false);
  7530. auto res = cli_.Get("/hi");
  7531. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7532. EXPECT_EQ(StatusCode::OK_200, res->status);
  7533. EXPECT_EQ("close", res->get_header_value("Connection"));
  7534. }
  7535. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  7536. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7537. Request req;
  7538. req.method = "PROPFIND";
  7539. req.path = "/dav/dir";
  7540. req.set_header("Expect", "100-continue");
  7541. req.body = xml;
  7542. auto res = cli_.send(req);
  7543. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7544. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7545. EXPECT_EQ(xml, res->body);
  7546. }
  7547. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  7548. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7549. TEST_F(ServerTest, Gzip) {
  7550. Headers headers;
  7551. headers.emplace("Accept-Encoding", "gzip, deflate");
  7552. auto res = cli_.Get("/compress", headers);
  7553. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7554. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7555. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7556. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7557. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7558. "7890123456789012345678901234567890",
  7559. res->body);
  7560. EXPECT_EQ(StatusCode::OK_200, res->status);
  7561. }
  7562. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  7563. Headers headers;
  7564. headers.emplace("Accept-Encoding", "gzip, deflate");
  7565. auto res = cli_.Get("/compress-with-charset", headers);
  7566. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7567. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7568. EXPECT_EQ("application/json; charset=utf-8",
  7569. res->get_header_value("Content-Type"));
  7570. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7571. "7890123456789012345678901234567890",
  7572. res->body);
  7573. EXPECT_EQ(StatusCode::OK_200, res->status);
  7574. }
  7575. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  7576. Headers headers;
  7577. headers.emplace("Accept-Encoding", "");
  7578. auto res = cli_.Get("/compress", headers);
  7579. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7580. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7581. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7582. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7583. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7584. "7890123456789012345678901234567890",
  7585. res->body);
  7586. EXPECT_EQ(StatusCode::OK_200, res->status);
  7587. }
  7588. TEST_F(ServerTest, GzipWithContentReceiver) {
  7589. Headers headers;
  7590. headers.emplace("Accept-Encoding", "gzip, deflate");
  7591. std::string body;
  7592. auto res = cli_.Get("/compress", headers,
  7593. [&](const char *data, uint64_t data_length) {
  7594. EXPECT_EQ(100U, data_length);
  7595. body.append(data, data_length);
  7596. return true;
  7597. });
  7598. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7599. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7600. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7601. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7602. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7603. "7890123456789012345678901234567890",
  7604. body);
  7605. EXPECT_EQ(StatusCode::OK_200, res->status);
  7606. }
  7607. TEST_F(ServerTest, GzipWithoutDecompressing) {
  7608. Headers headers;
  7609. headers.emplace("Accept-Encoding", "gzip, deflate");
  7610. cli_.set_decompress(false);
  7611. auto res = cli_.Get("/compress", headers);
  7612. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7613. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7614. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7615. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7616. EXPECT_EQ(33U, res->body.size());
  7617. EXPECT_EQ(StatusCode::OK_200, res->status);
  7618. }
  7619. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  7620. Headers headers;
  7621. headers.emplace("Accept-Encoding", "");
  7622. std::string body;
  7623. auto res = cli_.Get("/compress", headers,
  7624. [&](const char *data, uint64_t data_length) {
  7625. EXPECT_EQ(100U, data_length);
  7626. body.append(data, data_length);
  7627. return true;
  7628. });
  7629. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7630. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7631. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7632. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7633. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7634. "7890123456789012345678901234567890",
  7635. body);
  7636. EXPECT_EQ(StatusCode::OK_200, res->status);
  7637. }
  7638. TEST_F(ServerTest, NoGzip) {
  7639. Headers headers;
  7640. headers.emplace("Accept-Encoding", "gzip, deflate");
  7641. auto res = cli_.Get("/nocompress", headers);
  7642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7643. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7644. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7645. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7646. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7647. "7890123456789012345678901234567890",
  7648. res->body);
  7649. EXPECT_EQ(StatusCode::OK_200, res->status);
  7650. }
  7651. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  7652. Headers headers;
  7653. headers.emplace("Accept-Encoding", "gzip, deflate");
  7654. std::string body;
  7655. auto res = cli_.Get("/nocompress", headers,
  7656. [&](const char *data, uint64_t data_length) {
  7657. EXPECT_EQ(100U, data_length);
  7658. body.append(data, data_length);
  7659. return true;
  7660. });
  7661. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7662. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7663. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7664. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7665. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7666. "7890123456789012345678901234567890",
  7667. body);
  7668. EXPECT_EQ(StatusCode::OK_200, res->status);
  7669. }
  7670. TEST_F(ServerTest, MultipartFormDataGzip) {
  7671. UploadFormDataItems items = {
  7672. {"key1", "test", "", ""},
  7673. {"key2", "--abcdefg123", "", ""},
  7674. };
  7675. cli_.set_compress(true);
  7676. auto res = cli_.Post("/compress-multipart", items);
  7677. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7678. EXPECT_EQ(StatusCode::OK_200, res->status);
  7679. }
  7680. #endif
  7681. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7682. // Static file compression is opt-in, so these run their own server rather than
  7683. // flipping it on for the shared ServerTest fixture, which would silently
  7684. // rewrite what every other static file test is asserting.
  7685. class StaticFileCompressionTest : public ::testing::Test {
  7686. protected:
  7687. void TearDown() override {
  7688. if (t_.joinable()) {
  7689. svr_.stop();
  7690. t_.join();
  7691. }
  7692. }
  7693. int start(const std::function<void(Server &)> &configure = nullptr) {
  7694. // Serves the same tree as a directory of build-time compressed assets
  7695. // would be served: the mount point names the coding the files are already
  7696. // stored in. Registered before "/" so it is the one that matches.
  7697. svr_.set_mount_point("/pre-encoded", "./www",
  7698. {{"Content-Encoding", "gzip"}});
  7699. svr_.set_mount_point("/", "./www");
  7700. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  7701. res.set_file_content("./www/dir/index.html", "text/html");
  7702. });
  7703. svr_.Get("/pre-encoded-file-content",
  7704. [](const Request & /*req*/, Response &res) {
  7705. res.set_header("Content-Encoding", "gzip");
  7706. res.set_file_content("./www/dir/index.html", "text/html");
  7707. });
  7708. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  7709. res.set_content_provider(
  7710. 6, "text/plain",
  7711. [](size_t offset, size_t /*length*/, DataSink &sink) {
  7712. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  7713. return true;
  7714. });
  7715. });
  7716. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  7717. res.set_content_provider(
  7718. 1000, "text/plain",
  7719. [](size_t offset, size_t /*length*/, DataSink &sink) {
  7720. if (offset < 100) {
  7721. std::string data(100, 'A');
  7722. sink.write(data.data(), data.size());
  7723. return true;
  7724. }
  7725. std::this_thread::sleep_for(std::chrono::seconds(2));
  7726. std::string data(900, 'B');
  7727. sink.write(data.data(), data.size());
  7728. return true;
  7729. });
  7730. });
  7731. if (configure) { configure(svr_); }
  7732. auto port = svr_.bind_to_any_port(HOST);
  7733. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  7734. svr_.wait_until_ready();
  7735. return port;
  7736. }
  7737. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  7738. // Every file under ./www except 1MB.txt is smaller than the default
  7739. // 1400-byte floor, so a test that needs a small file compressed has to lower
  7740. // it out of the way.
  7741. static void enable_without_floor(Server &svr) {
  7742. svr.set_static_file_compression(true);
  7743. svr.set_static_file_compression_min_length(0);
  7744. }
  7745. Server svr_;
  7746. std::thread t_;
  7747. };
  7748. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  7749. auto port = start();
  7750. Client cli(HOST, port);
  7751. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7752. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7753. EXPECT_EQ(StatusCode::OK_200, res->status);
  7754. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7755. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  7756. EXPECT_EQ(1048576U, res->body.size());
  7757. }
  7758. TEST_F(StaticFileCompressionTest, MountPoint) {
  7759. auto port = start(enable);
  7760. Client cli(HOST, port);
  7761. cli.set_decompress(false);
  7762. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7763. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7764. EXPECT_EQ(StatusCode::OK_200, res->status);
  7765. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7766. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7767. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  7768. // The response stays self-delimiting: a length, not a chunked body.
  7769. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  7770. EXPECT_EQ(std::to_string(res->body.size()),
  7771. res->get_header_value("Content-Length"));
  7772. EXPECT_LT(res->body.size(), 1048576U);
  7773. EXPECT_FALSE(res->body.empty());
  7774. }
  7775. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  7776. auto port = start(enable);
  7777. Client cli(HOST, port);
  7778. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7779. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7780. EXPECT_EQ(StatusCode::OK_200, res->status);
  7781. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7782. EXPECT_EQ(1048576U, res->body.size());
  7783. }
  7784. TEST_F(StaticFileCompressionTest, FileContent) {
  7785. auto port = start(enable_without_floor);
  7786. Client cli(HOST, port);
  7787. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  7788. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7789. EXPECT_EQ(StatusCode::OK_200, res->status);
  7790. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  7791. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7792. EXPECT_EQ(104U, res->body.size());
  7793. }
  7794. // A handler that serves an already-encoded file names the coding itself. The
  7795. // file-backed path decided its coding from Accept-Encoding and the content
  7796. // type alone, so it compressed the stored bytes a second time and appended a
  7797. // second Content-Encoding field line.
  7798. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  7799. auto port = start(enable_without_floor);
  7800. Client cli(HOST, port);
  7801. cli.set_decompress(false);
  7802. auto res = cli.Get("/pre-encoded-file-content",
  7803. Headers{{"Accept-Encoding", "gzip"}});
  7804. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7805. EXPECT_EQ(StatusCode::OK_200, res->status);
  7806. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  7807. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7808. // Vary belongs to a coding the server chose, and it chose none here.
  7809. EXPECT_FALSE(res->has_header("Vary"));
  7810. // The file travels exactly as it is stored on disk.
  7811. EXPECT_EQ(104U, res->body.size());
  7812. }
  7813. // The 1MB file clears the default floor, so this one runs the configuration a
  7814. // deployment would actually have.
  7815. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  7816. auto port = start(enable);
  7817. Client cli(HOST, port);
  7818. cli.set_decompress(false);
  7819. auto res =
  7820. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7821. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7822. EXPECT_EQ(StatusCode::OK_200, res->status);
  7823. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  7824. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7825. EXPECT_FALSE(res->has_header("Vary"));
  7826. EXPECT_EQ(1048576U, res->body.size());
  7827. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  7828. }
  7829. TEST_F(StaticFileCompressionTest, Head) {
  7830. auto port = start(enable);
  7831. Client cli(HOST, port);
  7832. cli.set_decompress(false);
  7833. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7834. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  7835. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7836. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7837. EXPECT_EQ(StatusCode::OK_200, res->status);
  7838. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7839. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  7840. // HEAD still reports the size a GET would return.
  7841. EXPECT_EQ(get->get_header_value("Content-Length"),
  7842. res->get_header_value("Content-Length"));
  7843. EXPECT_TRUE(res->body.empty());
  7844. }
  7845. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  7846. auto port = start(enable);
  7847. Client cli(HOST, port);
  7848. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  7849. {"Accept-Encoding", "gzip"}});
  7850. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7851. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7852. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7853. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7854. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  7855. EXPECT_EQ("cd", res->body);
  7856. }
  7857. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  7858. auto port = start(enable);
  7859. Client cli(HOST, port);
  7860. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  7861. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7862. EXPECT_EQ(StatusCode::OK_200, res->status);
  7863. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7864. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7865. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  7866. }
  7867. TEST_F(StaticFileCompressionTest, EmptyFile) {
  7868. auto port = start(enable);
  7869. Client cli(HOST, port);
  7870. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  7871. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7872. EXPECT_EQ(StatusCode::OK_200, res->status);
  7873. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7874. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7875. EXPECT_TRUE(res->body.empty());
  7876. }
  7877. TEST_F(StaticFileCompressionTest, MinLength) {
  7878. auto port = start(enable);
  7879. Client cli(HOST, port);
  7880. // 104 bytes, well under the default floor. Compressing it would add the
  7881. // gzip header and trailer to a body that already fits in one packet.
  7882. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  7883. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7884. EXPECT_EQ(StatusCode::OK_200, res->status);
  7885. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7886. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  7887. }
  7888. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  7889. auto port = start([](Server &svr) {
  7890. svr.set_static_file_compression(true);
  7891. svr.set_static_file_compression_min_length(1);
  7892. });
  7893. Client cli(HOST, port);
  7894. cli.set_decompress(false);
  7895. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  7896. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7897. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7898. // A 9-byte file comes back larger than it went in, because gzip's header and
  7899. // trailer outweigh anything deflate can save. That is the end of the range
  7900. // the floor exists to keep out.
  7901. EXPECT_GT(res->body.size(), 9U);
  7902. }
  7903. TEST_F(StaticFileCompressionTest, MaxLength) {
  7904. auto port = start([](Server &svr) {
  7905. svr.set_static_file_compression(true);
  7906. svr.set_static_file_compression_min_length(0);
  7907. svr.set_static_file_compression_max_length(1024);
  7908. });
  7909. Client cli(HOST, port);
  7910. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  7911. // defines `small` as a macro on Windows.
  7912. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7913. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  7914. EXPECT_FALSE(over->has_header("Content-Encoding"));
  7915. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  7916. // Under it: compressed.
  7917. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  7918. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  7919. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  7920. }
  7921. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  7922. auto port = start(enable_without_floor);
  7923. Client cli(HOST, port);
  7924. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  7925. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  7926. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  7927. auto identity_etag = identity->get_header_value("ETag");
  7928. ASSERT_FALSE(identity_etag.empty());
  7929. auto gzipped =
  7930. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  7931. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  7932. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  7933. auto gzip_etag = gzipped->get_header_value("ETag");
  7934. ASSERT_FALSE(gzip_etag.empty());
  7935. // Two representations, two validators.
  7936. EXPECT_NE(identity_etag, gzip_etag);
  7937. // Each one revalidates against the request that would produce it...
  7938. auto fresh =
  7939. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  7940. {"If-None-Match", gzip_etag}});
  7941. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  7942. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  7943. auto fresh_identity =
  7944. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  7945. {"If-None-Match", identity_etag}});
  7946. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  7947. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  7948. // ...and not against the other representation.
  7949. auto crossed =
  7950. cli.Get("/dir/index.html",
  7951. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  7952. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  7953. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  7954. }
  7955. // The opt-in covers responses the server reads off disk itself. A caller's own
  7956. // known-length provider keeps its Content-Length and, more importantly, keeps
  7957. // delivering incrementally: routing it through a compressor would hold every
  7958. // write back until zlib's window filled.
  7959. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  7960. auto port = start(enable);
  7961. Client cli(HOST, port);
  7962. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  7963. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7964. EXPECT_EQ(StatusCode::OK_200, res->status);
  7965. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7966. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7967. EXPECT_EQ("aaabbb", res->body);
  7968. }
  7969. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  7970. auto port = start(enable);
  7971. Client cli(HOST, port);
  7972. cli.set_read_timeout(1, 0);
  7973. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  7974. Headers{{"Accept-Encoding", "gzip"}});
  7975. ASSERT_TRUE(handle.is_valid());
  7976. // The provider writes 100 bytes and then stalls for longer than the read
  7977. // timeout. Those first bytes have to arrive anyway: run the response through
  7978. // a compressor and zlib holds them until its window fills, so the read would
  7979. // come back empty instead.
  7980. char buf[256];
  7981. auto n = handle.read(buf, sizeof(buf));
  7982. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  7983. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  7984. }
  7985. #endif
  7986. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7987. TEST_F(ServerTest, Brotli) {
  7988. Headers headers;
  7989. headers.emplace("Accept-Encoding", "br");
  7990. auto res = cli_.Get("/compress", headers);
  7991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7992. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  7993. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7994. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  7995. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7996. "7890123456789012345678901234567890",
  7997. res->body);
  7998. EXPECT_EQ(StatusCode::OK_200, res->status);
  7999. }
  8000. #endif
  8001. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8002. TEST_F(ServerTest, Zstd) {
  8003. Headers headers;
  8004. headers.emplace("Accept-Encoding", "zstd");
  8005. auto res = cli_.Get("/compress", headers);
  8006. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8007. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8008. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8009. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8010. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8011. "7890123456789012345678901234567890",
  8012. res->body);
  8013. EXPECT_EQ(StatusCode::OK_200, res->status);
  8014. }
  8015. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  8016. Headers headers;
  8017. headers.emplace("Accept-Encoding", "");
  8018. auto res = cli_.Get("/compress", headers);
  8019. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8020. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8021. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8022. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8023. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8024. "7890123456789012345678901234567890",
  8025. res->body);
  8026. EXPECT_EQ(StatusCode::OK_200, res->status);
  8027. }
  8028. TEST_F(ServerTest, ZstdWithContentReceiver) {
  8029. Headers headers;
  8030. headers.emplace("Accept-Encoding", "zstd");
  8031. std::string body;
  8032. auto res = cli_.Get("/compress", headers,
  8033. [&](const char *data, uint64_t data_length) {
  8034. EXPECT_EQ(100U, data_length);
  8035. body.append(data, data_length);
  8036. return true;
  8037. });
  8038. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8039. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8040. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8041. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8042. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8043. "7890123456789012345678901234567890",
  8044. body);
  8045. EXPECT_EQ(StatusCode::OK_200, res->status);
  8046. }
  8047. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  8048. Headers headers;
  8049. headers.emplace("Accept-Encoding", "zstd");
  8050. cli_.set_decompress(false);
  8051. auto res = cli_.Get("/compress", headers);
  8052. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  8053. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  8054. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  8055. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  8056. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8057. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8058. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8059. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8060. EXPECT_EQ(StatusCode::OK_200, res->status);
  8061. ASSERT_EQ(26U, res->body.size());
  8062. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  8063. 0);
  8064. }
  8065. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  8066. Headers headers;
  8067. headers.emplace("Accept-Encoding", "");
  8068. std::string body;
  8069. auto res = cli_.Get("/compress", headers,
  8070. [&](const char *data, uint64_t data_length) {
  8071. EXPECT_EQ(100U, data_length);
  8072. body.append(data, data_length);
  8073. return true;
  8074. });
  8075. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8076. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8077. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8078. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8079. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8080. "7890123456789012345678901234567890",
  8081. body);
  8082. EXPECT_EQ(StatusCode::OK_200, res->status);
  8083. }
  8084. TEST_F(ServerTest, NoZstd) {
  8085. Headers headers;
  8086. headers.emplace("Accept-Encoding", "zstd");
  8087. auto res = cli_.Get("/nocompress", headers);
  8088. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8089. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8090. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8091. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8092. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8093. "7890123456789012345678901234567890",
  8094. res->body);
  8095. EXPECT_EQ(StatusCode::OK_200, res->status);
  8096. }
  8097. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  8098. Headers headers;
  8099. headers.emplace("Accept-Encoding", "zstd");
  8100. std::string body;
  8101. auto res = cli_.Get("/nocompress", headers,
  8102. [&](const char *data, uint64_t data_length) {
  8103. EXPECT_EQ(100U, data_length);
  8104. body.append(data, data_length);
  8105. return true;
  8106. });
  8107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8108. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8109. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8110. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8111. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8112. "7890123456789012345678901234567890",
  8113. body);
  8114. EXPECT_EQ(StatusCode::OK_200, res->status);
  8115. }
  8116. // TODO: How to enable zstd ??
  8117. TEST_F(ServerTest, MultipartFormDataZstd) {
  8118. UploadFormDataItems items = {
  8119. {"key1", "test", "", ""},
  8120. {"key2", "--abcdefg123", "", ""},
  8121. };
  8122. Headers headers;
  8123. headers.emplace("Accept-Encoding", "zstd");
  8124. cli_.set_compress(true);
  8125. auto res = cli_.Post("/compress-multipart", headers, items);
  8126. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8127. EXPECT_EQ(StatusCode::OK_200, res->status);
  8128. }
  8129. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  8130. Headers headers;
  8131. headers.emplace("Accept-Encoding", "zstd");
  8132. cli_.set_compress(true);
  8133. auto res = cli_.Put(
  8134. "/put", headers, 3,
  8135. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8136. sink.os << "PUT";
  8137. return true;
  8138. },
  8139. "text/plain");
  8140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8141. EXPECT_EQ(StatusCode::OK_200, res->status);
  8142. EXPECT_EQ("PUT", res->body);
  8143. }
  8144. // Pre-compression logging tests
  8145. TEST_F(ServerTest, PreCompressionLogging) {
  8146. // Test data for compression (matches the actual /compress endpoint content)
  8147. const std::string test_content =
  8148. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8149. "3456789012345678901234567890";
  8150. // Variables to capture logging data
  8151. std::string pre_compression_body;
  8152. std::string pre_compression_content_type;
  8153. std::string pre_compression_content_encoding;
  8154. std::string post_compression_body;
  8155. std::string post_compression_content_type;
  8156. std::string post_compression_content_encoding;
  8157. // Set up pre-compression logger
  8158. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  8159. const Response &res) {
  8160. pre_compression_body = res.body;
  8161. pre_compression_content_type = res.get_header_value("Content-Type");
  8162. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  8163. });
  8164. // Set up post-compression logger
  8165. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8166. post_compression_body = res.body;
  8167. post_compression_content_type = res.get_header_value("Content-Type");
  8168. post_compression_content_encoding =
  8169. res.get_header_value("Content-Encoding");
  8170. });
  8171. // Test with gzip compression
  8172. Headers headers;
  8173. headers.emplace("Accept-Encoding", "gzip");
  8174. auto res = cli_.Get("/compress", headers);
  8175. // Verify response was compressed
  8176. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8177. EXPECT_EQ(StatusCode::OK_200, res->status);
  8178. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8179. // Verify pre-compression logger captured uncompressed content
  8180. EXPECT_EQ(test_content, pre_compression_body);
  8181. EXPECT_EQ("text/plain", pre_compression_content_type);
  8182. EXPECT_TRUE(pre_compression_content_encoding
  8183. .empty()); // No encoding header before compression
  8184. // Verify post-compression logger captured compressed content
  8185. EXPECT_NE(test_content,
  8186. post_compression_body); // Should be different after compression
  8187. EXPECT_EQ("text/plain", post_compression_content_type);
  8188. EXPECT_EQ("gzip", post_compression_content_encoding);
  8189. // Verify compressed content is smaller
  8190. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8191. }
  8192. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  8193. const std::string test_content =
  8194. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8195. "3456789012345678901234567890";
  8196. std::string pre_compression_body;
  8197. std::string post_compression_body;
  8198. svr_.set_pre_compression_logger(
  8199. [&](const Request & /*req*/, const Response &res) {
  8200. pre_compression_body = res.body;
  8201. });
  8202. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8203. post_compression_body = res.body;
  8204. });
  8205. Headers headers;
  8206. headers.emplace("Accept-Encoding", "br");
  8207. auto res = cli_.Get("/compress", headers);
  8208. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8209. EXPECT_EQ(StatusCode::OK_200, res->status);
  8210. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8211. // Verify pre-compression content is uncompressed
  8212. EXPECT_EQ(test_content, pre_compression_body);
  8213. // Verify post-compression content is compressed
  8214. EXPECT_NE(test_content, post_compression_body);
  8215. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8216. }
  8217. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  8218. const std::string test_content =
  8219. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8220. "3456789012345678901234567890";
  8221. std::string pre_compression_body;
  8222. std::string post_compression_body;
  8223. svr_.set_pre_compression_logger(
  8224. [&](const Request & /*req*/, const Response &res) {
  8225. pre_compression_body = res.body;
  8226. });
  8227. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8228. post_compression_body = res.body;
  8229. });
  8230. // Request without compression (use /nocompress endpoint)
  8231. Headers headers;
  8232. auto res = cli_.Get("/nocompress", headers);
  8233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8234. EXPECT_EQ(StatusCode::OK_200, res->status);
  8235. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8236. // Pre-compression logger should not be called when no compression is applied
  8237. EXPECT_TRUE(
  8238. pre_compression_body.empty()); // Pre-compression logger not called
  8239. EXPECT_EQ(
  8240. test_content,
  8241. post_compression_body); // Post-compression logger captures final content
  8242. }
  8243. TEST_F(ServerTest, LoggerSeesContentLength) {
  8244. size_t logged_content_length = 0;
  8245. std::string logged_content_length_header;
  8246. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8247. logged_content_length = res.content_length_;
  8248. logged_content_length_header = res.get_header_value("Content-Length");
  8249. });
  8250. auto res = cli_.Get("/nocompress");
  8251. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8252. EXPECT_EQ(StatusCode::OK_200, res->status);
  8253. EXPECT_EQ(res->body.size(), logged_content_length);
  8254. EXPECT_EQ(std::to_string(logged_content_length),
  8255. logged_content_length_header);
  8256. }
  8257. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  8258. const std::string test_content =
  8259. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8260. "3456789012345678901234567890";
  8261. std::string pre_compression_body;
  8262. bool pre_logger_called = false;
  8263. // Set only pre-compression logger
  8264. svr_.set_pre_compression_logger(
  8265. [&](const Request & /*req*/, const Response &res) {
  8266. pre_compression_body = res.body;
  8267. pre_logger_called = true;
  8268. });
  8269. Headers headers;
  8270. headers.emplace("Accept-Encoding", "gzip");
  8271. auto res = cli_.Get("/compress", headers);
  8272. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8273. EXPECT_EQ(StatusCode::OK_200, res->status);
  8274. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8275. // Verify pre-compression logger was called
  8276. EXPECT_TRUE(pre_logger_called);
  8277. EXPECT_EQ(test_content, pre_compression_body);
  8278. }
  8279. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  8280. {
  8281. // Test with Expect: 100-continue header - success case
  8282. // Server returns 100 Continue, client sends body, server returns 200 OK
  8283. Request req;
  8284. req.method = "POST";
  8285. req.path = "/post-large";
  8286. req.set_header("Expect", "100-continue");
  8287. req.body = LARGE_DATA;
  8288. Response res;
  8289. auto error = Error::Success;
  8290. cli_.set_keep_alive(true);
  8291. auto ret = cli_.send(req, res, error);
  8292. EXPECT_TRUE(ret);
  8293. EXPECT_EQ(StatusCode::OK_200, res.status);
  8294. EXPECT_EQ(LARGE_DATA, res.body);
  8295. }
  8296. {
  8297. // Test with Expect: 100-continue header - error case
  8298. // Client should not send the body when server returns an error
  8299. Request req;
  8300. req.method = "POST";
  8301. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  8302. req.set_header("Expect", "100-continue");
  8303. req.body = LARGE_DATA;
  8304. Response res;
  8305. auto error = Error::Success;
  8306. auto start = std::chrono::high_resolution_clock::now();
  8307. cli_.set_keep_alive(true);
  8308. auto ret = cli_.send(req, res, error);
  8309. auto end = std::chrono::high_resolution_clock::now();
  8310. auto elapsed =
  8311. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8312. .count();
  8313. // With Expect: 100-continue, request completes successfully but with error
  8314. EXPECT_TRUE(ret);
  8315. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  8316. EXPECT_EQ("close", res.get_header_value("Connection"));
  8317. EXPECT_FALSE(cli_.is_socket_open());
  8318. EXPECT_LE(elapsed, 2000);
  8319. }
  8320. {
  8321. // Send an extra GET request to ensure error recovery without hanging
  8322. Request req;
  8323. req.method = "GET";
  8324. req.path = "/hi";
  8325. auto start = std::chrono::high_resolution_clock::now();
  8326. auto res = cli_.send(req);
  8327. auto end = std::chrono::high_resolution_clock::now();
  8328. auto elapsed =
  8329. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8330. .count();
  8331. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8332. EXPECT_EQ(StatusCode::OK_200, res->status);
  8333. EXPECT_EQ("Hello World!", res->body);
  8334. EXPECT_LE(elapsed, 500);
  8335. }
  8336. }
  8337. TEST(ZstdDecompressor, ChunkedDecompression) {
  8338. std::string data;
  8339. for (size_t i = 0; i < 32 * 1024; ++i) {
  8340. data.push_back(static_cast<char>('a' + i % 26));
  8341. }
  8342. std::string compressed_data;
  8343. {
  8344. httplib::detail::zstd_compressor compressor;
  8345. bool result = compressor.compress(
  8346. data.data(), data.size(),
  8347. /*last=*/true,
  8348. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  8349. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  8350. compressed_data_size);
  8351. return true;
  8352. });
  8353. ASSERT_TRUE(result);
  8354. }
  8355. std::string decompressed_data;
  8356. {
  8357. httplib::detail::zstd_decompressor decompressor;
  8358. // Chunk size is chosen specifically to have a decompressed chunk size equal
  8359. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  8360. size_t chunk_size = 130;
  8361. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  8362. chunk_begin += chunk_size) {
  8363. size_t current_chunk_size =
  8364. std::min(compressed_data.size() - chunk_begin, chunk_size);
  8365. bool result = decompressor.decompress(
  8366. compressed_data.data() + chunk_begin, current_chunk_size,
  8367. [&](const char *decompressed_data_chunk,
  8368. size_t decompressed_data_chunk_size) {
  8369. decompressed_data.insert(decompressed_data.size(),
  8370. decompressed_data_chunk,
  8371. decompressed_data_chunk_size);
  8372. return true;
  8373. });
  8374. ASSERT_TRUE(result);
  8375. }
  8376. }
  8377. ASSERT_EQ(data, decompressed_data);
  8378. }
  8379. TEST(ZstdDecompressor, Decompress) {
  8380. std::string original_text = "Compressed with ZSTD";
  8381. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  8382. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  8383. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  8384. 0x20, 0x5a, 0x53, 0x54, 0x44};
  8385. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8386. std::string decompressed_data;
  8387. {
  8388. httplib::detail::zstd_decompressor decompressor;
  8389. bool result = decompressor.decompress(
  8390. compressed_data.data(), compressed_data.size(),
  8391. [&](const char *decompressed_data_chunk,
  8392. size_t decompressed_data_chunk_size) {
  8393. decompressed_data.insert(decompressed_data.size(),
  8394. decompressed_data_chunk,
  8395. decompressed_data_chunk_size);
  8396. return true;
  8397. });
  8398. ASSERT_TRUE(result);
  8399. }
  8400. ASSERT_EQ(original_text, decompressed_data);
  8401. }
  8402. #endif
  8403. // Sends a raw request to a server listening at HOST:PORT, writing it in
  8404. // separate chunks so that the server sees each part in its own read(). Used to
  8405. // place a read boundary at a specific offset of a request body.
  8406. static bool send_request_in_parts(time_t read_timeout_sec,
  8407. const std::vector<std::string> &parts,
  8408. std::string *resp = nullptr,
  8409. int port = PORT) {
  8410. auto error = Error::Success;
  8411. auto client_sock = detail::create_client_socket(
  8412. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  8413. /*connection_timeout_sec=*/5, 0,
  8414. /*read_timeout_sec=*/5, 0,
  8415. /*write_timeout_sec=*/5, 0, std::string(), error);
  8416. if (client_sock == INVALID_SOCKET) { return false; }
  8417. auto ret = detail::process_client_socket(
  8418. client_sock, read_timeout_sec, 0, 0, 0, 0,
  8419. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  8420. for (size_t i = 0; i < parts.size(); i++) {
  8421. const auto &part = parts[i];
  8422. if (part.size() !=
  8423. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  8424. return false;
  8425. }
  8426. if (i + 1 < parts.size()) {
  8427. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8428. }
  8429. }
  8430. char buf[512];
  8431. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  8432. while (line_reader.getline()) {
  8433. if (resp) { *resp += line_reader.ptr(); }
  8434. }
  8435. return true;
  8436. });
  8437. detail::close_socket(client_sock);
  8438. return ret;
  8439. }
  8440. // Sends a raw request to a server listening at HOST:PORT.
  8441. static bool send_request(time_t read_timeout_sec, const std::string &req,
  8442. std::string *resp = nullptr, int port = PORT) {
  8443. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  8444. }
  8445. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  8446. Server svr;
  8447. std::string header_value;
  8448. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  8449. header_value = req.get_header_value("foo");
  8450. res.set_content("ok", "text/plain");
  8451. });
  8452. thread t = thread([&] { svr.listen(HOST, PORT); });
  8453. auto se = detail::scope_exit([&] {
  8454. svr.stop();
  8455. t.join();
  8456. ASSERT_FALSE(svr.is_running());
  8457. });
  8458. svr.wait_until_ready();
  8459. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  8460. // like characters are not treated the same - use vertical tab and escape.
  8461. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  8462. "foo: \t \v bar \x1B\t \r\n"
  8463. "Connection: close\r\n"
  8464. "\r\n";
  8465. std::string res;
  8466. ASSERT_TRUE(send_request(5, req, &res));
  8467. EXPECT_EQ(header_value, "");
  8468. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  8469. }
  8470. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  8471. Server svr;
  8472. std::string received;
  8473. svr.Get("/order", [&](const Request &req, Response &res) {
  8474. received = entries_to_string(req.headers);
  8475. res.set_content("ok", "text/plain");
  8476. });
  8477. auto port = svr.bind_to_any_port(HOST);
  8478. thread t = thread([&] { svr.listen_after_bind(); });
  8479. auto se = detail::scope_exit([&] {
  8480. svr.stop();
  8481. t.join();
  8482. ASSERT_FALSE(svr.is_running());
  8483. });
  8484. svr.wait_until_ready();
  8485. const std::string req = "GET /order HTTP/1.1\r\n"
  8486. "X-First: 1\r\n"
  8487. "X-Dup: a\r\n"
  8488. "X-Second: 2\r\n"
  8489. "X-Dup: b\r\n"
  8490. "Connection: close\r\n"
  8491. "\r\n";
  8492. std::string res;
  8493. ASSERT_TRUE(send_request(5, req, &res, port));
  8494. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8495. EXPECT_EQ("X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ", received);
  8496. }
  8497. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  8498. Server svr;
  8499. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  8500. res.set_header("Set-Cookie", "first=1");
  8501. res.set_header("X-Between", "y");
  8502. res.set_header("Set-Cookie", "second=2");
  8503. res.set_content("ok", "text/plain");
  8504. });
  8505. auto port = svr.bind_to_any_port(HOST);
  8506. thread t = thread([&] { svr.listen_after_bind(); });
  8507. auto se = detail::scope_exit([&] {
  8508. svr.stop();
  8509. t.join();
  8510. ASSERT_FALSE(svr.is_running());
  8511. });
  8512. svr.wait_until_ready();
  8513. Client cli(HOST, port);
  8514. auto res = cli.Get("/cookies");
  8515. ASSERT_TRUE(res);
  8516. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  8517. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  8518. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  8519. }
  8520. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  8521. Server svr;
  8522. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  8523. auto i = new int(0);
  8524. res.set_header("Trailer", "X-Safe, X-Reflected");
  8525. res.set_chunked_content_provider(
  8526. "text/plain",
  8527. [i](size_t /*offset*/, DataSink &sink) {
  8528. if (*i == 0) {
  8529. sink.os << "body";
  8530. } else {
  8531. Headers trailer;
  8532. // A valid trailer that must survive.
  8533. trailer.emplace("X-Safe", "safe");
  8534. // Attacker-controlled value carrying CR/LF (response splitting).
  8535. trailer.emplace("X-Reflected",
  8536. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8537. // Attacker-controlled name carrying CR/LF.
  8538. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8539. sink.done_with_trailer(trailer);
  8540. }
  8541. (*i)++;
  8542. return true;
  8543. },
  8544. [i](bool /*success*/) { delete i; });
  8545. });
  8546. thread t = thread([&] { svr.listen(HOST, PORT); });
  8547. auto se = detail::scope_exit([&] {
  8548. svr.stop();
  8549. t.join();
  8550. ASSERT_FALSE(svr.is_running());
  8551. });
  8552. svr.wait_until_ready();
  8553. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  8554. "Host: " + HOST +
  8555. "\r\n"
  8556. "Connection: close\r\n"
  8557. "\r\n";
  8558. std::string res;
  8559. ASSERT_TRUE(send_request(5, req, &res));
  8560. // The injected fields must not appear anywhere in the raw response.
  8561. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8562. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8563. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8564. // Invalid trailers are dropped entirely, matching set_header().
  8565. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8566. // The valid trailer still passes through.
  8567. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8568. }
  8569. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  8570. Server svr;
  8571. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  8572. // res.headers is a public field an application can populate directly,
  8573. // bypassing set_header()'s validation (e.g. reflecting a request value).
  8574. // A valid header that must survive.
  8575. res.headers.emplace("X-Safe", "safe");
  8576. // Attacker-controlled value carrying CR/LF (response splitting).
  8577. res.headers.emplace("X-Reflected",
  8578. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8579. // Attacker-controlled name carrying CR/LF.
  8580. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8581. res.set_content("body", "text/plain");
  8582. });
  8583. thread t = thread([&] { svr.listen(HOST, PORT); });
  8584. auto se = detail::scope_exit([&] {
  8585. svr.stop();
  8586. t.join();
  8587. ASSERT_FALSE(svr.is_running());
  8588. });
  8589. svr.wait_until_ready();
  8590. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  8591. "Host: " + HOST +
  8592. "\r\n"
  8593. "Connection: close\r\n"
  8594. "\r\n";
  8595. std::string res;
  8596. ASSERT_TRUE(send_request(5, req, &res));
  8597. // The injected fields must not appear anywhere in the raw response.
  8598. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8599. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8600. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8601. // Invalid headers are dropped entirely, matching set_header().
  8602. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8603. // The valid header still passes through.
  8604. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8605. }
  8606. // Forward declaration: in split builds split.py strips `inline` and moves the
  8607. // definition into httplib.cc, so detail::write_request_line is not visible from
  8608. // the public httplib.h. Re-declaring it here lets the tests link against the
  8609. // symbol in both header-only and split builds.
  8610. namespace httplib {
  8611. namespace detail {
  8612. ssize_t write_request_line(Stream &strm, const std::string &method,
  8613. const std::string &path);
  8614. } // namespace detail
  8615. } // namespace httplib
  8616. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  8617. // A well-formed target is written verbatim.
  8618. {
  8619. detail::BufferStream strm;
  8620. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  8621. EXPECT_GT(n, 0);
  8622. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  8623. }
  8624. // A target carrying CR/LF, SP or other control octets must be rejected
  8625. // before anything reaches the wire, otherwise it splits the request line and
  8626. // injects a header or a whole request. This is what a decoded redirect
  8627. // Location ("%0D%0A") turns into when path encoding is disabled.
  8628. const std::string evil_targets[] = {
  8629. "/a\r\nInjected: pwned",
  8630. "/a\rInjected",
  8631. "/a\nInjected",
  8632. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  8633. "/a b",
  8634. "/a\tb",
  8635. "/a\x7f",
  8636. };
  8637. for (const auto &evil : evil_targets) {
  8638. detail::BufferStream strm;
  8639. auto n = detail::write_request_line(strm, "GET", evil);
  8640. EXPECT_LT(n, 0);
  8641. EXPECT_TRUE(strm.get_buffer().empty());
  8642. }
  8643. }
  8644. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  8645. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  8646. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  8647. // target -- what a redirect Location "%0D%0A" decodes to -- reaches
  8648. // write_request. The client must fail cleanly with Error::Write instead of
  8649. // putting a request-line-less, header-injecting request on the wire.
  8650. Server svr;
  8651. svr.Get("/a", [](const Request &, Response &res) {
  8652. res.set_content("ok", "text/plain");
  8653. });
  8654. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8655. auto se = detail::scope_exit([&] {
  8656. svr.stop();
  8657. thread.join();
  8658. ASSERT_FALSE(svr.is_running());
  8659. });
  8660. svr.wait_until_ready();
  8661. {
  8662. Client cli(HOST, PORT);
  8663. cli.set_path_encode(false);
  8664. // The request is rejected before anything is written, so the connection
  8665. // stays silent and the subsequent response read would otherwise block for
  8666. // the full default read timeout. Shorten it -- the assertion is on the
  8667. // error, not the timeout.
  8668. cli.set_read_timeout(1, 0);
  8669. auto res = cli.Get("/a\r\nInjected: pwned");
  8670. EXPECT_FALSE(res);
  8671. EXPECT_EQ(Error::Write, res.error());
  8672. }
  8673. }
  8674. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  8675. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  8676. // including extension methods.
  8677. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  8678. for (const auto &method : good_methods) {
  8679. detail::BufferStream strm;
  8680. auto n = detail::write_request_line(strm, method, "/");
  8681. EXPECT_GT(n, 0);
  8682. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  8683. }
  8684. // A method carrying CR/LF would split the request line and smuggle a whole
  8685. // request ahead of the real one. A space or an empty method corrupts the
  8686. // request line. All must be rejected before anything reaches the wire.
  8687. const std::string evil_methods[] = {
  8688. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  8689. "GET\r\nInjected: pwned",
  8690. "GET\r",
  8691. "GET\n",
  8692. "GE T",
  8693. "",
  8694. };
  8695. for (const auto &evil : evil_methods) {
  8696. detail::BufferStream strm;
  8697. auto n = detail::write_request_line(strm, evil, "/");
  8698. EXPECT_LT(n, 0);
  8699. EXPECT_TRUE(strm.get_buffer().empty());
  8700. }
  8701. }
  8702. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  8703. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  8704. // through Client::send must fail with Error::Write and no request, neither
  8705. // the smuggled one nor the real one, may reach the server.
  8706. Server svr;
  8707. std::atomic<int> request_count(0);
  8708. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  8709. request_count++;
  8710. res.status = StatusCode::OK_200;
  8711. return Server::HandlerResponse::Handled;
  8712. });
  8713. auto port = svr.bind_to_any_port(HOST);
  8714. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  8715. auto se = detail::scope_exit([&] {
  8716. svr.stop();
  8717. thread.join();
  8718. ASSERT_FALSE(svr.is_running());
  8719. });
  8720. svr.wait_until_ready();
  8721. {
  8722. Client cli(HOST, port);
  8723. const std::string evil_methods[] = {
  8724. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  8725. "GE T",
  8726. "",
  8727. };
  8728. for (const auto &evil : evil_methods) {
  8729. Request req;
  8730. req.method = evil;
  8731. req.path = "/";
  8732. auto res = cli.send(req);
  8733. EXPECT_FALSE(res);
  8734. EXPECT_EQ(Error::Write, res.error());
  8735. }
  8736. auto handle =
  8737. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  8738. EXPECT_FALSE(handle.is_valid());
  8739. EXPECT_EQ(Error::Write, handle.error);
  8740. // A valid request on the same client still goes through.
  8741. auto res = cli.Get("/");
  8742. ASSERT_TRUE(res);
  8743. EXPECT_EQ(StatusCode::OK_200, res->status);
  8744. }
  8745. EXPECT_EQ(1, request_count.load());
  8746. }
  8747. // Sends a raw request and verifies that there isn't a crash or exception.
  8748. static void test_raw_request(const std::string &req,
  8749. std::string *out = nullptr) {
  8750. Server svr;
  8751. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  8752. res.set_content("ok", "text/plain");
  8753. });
  8754. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  8755. res.set_content("ok", "text/plain");
  8756. });
  8757. svr.Get("/header_field_value_check",
  8758. [&](const Request & /*req*/, Response &res) {
  8759. res.set_content("ok", "text/plain");
  8760. });
  8761. svr.CustomRoute("PROPFIND", "/dav",
  8762. [&](const Request & /*req*/, Response &res) {
  8763. res.status = StatusCode::MultiStatus_207;
  8764. });
  8765. // Server read timeout must be longer than the client read timeout for the
  8766. // bug to reproduce, probably to force the server to process a request
  8767. // without a trailing blank line.
  8768. const time_t client_read_timeout_sec = 1;
  8769. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  8770. bool listen_thread_ok = false;
  8771. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  8772. auto se = detail::scope_exit([&] {
  8773. svr.stop();
  8774. t.join();
  8775. ASSERT_FALSE(svr.is_running());
  8776. EXPECT_TRUE(listen_thread_ok);
  8777. });
  8778. svr.wait_until_ready();
  8779. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  8780. }
  8781. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  8782. // A certain header line causes an exception if the header property is parsed
  8783. // naively with a single regex. This occurs with libc++ but not libstdc++.
  8784. test_raw_request(
  8785. "GET /hi HTTP/1.1\r\n"
  8786. " : "
  8787. " "
  8788. " ");
  8789. }
  8790. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  8791. // A certain header line causes an exception if the header property *name* is
  8792. // parsed with a regular expression starting with "(.+?):" - this is a non-
  8793. // greedy matcher and requires backtracking when there are a lot of ":"
  8794. // characters.
  8795. // This occurs with libc++ but not libstdc++.
  8796. test_raw_request(
  8797. "GET /hi HTTP/1.1\r\n"
  8798. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  8799. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  8800. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  8801. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  8802. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  8803. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  8804. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  8805. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  8806. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  8807. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  8808. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  8809. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  8810. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  8811. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  8812. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  8813. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  8814. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  8815. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  8816. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  8817. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  8818. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  8819. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  8820. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  8821. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  8822. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  8823. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  8824. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  8825. "&&&%%%");
  8826. }
  8827. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  8828. // Make sure this doesn't crash the server.
  8829. // In a previous version of the header line regex, the "\r" rendered the line
  8830. // unparsable and the regex engine repeatedly backtracked, trying to look for
  8831. // a new position where the leading white space ended and the field value
  8832. // began.
  8833. // The crash occurs with libc++ but not libstdc++.
  8834. test_raw_request("GET /hi HTTP/1.1\r\n"
  8835. "a:" +
  8836. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  8837. "\r\n"
  8838. "\r\n");
  8839. }
  8840. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  8841. std::string out;
  8842. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  8843. "Content-Type: text/plain\r\n"
  8844. "Transfer-Encoding: chunked\r\n"
  8845. "\r\n"
  8846. "nothex\r\n",
  8847. &out);
  8848. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8849. }
  8850. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  8851. std::string out;
  8852. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  8853. "Content-Type: text/plain\r\n"
  8854. "Transfer-Encoding: chunked\r\n"
  8855. "\r\n"
  8856. "3\r\n"
  8857. "xyz\r\n"
  8858. "NaN\r\n",
  8859. &out);
  8860. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8861. }
  8862. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  8863. std::string out;
  8864. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  8865. "Content-Type: text/plain\r\n"
  8866. "Transfer-Encoding: chunked\r\n"
  8867. "\r\n"
  8868. // Length is too large for 64 bits.
  8869. "1ffffffffffffffff\r\n"
  8870. "xyz\r\n",
  8871. &out);
  8872. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8873. }
  8874. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  8875. test_raw_request("GET /hi HTTP/1.1\r\n"
  8876. "Content-Type: text/plain\r\n\r");
  8877. }
  8878. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  8879. std::string out;
  8880. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  8881. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8882. }
  8883. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  8884. for (auto target : {"/h\ri", "/h\x7fi"}) {
  8885. std::string out;
  8886. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  8887. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  8888. }
  8889. }
  8890. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  8891. std::string out;
  8892. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  8893. "Connection: close\r\n\r\n",
  8894. &out);
  8895. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  8896. }
  8897. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  8898. Server svr;
  8899. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  8900. EXPECT_TRUE(!req.remote_addr.empty());
  8901. });
  8902. thread t = thread([&] { svr.listen(HOST, PORT); });
  8903. auto se = detail::scope_exit([&] {
  8904. svr.stop();
  8905. t.join();
  8906. ASSERT_FALSE(svr.is_running());
  8907. });
  8908. svr.wait_until_ready();
  8909. // Send an invalid request line to trigger Bad Request
  8910. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  8911. std::string out;
  8912. ASSERT_TRUE(send_request(5, bad_req, &out));
  8913. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8914. }
  8915. // A custom method with neither Content-Length nor Transfer-Encoding must be
  8916. // answered right away rather than blocking on a read that waits for EOF.
  8917. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  8918. std::string out;
  8919. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  8920. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  8921. }
  8922. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  8923. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  8924. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  8925. for (const auto *method : methods) {
  8926. Server svr;
  8927. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  8928. EXPECT_FALSE(svr.is_valid()) << method;
  8929. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  8930. }
  8931. }
  8932. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  8933. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  8934. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  8935. for (const auto *method : methods) {
  8936. Server svr;
  8937. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  8938. EXPECT_FALSE(svr.is_valid()) << method;
  8939. }
  8940. }
  8941. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  8942. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  8943. "COPY", "MOVE", "LOCK",
  8944. "UNLOCK", "REPORT", "SUBSCRIBE"};
  8945. Server svr;
  8946. for (const auto *method : methods) {
  8947. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  8948. }
  8949. EXPECT_TRUE(svr.is_valid());
  8950. }
  8951. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  8952. Server svr;
  8953. svr.CustomRoute("POST", "/x",
  8954. [](const Request &, Response &, const ContentReader &) {});
  8955. EXPECT_FALSE(svr.is_valid());
  8956. }
  8957. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  8958. Server svr;
  8959. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  8960. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  8961. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  8962. EXPECT_FALSE(svr.is_valid());
  8963. }
  8964. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  8965. Server svr;
  8966. auto captured = Error::Success;
  8967. svr.set_error_logger(
  8968. [&](const Error &err, const Request * /*req*/) { captured = err; });
  8969. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  8970. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  8971. }
  8972. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  8973. std::string out;
  8974. std::string request(
  8975. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  8976. test_raw_request(request, &out);
  8977. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8978. }
  8979. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  8980. std::string out;
  8981. std::string request(
  8982. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  8983. test_raw_request(request, &out);
  8984. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8985. }
  8986. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  8987. std::string out;
  8988. std::string request(
  8989. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  8990. test_raw_request(request, &out);
  8991. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8992. }
  8993. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  8994. std::string out;
  8995. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  8996. "Test: \r\n\r\n",
  8997. &out);
  8998. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  8999. }
  9000. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  9001. Server svr;
  9002. std::string x_custom;
  9003. std::string cookie;
  9004. std::string xff;
  9005. std::string x_unicode;
  9006. std::string x_iis;
  9007. svr.Get("/check", [&](const Request &req, Response &res) {
  9008. x_custom = req.get_header_value("X-Custom");
  9009. cookie = req.get_header_value("Cookie");
  9010. xff = req.get_header_value("X-Forwarded-For");
  9011. x_unicode = req.get_header_value("X-Unicode");
  9012. x_iis = req.get_header_value("X-IIS");
  9013. res.set_content("ok", "text/plain");
  9014. });
  9015. thread t = thread([&] { svr.listen(HOST, PORT); });
  9016. auto se = detail::scope_exit([&] {
  9017. svr.stop();
  9018. t.join();
  9019. ASSERT_FALSE(svr.is_running());
  9020. });
  9021. svr.wait_until_ready();
  9022. const std::string req = "GET /check HTTP/1.1\r\n"
  9023. "Host: localhost\r\n"
  9024. "X-Custom: a%0D%0AInjected: b\r\n"
  9025. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  9026. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  9027. "X-Unicode: %E3%81%82\r\n"
  9028. "X-IIS: %u00E9\r\n"
  9029. "Connection: close\r\n"
  9030. "\r\n";
  9031. std::string res;
  9032. ASSERT_TRUE(send_request(5, req, &res));
  9033. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9034. // Every value must be returned verbatim (wire form), with no decoding.
  9035. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  9036. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  9037. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  9038. EXPECT_EQ("%E3%81%82", x_unicode);
  9039. EXPECT_EQ("%u00E9", x_iis);
  9040. }
  9041. // Applications that previously relied on automatic percent-decoding can
  9042. // reproduce the old behavior by explicitly calling decode_path_component()
  9043. // or, for RFC 3986 conformance, decode_uri_component().
  9044. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  9045. Server svr;
  9046. std::string decoded;
  9047. svr.Get("/check", [&](const Request &req, Response &res) {
  9048. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  9049. res.set_content("ok", "text/plain");
  9050. });
  9051. thread t = thread([&] { svr.listen(HOST, PORT); });
  9052. auto se = detail::scope_exit([&] {
  9053. svr.stop();
  9054. t.join();
  9055. ASSERT_FALSE(svr.is_running());
  9056. });
  9057. svr.wait_until_ready();
  9058. const std::string req = "GET /check HTTP/1.1\r\n"
  9059. "Host: localhost\r\n"
  9060. "X-Custom: hello%20world\r\n"
  9061. "Connection: close\r\n"
  9062. "\r\n";
  9063. std::string res;
  9064. ASSERT_TRUE(send_request(5, req, &res));
  9065. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9066. EXPECT_EQ("hello world", decoded);
  9067. }
  9068. // Regression test for #2033. Browsers send Referer values that include
  9069. // percent-encoded characters such as %0A inside the URL. Decoding the
  9070. // header value would either trip the post-decode CR/LF/NUL guard (the
  9071. // original bug, returning 400) or, after that guard was relaxed, silently
  9072. // store a literal LF — both unacceptable. The wire form must round-trip.
  9073. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  9074. Server svr;
  9075. std::string referer;
  9076. svr.Get("/check", [&](const Request &req, Response &res) {
  9077. referer = req.get_header_value("Referer");
  9078. res.set_content("ok", "text/plain");
  9079. });
  9080. thread t = thread([&] { svr.listen(HOST, PORT); });
  9081. auto se = detail::scope_exit([&] {
  9082. svr.stop();
  9083. t.join();
  9084. ASSERT_FALSE(svr.is_running());
  9085. });
  9086. svr.wait_until_ready();
  9087. const std::string req = "GET /check HTTP/1.1\r\n"
  9088. "Host: localhost\r\n"
  9089. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  9090. "Connection: close\r\n"
  9091. "\r\n";
  9092. std::string res;
  9093. ASSERT_TRUE(send_request(5, req, &res));
  9094. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9095. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  9096. }
  9097. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  9098. Server svr;
  9099. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  9100. res.set_header("Cache-Control", "no-cache");
  9101. res.set_chunked_content_provider(
  9102. "text/event-stream", [](size_t offset, DataSink &sink) {
  9103. std::string s = "data:";
  9104. s += std::to_string(offset);
  9105. s += "\n\n";
  9106. auto ret = sink.write(s.data(), s.size());
  9107. EXPECT_TRUE(ret);
  9108. std::this_thread::sleep_for(std::chrono::seconds(1));
  9109. return true;
  9110. });
  9111. });
  9112. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9113. svr.wait_until_ready();
  9114. Client client(HOST, PORT);
  9115. const Headers headers = {{"Accept", "text/event-stream"}};
  9116. auto get_thread = std::thread([&client, &headers]() {
  9117. auto res = client.Get(
  9118. "/events", headers,
  9119. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  9120. });
  9121. auto se = detail::scope_exit([&] {
  9122. svr.stop();
  9123. get_thread.join();
  9124. listen_thread.join();
  9125. ASSERT_FALSE(svr.is_running());
  9126. });
  9127. // Give GET time to get a few messages.
  9128. std::this_thread::sleep_for(std::chrono::seconds(2));
  9129. }
  9130. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  9131. httplib::Server svr;
  9132. svr.Post("/hi",
  9133. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  9134. res.status = StatusCode::OK_200;
  9135. });
  9136. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9137. svr.wait_until_ready();
  9138. Client cli(HOST, PORT);
  9139. auto res = cli.Post("/hi", "data", "text/plain");
  9140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9141. EXPECT_EQ(StatusCode::OK_200, res->status);
  9142. svr.stop();
  9143. thread.join();
  9144. ASSERT_FALSE(svr.is_running());
  9145. res = cli.Post("/hi", "data", "text/plain");
  9146. ASSERT_FALSE(res);
  9147. }
  9148. TEST(ServerStopTest, ListenFailure) {
  9149. Server svr;
  9150. auto t = thread([&]() {
  9151. auto ret = svr.listen("????", PORT);
  9152. EXPECT_FALSE(ret);
  9153. });
  9154. svr.wait_until_ready();
  9155. svr.stop();
  9156. t.join();
  9157. }
  9158. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9159. TEST(ServerStopTest, Decommision) {
  9160. Server svr;
  9161. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  9162. for (int i = 0; i < 4; i++) {
  9163. auto is_even = !(i % 2);
  9164. std::thread t{[&] {
  9165. try {
  9166. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9167. if (is_even) {
  9168. throw std::runtime_error("Some thing that happens to go wrong.");
  9169. }
  9170. svr.listen(HOST, PORT);
  9171. } catch (...) { svr.decommission(); }
  9172. }};
  9173. svr.wait_until_ready();
  9174. // Server is up
  9175. {
  9176. Client cli(HOST, PORT);
  9177. auto res = cli.Get("/hi");
  9178. if (is_even) {
  9179. EXPECT_FALSE(res);
  9180. } else {
  9181. EXPECT_TRUE(res);
  9182. EXPECT_EQ("hi...", res->body);
  9183. }
  9184. }
  9185. svr.stop();
  9186. t.join();
  9187. // Server is down...
  9188. {
  9189. Client cli(HOST, PORT);
  9190. auto res = cli.Get("/hi");
  9191. EXPECT_FALSE(res);
  9192. }
  9193. }
  9194. }
  9195. #endif
  9196. // Helper function for string body upload progress tests
  9197. template <typename SetupHandler, typename ClientCall>
  9198. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  9199. ClientCall &&client_call,
  9200. const string &body) {
  9201. Server svr;
  9202. setup_handler(svr);
  9203. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9204. auto se = detail::scope_exit([&] {
  9205. svr.stop();
  9206. t.join();
  9207. });
  9208. svr.wait_until_ready();
  9209. Client cli(HOST, PORT);
  9210. vector<uint64_t> progress_values;
  9211. bool progress_called = false;
  9212. auto res =
  9213. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9214. progress_values.push_back(current);
  9215. progress_called = true;
  9216. return true;
  9217. });
  9218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9219. EXPECT_EQ(200, res->status);
  9220. EXPECT_TRUE(progress_called);
  9221. }
  9222. TEST(UploadProgressTest, PostStringBodyBasic) {
  9223. TestStringBodyUploadProgress(
  9224. [](Server &svr) {
  9225. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9226. res.set_content("received", "text/plain");
  9227. });
  9228. },
  9229. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9230. return cli.Post("/test", body, "text/plain", progress_callback);
  9231. },
  9232. "test data for upload progress");
  9233. }
  9234. TEST(UploadProgressTest, PutStringBodyBasic) {
  9235. TestStringBodyUploadProgress(
  9236. [](Server &svr) {
  9237. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  9238. res.set_content("put received", "text/plain");
  9239. });
  9240. },
  9241. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9242. return cli.Put("/test", body, "text/plain", progress_callback);
  9243. },
  9244. "put test data for upload progress");
  9245. }
  9246. TEST(UploadProgressTest, PatchStringBodyBasic) {
  9247. TestStringBodyUploadProgress(
  9248. [](Server &svr) {
  9249. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  9250. res.set_content("patch received", "text/plain");
  9251. });
  9252. },
  9253. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9254. return cli.Patch("/test", body, "text/plain", progress_callback);
  9255. },
  9256. "patch test data for upload progress");
  9257. }
  9258. // Helper function for content provider upload progress tests
  9259. template <typename SetupHandler, typename ClientCall>
  9260. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  9261. ClientCall &&client_call) {
  9262. Server svr;
  9263. setup_handler(svr);
  9264. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9265. auto se = detail::scope_exit([&] {
  9266. svr.stop();
  9267. t.join();
  9268. });
  9269. svr.wait_until_ready();
  9270. Client cli(HOST, PORT);
  9271. vector<uint64_t> progress_values;
  9272. auto res =
  9273. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9274. progress_values.push_back(current);
  9275. return true;
  9276. });
  9277. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9278. EXPECT_EQ(200, res->status);
  9279. EXPECT_FALSE(progress_values.empty());
  9280. }
  9281. TEST(UploadProgressTest, PostContentProviderProgress) {
  9282. TestContentProviderUploadProgress(
  9283. [](Server &svr) {
  9284. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9285. res.set_content("provider received", "text/plain");
  9286. });
  9287. },
  9288. [](Client &cli, UploadProgress progress_callback) {
  9289. return cli.Post(
  9290. "/test", 10,
  9291. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  9292. sink.os << "test data";
  9293. return true;
  9294. },
  9295. "text/plain", progress_callback);
  9296. });
  9297. }
  9298. // Helper function for multipart upload progress tests
  9299. template <typename SetupHandler, typename ClientCall>
  9300. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  9301. ClientCall &&client_call,
  9302. const string &endpoint) {
  9303. Server svr;
  9304. setup_handler(svr);
  9305. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9306. auto se = detail::scope_exit([&] {
  9307. svr.stop();
  9308. t.join();
  9309. });
  9310. svr.wait_until_ready();
  9311. Client cli(HOST, PORT);
  9312. vector<uint64_t> progress_values;
  9313. UploadFormDataItems items = {
  9314. {"field1", "value1", "", ""},
  9315. {"field2", "longer value for progress tracking test", "", ""},
  9316. {"file1", "file content data for upload progress", "test.txt",
  9317. "text/plain"}};
  9318. auto res = client_call(cli, endpoint, items,
  9319. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9320. progress_values.push_back(current);
  9321. return true;
  9322. });
  9323. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9324. EXPECT_EQ(200, res->status);
  9325. EXPECT_FALSE(progress_values.empty());
  9326. }
  9327. TEST(UploadProgressTest, PostMultipartProgress) {
  9328. TestMultipartUploadProgress(
  9329. [](Server &svr) {
  9330. svr.Post("/multipart", [](const Request &req, Response &res) {
  9331. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  9332. res.set_content("multipart received", "text/plain");
  9333. });
  9334. },
  9335. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  9336. UploadProgress progress_callback) {
  9337. return cli.Post(endpoint, items, progress_callback);
  9338. },
  9339. "/multipart");
  9340. }
  9341. // Helper function for basic download progress tests
  9342. template <typename SetupHandler, typename ClientCall>
  9343. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  9344. ClientCall &&client_call, const string &endpoint,
  9345. size_t expected_content_size) {
  9346. Server svr;
  9347. setup_handler(svr);
  9348. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9349. auto se = detail::scope_exit([&] {
  9350. svr.stop();
  9351. t.join();
  9352. });
  9353. svr.wait_until_ready();
  9354. Client cli(HOST, PORT);
  9355. vector<uint64_t> progress_values;
  9356. auto res = client_call(cli, endpoint,
  9357. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9358. progress_values.push_back(current);
  9359. return true;
  9360. });
  9361. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9362. EXPECT_EQ(200, res->status);
  9363. EXPECT_FALSE(progress_values.empty());
  9364. EXPECT_EQ(expected_content_size, res->body.size());
  9365. }
  9366. TEST(DownloadProgressTest, GetBasic) {
  9367. TestBasicDownloadProgress(
  9368. [](Server &svr) {
  9369. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  9370. string content(1000, 'D');
  9371. res.set_content(content, "text/plain");
  9372. });
  9373. },
  9374. [](Client &cli, const string &endpoint,
  9375. DownloadProgress progress_callback) {
  9376. return cli.Get(endpoint, progress_callback);
  9377. },
  9378. "/download", 1000u);
  9379. }
  9380. // Helper function for content receiver download progress tests
  9381. template <typename SetupHandler, typename ClientCall>
  9382. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  9383. ClientCall &&client_call,
  9384. const string &endpoint,
  9385. size_t expected_content_size) {
  9386. Server svr;
  9387. setup_handler(svr);
  9388. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9389. auto se = detail::scope_exit([&] {
  9390. svr.stop();
  9391. t.join();
  9392. });
  9393. svr.wait_until_ready();
  9394. Client cli(HOST, PORT);
  9395. vector<uint64_t> progress_values;
  9396. string received_body;
  9397. auto res = client_call(
  9398. cli, endpoint,
  9399. [&](const char *data, size_t data_length) -> bool {
  9400. received_body.append(data, data_length);
  9401. return true;
  9402. },
  9403. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9404. progress_values.push_back(current);
  9405. return true;
  9406. });
  9407. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9408. EXPECT_EQ(200, res->status);
  9409. EXPECT_FALSE(progress_values.empty());
  9410. EXPECT_EQ(expected_content_size, received_body.size());
  9411. EXPECT_TRUE(res->body.empty());
  9412. }
  9413. TEST(DownloadProgressTest, GetWithContentReceiver) {
  9414. TestContentReceiverDownloadProgress(
  9415. [](Server &svr) {
  9416. svr.Get("/download-receiver",
  9417. [](const Request & /*req*/, Response &res) {
  9418. string content(2000, 'R');
  9419. res.set_content(content, "text/plain");
  9420. });
  9421. },
  9422. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  9423. DownloadProgress progress_callback) {
  9424. return cli.Get(endpoint, content_receiver, progress_callback);
  9425. },
  9426. "/download-receiver", 2000u);
  9427. }
  9428. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  9429. // A provider reaching a pass with nothing to hand over - an empty buffer
  9430. // popped off a queue, say - must not be taken to mean the body is finished.
  9431. // It used to end the loop with the terminating chunk unwritten while the
  9432. // server still considered the response complete, so the peer waited for an
  9433. // end that never arrived.
  9434. Server svr;
  9435. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9436. auto step = std::make_shared<int>(0);
  9437. res.set_chunked_content_provider("text/plain",
  9438. [step](size_t /*offset*/, DataSink &sink) {
  9439. switch ((*step)++) {
  9440. case 0: sink.write("", 0); break;
  9441. case 1: sink.write("hello", 5); break;
  9442. default: sink.done(); break;
  9443. }
  9444. return true;
  9445. });
  9446. });
  9447. auto port = svr.bind_to_any_port(HOST);
  9448. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9449. auto listen_se = detail::scope_exit([&] {
  9450. svr.stop();
  9451. listen_thread.join();
  9452. ASSERT_FALSE(svr.is_running());
  9453. });
  9454. svr.wait_until_ready();
  9455. Client cli(HOST, port);
  9456. // Without the fix the body is never terminated, so bound the wait rather
  9457. // than letting the test hang on the default read timeout.
  9458. cli.set_read_timeout(5, 0);
  9459. auto res = cli.Get("/stream");
  9460. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9461. EXPECT_EQ(StatusCode::OK_200, res->status);
  9462. EXPECT_EQ("hello", res->body);
  9463. }
  9464. TEST(StreamingTest, NoContentLengthStreaming) {
  9465. Server svr;
  9466. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9467. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  9468. if (offset < 6) {
  9469. sink.os << (offset < 3 ? "a" : "b");
  9470. } else {
  9471. sink.done();
  9472. }
  9473. return true;
  9474. });
  9475. });
  9476. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9477. auto listen_se = detail::scope_exit([&] {
  9478. svr.stop();
  9479. listen_thread.join();
  9480. ASSERT_FALSE(svr.is_running());
  9481. });
  9482. svr.wait_until_ready();
  9483. Client client(HOST, PORT);
  9484. auto get_thread = std::thread([&client]() {
  9485. std::string s;
  9486. auto res =
  9487. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  9488. s += std::string(data, len);
  9489. return true;
  9490. });
  9491. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9492. EXPECT_EQ(StatusCode::OK_200, res->status);
  9493. EXPECT_EQ("aaabbb", s);
  9494. });
  9495. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  9496. // Give GET time to get a few messages.
  9497. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  9498. }
  9499. TEST(MountTest, Unmount) {
  9500. Server svr;
  9501. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9502. auto se = detail::scope_exit([&] {
  9503. svr.stop();
  9504. listen_thread.join();
  9505. ASSERT_FALSE(svr.is_running());
  9506. });
  9507. svr.wait_until_ready();
  9508. Client cli("localhost", PORT);
  9509. svr.set_mount_point("/mount2", "./www2");
  9510. auto res = cli.Get("/");
  9511. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9512. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9513. res = cli.Get("/mount2/dir/test.html");
  9514. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9515. EXPECT_EQ(StatusCode::OK_200, res->status);
  9516. svr.set_mount_point("/", "./www");
  9517. res = cli.Get("/dir/");
  9518. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9519. EXPECT_EQ(StatusCode::OK_200, res->status);
  9520. svr.remove_mount_point("/");
  9521. res = cli.Get("/dir/");
  9522. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9523. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9524. svr.remove_mount_point("/mount2");
  9525. res = cli.Get("/mount2/dir/test.html");
  9526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9527. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9528. }
  9529. TEST(MountTest, PathSegmentBoundary) {
  9530. Server svr;
  9531. svr.set_mount_point("/mount2", "./www2");
  9532. svr.set_mount_point("/", "./www");
  9533. auto port = svr.bind_to_any_port(HOST);
  9534. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9535. auto se = detail::scope_exit([&] {
  9536. svr.stop();
  9537. listen_thread.join();
  9538. ASSERT_FALSE(svr.is_running());
  9539. });
  9540. svr.wait_until_ready();
  9541. Client cli(HOST, port);
  9542. auto res = cli.Get("/mount2/dir/test.html");
  9543. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9544. EXPECT_EQ(StatusCode::OK_200, res->status);
  9545. // "/mount2" must not match part-way through a path segment.
  9546. res = cli.Get("/mount2dir/test.html");
  9547. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9548. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9549. // A mount point ending in '/' keeps matching every path below it.
  9550. res = cli.Get("/dir/test.html");
  9551. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9552. EXPECT_EQ(StatusCode::OK_200, res->status);
  9553. }
  9554. TEST(MountTest, Redicect) {
  9555. Server svr;
  9556. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9557. auto se = detail::scope_exit([&] {
  9558. svr.stop();
  9559. listen_thread.join();
  9560. ASSERT_FALSE(svr.is_running());
  9561. });
  9562. svr.set_mount_point("/", "./www");
  9563. svr.wait_until_ready();
  9564. Client cli("localhost", PORT);
  9565. auto res = cli.Get("/dir/");
  9566. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9567. EXPECT_EQ(StatusCode::OK_200, res->status);
  9568. res = cli.Get("/dir");
  9569. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9570. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9571. res = cli.Get("/file");
  9572. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9573. EXPECT_EQ(StatusCode::OK_200, res->status);
  9574. res = cli.Get("/file/");
  9575. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9576. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9577. cli.set_follow_location(true);
  9578. res = cli.Get("/dir");
  9579. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9580. EXPECT_EQ(StatusCode::OK_200, res->status);
  9581. }
  9582. TEST(MountTest, MultibytesPathName) {
  9583. Server svr;
  9584. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9585. auto se = detail::scope_exit([&] {
  9586. svr.stop();
  9587. listen_thread.join();
  9588. ASSERT_FALSE(svr.is_running());
  9589. });
  9590. svr.set_mount_point("/", "./www");
  9591. svr.wait_until_ready();
  9592. Client cli("localhost", PORT);
  9593. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  9594. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9595. EXPECT_EQ(StatusCode::OK_200, res->status);
  9596. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  9597. }
  9598. #ifdef _WIN32
  9599. // Issue #2435: mmap::open() must succeed even when another handle holds
  9600. // the file open for writing (e.g. an active log file).
  9601. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  9602. const char *path = "mmap_concurrent_writer_test.txt";
  9603. const char *content = "hello";
  9604. {
  9605. std::ofstream f(path, std::ios::binary);
  9606. f.write(content, static_cast<std::streamsize>(strlen(content)));
  9607. }
  9608. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  9609. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  9610. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  9611. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  9612. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  9613. detail::mmap m(path);
  9614. ASSERT_TRUE(m.is_open());
  9615. EXPECT_EQ(strlen(content), m.size());
  9616. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  9617. }
  9618. #endif
  9619. #ifndef _WIN32
  9620. // A failed ::mmap() must not be reported as an open mapping, otherwise data()
  9621. // hands the caller the MAP_FAILED sentinel. A directory is the easiest way to
  9622. // reach it, since ::open() and fstat() succeed for one but ::mmap() doesn't.
  9623. TEST(MmapTest, FailedMappingIsNotOpen) {
  9624. const char *path = "./mmap_failed_mapping_test_dir";
  9625. ASSERT_EQ(0, ::mkdir(path, 0755));
  9626. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  9627. detail::mmap m(path);
  9628. EXPECT_FALSE(m.is_open());
  9629. EXPECT_EQ(0U, m.size());
  9630. EXPECT_NE(static_cast<const void *>(m.data()),
  9631. static_cast<const void *>(MAP_FAILED));
  9632. }
  9633. #endif
  9634. TEST(KeepAliveTest, ReadTimeout) {
  9635. Server svr;
  9636. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  9637. std::this_thread::sleep_for(std::chrono::seconds(2));
  9638. res.set_content("a", "text/plain");
  9639. });
  9640. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  9641. res.set_content("b", "text/plain");
  9642. });
  9643. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9644. auto se = detail::scope_exit([&] {
  9645. svr.stop();
  9646. listen_thread.join();
  9647. ASSERT_FALSE(svr.is_running());
  9648. });
  9649. svr.wait_until_ready();
  9650. Client cli("localhost", PORT);
  9651. cli.set_keep_alive(true);
  9652. cli.set_read_timeout(std::chrono::seconds(1));
  9653. auto resa = cli.Get("/a");
  9654. ASSERT_FALSE(resa);
  9655. EXPECT_EQ(Error::Read, resa.error());
  9656. auto resb = cli.Get("/b");
  9657. ASSERT_TRUE(resb);
  9658. EXPECT_EQ(StatusCode::OK_200, resb->status);
  9659. EXPECT_EQ("b", resb->body);
  9660. }
  9661. TEST(KeepAliveTest, MaxCount) {
  9662. size_t keep_alive_max_count = 3;
  9663. Server svr;
  9664. svr.set_keep_alive_max_count(keep_alive_max_count);
  9665. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9666. res.set_content("Hello World!", "text/plain");
  9667. });
  9668. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9669. auto se = detail::scope_exit([&] {
  9670. svr.stop();
  9671. listen_thread.join();
  9672. ASSERT_FALSE(svr.is_running());
  9673. });
  9674. svr.wait_until_ready();
  9675. Client cli(HOST, PORT);
  9676. cli.set_keep_alive(true);
  9677. for (size_t i = 0; i < 5; i++) {
  9678. auto result = cli.Get("/hi");
  9679. ASSERT_TRUE(result);
  9680. EXPECT_EQ(StatusCode::OK_200, result->status);
  9681. if (i == keep_alive_max_count - 1) {
  9682. EXPECT_EQ("close", result->get_header_value("Connection"));
  9683. } else {
  9684. EXPECT_FALSE(result->has_header("Connection"));
  9685. }
  9686. }
  9687. }
  9688. TEST(KeepAliveTest, Issue1041) {
  9689. Server svr;
  9690. svr.set_keep_alive_timeout(3);
  9691. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9692. res.set_content("Hello World!", "text/plain");
  9693. });
  9694. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9695. auto se = detail::scope_exit([&] {
  9696. svr.stop();
  9697. listen_thread.join();
  9698. ASSERT_FALSE(svr.is_running());
  9699. });
  9700. svr.wait_until_ready();
  9701. Client cli(HOST, PORT);
  9702. cli.set_keep_alive(true);
  9703. auto result = cli.Get("/hi");
  9704. ASSERT_TRUE(result);
  9705. EXPECT_EQ(StatusCode::OK_200, result->status);
  9706. std::this_thread::sleep_for(std::chrono::seconds(5));
  9707. result = cli.Get("/hi");
  9708. ASSERT_TRUE(result);
  9709. EXPECT_EQ(StatusCode::OK_200, result->status);
  9710. }
  9711. TEST(KeepAliveTest, Issue1959) {
  9712. Server svr;
  9713. svr.set_keep_alive_timeout(5);
  9714. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  9715. res.set_content("a", "text/plain");
  9716. });
  9717. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9718. auto se = detail::scope_exit([&] {
  9719. if (!svr.is_running()) return;
  9720. svr.stop();
  9721. listen_thread.join();
  9722. ASSERT_FALSE(svr.is_running());
  9723. });
  9724. svr.wait_until_ready();
  9725. Client cli("localhost", PORT);
  9726. cli.set_keep_alive(true);
  9727. using namespace std::chrono;
  9728. auto start = steady_clock::now();
  9729. cli.Get("/a");
  9730. svr.stop();
  9731. listen_thread.join();
  9732. auto end = steady_clock::now();
  9733. auto elapsed = duration_cast<milliseconds>(end - start).count();
  9734. EXPECT_LT(elapsed, 5000);
  9735. }
  9736. #ifdef CPPHTTPLIB_SSL_ENABLED
  9737. TEST(KeepAliveTest, SSLClientReconnection) {
  9738. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9739. ASSERT_TRUE(svr.is_valid());
  9740. svr.set_keep_alive_timeout(1);
  9741. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9742. res.set_content("Hello World!", "text/plain");
  9743. });
  9744. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9745. auto se = detail::scope_exit([&] {
  9746. svr.stop();
  9747. listen_thread.join();
  9748. ASSERT_FALSE(svr.is_running());
  9749. });
  9750. svr.wait_until_ready();
  9751. SSLClient cli(HOST, PORT);
  9752. cli.enable_server_certificate_verification(false);
  9753. cli.set_keep_alive(true);
  9754. auto result = cli.Get("/hi");
  9755. ASSERT_TRUE(result);
  9756. EXPECT_EQ(StatusCode::OK_200, result->status);
  9757. result = cli.Get("/hi");
  9758. ASSERT_TRUE(result);
  9759. EXPECT_EQ(StatusCode::OK_200, result->status);
  9760. std::this_thread::sleep_for(std::chrono::seconds(2));
  9761. // Recoonect
  9762. result = cli.Get("/hi");
  9763. ASSERT_TRUE(result);
  9764. EXPECT_EQ(StatusCode::OK_200, result->status);
  9765. result = cli.Get("/hi");
  9766. ASSERT_TRUE(result);
  9767. EXPECT_EQ(StatusCode::OK_200, result->status);
  9768. }
  9769. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  9770. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9771. ASSERT_TRUE(svr.is_valid());
  9772. svr.set_keep_alive_timeout(1);
  9773. std::string content = "reconnect";
  9774. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  9775. res.set_content("Hello World!", "text/plain");
  9776. });
  9777. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9778. auto se = detail::scope_exit([&] {
  9779. svr.stop();
  9780. listen_thread.join();
  9781. ASSERT_FALSE(svr.is_running());
  9782. });
  9783. svr.wait_until_ready();
  9784. SSLClient cli(HOST, PORT);
  9785. cli.enable_server_certificate_verification(false);
  9786. cli.set_keep_alive(true);
  9787. auto result = cli.Post(
  9788. "/hi", content.size(),
  9789. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9790. sink.write(content.c_str(), content.size());
  9791. return true;
  9792. },
  9793. "text/plain");
  9794. ASSERT_TRUE(result);
  9795. EXPECT_EQ(200, result->status);
  9796. std::this_thread::sleep_for(std::chrono::seconds(2));
  9797. // Recoonect
  9798. result = cli.Post(
  9799. "/hi", content.size(),
  9800. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9801. sink.write(content.c_str(), content.size());
  9802. return true;
  9803. },
  9804. "text/plain");
  9805. ASSERT_TRUE(result);
  9806. EXPECT_EQ(200, result->status);
  9807. result = cli.Post(
  9808. "/hi", content.size(),
  9809. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9810. sink.write(content.c_str(), content.size());
  9811. return true;
  9812. },
  9813. "text/plain");
  9814. ASSERT_TRUE(result);
  9815. EXPECT_EQ(200, result->status);
  9816. }
  9817. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  9818. using namespace httplib::tls;
  9819. {
  9820. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9821. ASSERT_TRUE(svr.is_valid());
  9822. svr.Get("/sni", [&](const Request &req, Response &res) {
  9823. std::string expected = req.sni();
  9824. EXPECT_EQ(expected, req.get_param_value("expected"));
  9825. res.set_content("ok", "text/plain");
  9826. });
  9827. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9828. auto se = detail::scope_exit([&] {
  9829. svr.stop();
  9830. listen_thread.join();
  9831. ASSERT_FALSE(svr.is_running());
  9832. });
  9833. svr.wait_until_ready();
  9834. {
  9835. SSLClient cli("localhost", PORT);
  9836. cli.enable_server_certificate_verification(false);
  9837. auto res = cli.Get("/sni?expected=localhost");
  9838. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9839. }
  9840. {
  9841. SSLClient cli("::1", PORT);
  9842. cli.enable_server_certificate_verification(false);
  9843. auto res = cli.Get("/sni?expected=");
  9844. // NOTE: This may fail if the server is listening on IPv4 only
  9845. // (e.g., when localhost resolves to 127.0.0.1 only)
  9846. if (res) {
  9847. EXPECT_EQ(StatusCode::OK_200, res->status);
  9848. } else {
  9849. EXPECT_EQ(Error::Connection, res.error());
  9850. }
  9851. }
  9852. }
  9853. }
  9854. #endif
  9855. TEST(ClientProblemDetectionTest, ContentProvider) {
  9856. Server svr;
  9857. size_t content_length = 1024 * 1024;
  9858. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9859. res.set_content_provider(
  9860. content_length, "text/plain",
  9861. [&](size_t offset, size_t length, DataSink &sink) {
  9862. auto out_len = std::min(length, static_cast<size_t>(1024));
  9863. std::string out(out_len, '@');
  9864. sink.write(out.data(), out_len);
  9865. return offset < 4096;
  9866. },
  9867. [](bool success) { ASSERT_FALSE(success); });
  9868. });
  9869. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  9870. res.set_content_provider(
  9871. 0, "text/plain",
  9872. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  9873. EXPECT_TRUE(false);
  9874. return true;
  9875. },
  9876. [](bool success) { ASSERT_FALSE(success); });
  9877. });
  9878. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9879. auto se = detail::scope_exit([&] {
  9880. svr.stop();
  9881. listen_thread.join();
  9882. ASSERT_FALSE(svr.is_running());
  9883. });
  9884. svr.wait_until_ready();
  9885. Client cli("localhost", PORT);
  9886. {
  9887. auto res = cli.Get("/hi", [&](const char * /*data*/,
  9888. size_t /*data_length*/) { return false; });
  9889. ASSERT_FALSE(res);
  9890. }
  9891. {
  9892. auto res = cli.Get("/empty", [&](const char * /*data*/,
  9893. size_t /*data_length*/) { return false; });
  9894. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9895. }
  9896. }
  9897. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  9898. // A provider that reports success without writing anything and without
  9899. // calling done() used to be handed the same offset and length again on every
  9900. // pass, so it spun for as long as the peer stayed connected.
  9901. Server svr;
  9902. svr.Post("/", [](const Request & /*req*/, Response &res) {
  9903. res.set_content("ok", "text/plain");
  9904. });
  9905. auto port = svr.bind_to_any_port(HOST);
  9906. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  9907. auto se = detail::scope_exit([&] {
  9908. svr.stop();
  9909. listen_thread.join();
  9910. ASSERT_FALSE(svr.is_running());
  9911. });
  9912. svr.wait_until_ready();
  9913. std::atomic<int> call_count{0};
  9914. Client cli(HOST, port);
  9915. auto res = cli.Post(
  9916. "/", 1024,
  9917. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  9918. // Give up after enough passes to show the spin, so that losing the
  9919. // check below fails this test instead of hanging it.
  9920. return ++call_count < 100;
  9921. },
  9922. "text/plain");
  9923. ASSERT_FALSE(res);
  9924. EXPECT_EQ(Error::Write, res.error());
  9925. EXPECT_EQ(1, call_count.load());
  9926. }
  9927. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  9928. // A writer only has to assign `write`. The other three used to be left as
  9929. // empty std::functions, so a provider calling one threw
  9930. // std::bad_function_call out of the thread running it and took the whole
  9931. // process down.
  9932. DataSink sink;
  9933. std::string written;
  9934. sink.write = [&](const char *data, size_t data_len) {
  9935. written.append(data, data_len);
  9936. return true;
  9937. };
  9938. EXPECT_TRUE(sink.is_writable());
  9939. sink.done();
  9940. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  9941. EXPECT_TRUE(written.empty());
  9942. }
  9943. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  9944. // A sink that cannot carry trailers still has to finish.
  9945. DataSink sink;
  9946. auto done_count = 0;
  9947. sink.done = [&]() { done_count++; };
  9948. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  9949. EXPECT_EQ(1, done_count);
  9950. }
  9951. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  9952. Server svr;
  9953. const std::string body(4096, 'x');
  9954. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  9955. res.set_content_provider(body.size(), "text/plain",
  9956. [&](size_t offset, size_t length, DataSink &sink) {
  9957. sink.write(body.data() + offset, length);
  9958. sink.done();
  9959. return true;
  9960. });
  9961. });
  9962. auto port = svr.bind_to_any_port(HOST);
  9963. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9964. auto se = detail::scope_exit([&] {
  9965. svr.stop();
  9966. listen_thread.join();
  9967. ASSERT_FALSE(svr.is_running());
  9968. });
  9969. svr.wait_until_ready();
  9970. Client cli(HOST, port);
  9971. auto res = cli.Get("/");
  9972. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9973. EXPECT_EQ(StatusCode::OK_200, res->status);
  9974. EXPECT_EQ(body, res->body);
  9975. }
  9976. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  9977. Server svr;
  9978. svr.Get("/", [](const Request & /*req*/, Response &res) {
  9979. res.set_content_provider(
  9980. 1024, "text/plain",
  9981. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9982. sink.write("hello", 5);
  9983. sink.done(); // short of the 1024 bytes the response promised
  9984. return true;
  9985. });
  9986. });
  9987. auto port = svr.bind_to_any_port(HOST);
  9988. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9989. auto se = detail::scope_exit([&] {
  9990. svr.stop();
  9991. listen_thread.join();
  9992. ASSERT_FALSE(svr.is_running());
  9993. });
  9994. svr.wait_until_ready();
  9995. Client cli(HOST, port);
  9996. cli.set_read_timeout(5, 0);
  9997. // The response is short of its Content-Length, so the client cannot read a
  9998. // complete body. What matters is that this returns at all: a no-op done()
  9999. // would leave the writer looping over a provider that never makes progress.
  10000. auto res = cli.Get("/");
  10001. EXPECT_FALSE(res);
  10002. }
  10003. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10004. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  10005. // The compressed path builds the whole body before connecting, so this
  10006. // fails client-side and never reaches a server.
  10007. Client cli(HOST, PORT);
  10008. cli.set_compress(true);
  10009. auto res = cli.Post(
  10010. "/", 1024,
  10011. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10012. sink.write("hello", 5);
  10013. sink.done(); // short of the 1024 bytes the request announced
  10014. return true;
  10015. },
  10016. "text/plain");
  10017. ASSERT_FALSE(res);
  10018. EXPECT_EQ(Error::Write, res.error());
  10019. }
  10020. #endif
  10021. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  10022. Server svr;
  10023. svr.set_error_handler([](Request const &, Response &res) -> void {
  10024. res.set_chunked_content_provider(
  10025. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10026. sink.os << "hello";
  10027. sink.os << "world";
  10028. sink.done();
  10029. return true;
  10030. });
  10031. });
  10032. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10033. auto se = detail::scope_exit([&] {
  10034. svr.stop();
  10035. listen_thread.join();
  10036. ASSERT_FALSE(svr.is_running());
  10037. });
  10038. svr.wait_until_ready();
  10039. Client cli("localhost", PORT);
  10040. auto res = cli.Get("/");
  10041. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10042. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10043. EXPECT_EQ("helloworld", res->body);
  10044. }
  10045. TEST(LongPollingTest, ClientCloseDetection) {
  10046. Server svr;
  10047. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  10048. res.set_chunked_content_provider(
  10049. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10050. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  10051. sink.os << "hello";
  10052. auto count = 10;
  10053. while (count > 0 && sink.is_writable()) {
  10054. this_thread::sleep_for(chrono::milliseconds(10));
  10055. count--;
  10056. }
  10057. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  10058. return true;
  10059. });
  10060. });
  10061. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10062. auto se = detail::scope_exit([&] {
  10063. svr.stop();
  10064. listen_thread.join();
  10065. ASSERT_FALSE(svr.is_running());
  10066. });
  10067. svr.wait_until_ready();
  10068. Client cli("localhost", PORT);
  10069. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  10070. EXPECT_EQ("hello", string(data, data_length));
  10071. return false; // close the socket immediately.
  10072. });
  10073. ASSERT_FALSE(res);
  10074. }
  10075. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  10076. Server svr;
  10077. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  10078. res.set_chunked_content_provider(
  10079. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10080. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  10081. sink.os << "hello";
  10082. EXPECT_TRUE(sink.os.good());
  10083. // Wait for the client to close the connection
  10084. auto count = 10;
  10085. while (count > 0 && sink.is_writable()) {
  10086. this_thread::sleep_for(chrono::milliseconds(10));
  10087. count--;
  10088. }
  10089. // After client disconnect, write repeatedly until the socket
  10090. // write actually fails (small writes may be absorbed by the
  10091. // kernel buffer)
  10092. std::string chunk(1024, 'x');
  10093. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  10094. sink.os << chunk;
  10095. }
  10096. EXPECT_TRUE(sink.os.fail());
  10097. return true;
  10098. });
  10099. });
  10100. auto port = svr.bind_to_any_port("localhost");
  10101. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10102. auto se = detail::scope_exit([&] {
  10103. svr.stop();
  10104. listen_thread.join();
  10105. ASSERT_FALSE(svr.is_running());
  10106. });
  10107. svr.wait_until_ready();
  10108. Client cli("localhost", port);
  10109. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  10110. EXPECT_EQ("hello", string(data, data_length));
  10111. return false; // close the socket immediately.
  10112. });
  10113. ASSERT_FALSE(res);
  10114. }
  10115. TEST(GetWithParametersTest, GetWithParameters) {
  10116. Server svr;
  10117. svr.Get("/", [&](const Request &req, Response &) {
  10118. EXPECT_EQ("world", req.get_param_value("hello"));
  10119. EXPECT_EQ("world2", req.get_param_value("hello2"));
  10120. EXPECT_EQ("world3", req.get_param_value("hello3"));
  10121. });
  10122. svr.Get("/params", [&](const Request &req, Response &) {
  10123. EXPECT_EQ("world", req.get_param_value("hello"));
  10124. EXPECT_EQ("world2", req.get_param_value("hello2"));
  10125. EXPECT_EQ("world3", req.get_param_value("hello3"));
  10126. });
  10127. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  10128. EXPECT_EQ("resource-id", req.matches[1]);
  10129. EXPECT_EQ("foo", req.get_param_value("param1"));
  10130. EXPECT_EQ("bar", req.get_param_value("param2"));
  10131. });
  10132. svr.Get("/users/:id", [&](const Request &req, Response &) {
  10133. EXPECT_EQ("user-id", req.path_params.at("id"));
  10134. EXPECT_EQ("foo", req.get_param_value("param1"));
  10135. EXPECT_EQ("bar", req.get_param_value("param2"));
  10136. });
  10137. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10138. auto se = detail::scope_exit([&] {
  10139. svr.stop();
  10140. listen_thread.join();
  10141. ASSERT_FALSE(svr.is_running());
  10142. });
  10143. svr.wait_until_ready();
  10144. {
  10145. Client cli(HOST, PORT);
  10146. Params params;
  10147. params.emplace("hello", "world");
  10148. params.emplace("hello2", "world2");
  10149. params.emplace("hello3", "world3");
  10150. auto res = cli.Get("/", params, Headers{});
  10151. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10152. EXPECT_EQ(StatusCode::OK_200, res->status);
  10153. }
  10154. {
  10155. Client cli(HOST, PORT);
  10156. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  10157. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10158. EXPECT_EQ(StatusCode::OK_200, res->status);
  10159. }
  10160. {
  10161. Client cli(HOST, PORT);
  10162. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  10163. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10164. EXPECT_EQ(StatusCode::OK_200, res->status);
  10165. }
  10166. {
  10167. Client cli(HOST, PORT);
  10168. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  10169. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10170. EXPECT_EQ(StatusCode::OK_200, res->status);
  10171. }
  10172. }
  10173. TEST(GetWithParametersTest, GetWithParameters2) {
  10174. Server svr;
  10175. svr.Get("/", [&](const Request &req, Response &res) {
  10176. auto text = req.get_param_value("hello");
  10177. res.set_content(text, "text/plain");
  10178. });
  10179. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10180. auto se = detail::scope_exit([&] {
  10181. svr.stop();
  10182. listen_thread.join();
  10183. ASSERT_FALSE(svr.is_running());
  10184. });
  10185. svr.wait_until_ready();
  10186. Client cli("localhost", PORT);
  10187. Params params;
  10188. params.emplace("hello", "world");
  10189. std::string body;
  10190. auto res = cli.Get("/", params, Headers{},
  10191. [&](const char *data, size_t data_length) {
  10192. body.append(data, data_length);
  10193. return true;
  10194. });
  10195. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10196. EXPECT_EQ(StatusCode::OK_200, res->status);
  10197. EXPECT_EQ("world", body);
  10198. }
  10199. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  10200. Server svr;
  10201. svr.Get("/search", [&](const Request &req, Response &res) {
  10202. auto q = req.get_param_value("q");
  10203. res.set_content(q, "text/plain");
  10204. });
  10205. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10206. auto se = detail::scope_exit([&] {
  10207. svr.stop();
  10208. listen_thread.join();
  10209. ASSERT_FALSE(svr.is_running());
  10210. });
  10211. svr.wait_until_ready();
  10212. Client cli("localhost", PORT);
  10213. // Verify that Get(path, params) works without requiring Headers argument
  10214. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  10215. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10216. EXPECT_EQ(StatusCode::OK_200, res->status);
  10217. EXPECT_EQ("cpp-httplib", res->body);
  10218. }
  10219. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  10220. auto host = "httpbingo.org";
  10221. auto path = std::string{"/range/32"};
  10222. #ifdef CPPHTTPLIB_SSL_ENABLED
  10223. SSLClient cli(host);
  10224. #else
  10225. Client cli(host);
  10226. #endif
  10227. cli.set_default_headers({make_range_header({{1, 10}})});
  10228. cli.set_connection_timeout(5);
  10229. {
  10230. auto res = cli.Get(path);
  10231. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10232. EXPECT_EQ("bcdefghijk", res->body);
  10233. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10234. }
  10235. {
  10236. auto res = cli.Get(path);
  10237. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10238. EXPECT_EQ("bcdefghijk", res->body);
  10239. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10240. }
  10241. }
  10242. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  10243. Server svr;
  10244. svr.set_default_headers({{"Hello", "World"}});
  10245. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  10246. res.set_content("ok", "text/plain");
  10247. });
  10248. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10249. auto se = detail::scope_exit([&] {
  10250. svr.stop();
  10251. listen_thread.join();
  10252. ASSERT_FALSE(svr.is_running());
  10253. });
  10254. svr.wait_until_ready();
  10255. Client cli("localhost", PORT);
  10256. auto res = cli.Get("/");
  10257. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10258. EXPECT_EQ(StatusCode::OK_200, res->status);
  10259. EXPECT_EQ("ok", res->body);
  10260. EXPECT_EQ("World", res->get_header_value("Hello"));
  10261. }
  10262. #ifdef CPPHTTPLIB_SSL_ENABLED
  10263. TEST(KeepAliveTest, ReadTimeoutSSL) {
  10264. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10265. ASSERT_TRUE(svr.is_valid());
  10266. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10267. std::this_thread::sleep_for(std::chrono::seconds(2));
  10268. res.set_content("a", "text/plain");
  10269. });
  10270. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10271. res.set_content("b", "text/plain");
  10272. });
  10273. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10274. auto se = detail::scope_exit([&] {
  10275. svr.stop();
  10276. listen_thread.join();
  10277. ASSERT_FALSE(svr.is_running());
  10278. });
  10279. svr.wait_until_ready();
  10280. SSLClient cli("localhost", PORT);
  10281. cli.enable_server_certificate_verification(false);
  10282. cli.set_keep_alive(true);
  10283. cli.set_read_timeout(std::chrono::seconds(1));
  10284. auto resa = cli.Get("/a");
  10285. ASSERT_TRUE(!resa);
  10286. EXPECT_EQ(Error::Read, resa.error());
  10287. auto resb = cli.Get("/b");
  10288. ASSERT_TRUE(resb);
  10289. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10290. EXPECT_EQ("b", resb->body);
  10291. }
  10292. // Closing an idle keep-alive connection sends close_notify and returns. The
  10293. // server must not wait for the client's close_notify: an idle client never
  10294. // sends one, so the worker would be held until the read timeout expires, and
  10295. // stop() would wait for it.
  10296. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  10297. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10298. ASSERT_TRUE(svr.is_valid());
  10299. svr.set_keep_alive_timeout(1);
  10300. svr.set_read_timeout(10, 0);
  10301. svr.Get("/", [](const Request &, Response &res) {
  10302. res.set_content("ok", "text/plain");
  10303. });
  10304. auto port = svr.bind_to_any_port(HOST);
  10305. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10306. auto se = detail::scope_exit([&] {
  10307. if (listen_thread.joinable()) {
  10308. svr.stop();
  10309. listen_thread.join();
  10310. }
  10311. });
  10312. svr.wait_until_ready();
  10313. SSLClient cli(HOST, port);
  10314. cli.enable_server_certificate_verification(false);
  10315. cli.set_keep_alive(true);
  10316. auto res = cli.Get("/");
  10317. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10318. EXPECT_EQ(StatusCode::OK_200, res->status);
  10319. // Stay idle past the keep-alive timeout so the server closes the connection.
  10320. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  10321. auto start = std::chrono::steady_clock::now();
  10322. svr.stop();
  10323. listen_thread.join();
  10324. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10325. std::chrono::steady_clock::now() - start)
  10326. .count();
  10327. EXPECT_LT(elapsed, 3000);
  10328. }
  10329. #endif
  10330. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  10331. protected:
  10332. ServerTestWithAI_PASSIVE()
  10333. : cli_(HOST, PORT)
  10334. #ifdef CPPHTTPLIB_SSL_ENABLED
  10335. ,
  10336. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10337. #endif
  10338. {
  10339. #ifdef CPPHTTPLIB_SSL_ENABLED
  10340. cli_.enable_server_certificate_verification(false);
  10341. #endif
  10342. }
  10343. virtual void SetUp() {
  10344. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10345. res.set_content("Hello World!", "text/plain");
  10346. });
  10347. t_ = thread(
  10348. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  10349. svr_.wait_until_ready();
  10350. }
  10351. virtual void TearDown() {
  10352. svr_.stop();
  10353. t_.join();
  10354. }
  10355. #ifdef CPPHTTPLIB_SSL_ENABLED
  10356. SSLClient cli_;
  10357. SSLServer svr_;
  10358. #else
  10359. Client cli_;
  10360. Server svr_;
  10361. #endif
  10362. thread t_;
  10363. };
  10364. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  10365. auto res = cli_.Get("/hi");
  10366. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10367. EXPECT_EQ(StatusCode::OK_200, res->status);
  10368. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  10369. EXPECT_EQ("Hello World!", res->body);
  10370. }
  10371. class ServerUpDownTest : public ::testing::Test {
  10372. protected:
  10373. ServerUpDownTest() : cli_(HOST, PORT) {}
  10374. virtual void SetUp() {
  10375. t_ = thread([&]() {
  10376. svr_.bind_to_any_port(HOST);
  10377. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  10378. ASSERT_TRUE(svr_.listen_after_bind());
  10379. });
  10380. svr_.wait_until_ready();
  10381. }
  10382. virtual void TearDown() {
  10383. svr_.stop();
  10384. t_.join();
  10385. }
  10386. Client cli_;
  10387. Server svr_;
  10388. thread t_;
  10389. };
  10390. TEST_F(ServerUpDownTest, QuickStartStop) {
  10391. // Should not crash, especially when run with
  10392. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  10393. }
  10394. class PayloadMaxLengthTest : public ::testing::Test {
  10395. protected:
  10396. PayloadMaxLengthTest()
  10397. : cli_(HOST, PORT)
  10398. #ifdef CPPHTTPLIB_SSL_ENABLED
  10399. ,
  10400. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10401. #endif
  10402. {
  10403. #ifdef CPPHTTPLIB_SSL_ENABLED
  10404. cli_.enable_server_certificate_verification(false);
  10405. #endif
  10406. }
  10407. virtual void SetUp() {
  10408. svr_.set_payload_max_length(8);
  10409. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  10410. res.set_content("test", "text/plain");
  10411. });
  10412. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  10413. svr_.wait_until_ready();
  10414. }
  10415. virtual void TearDown() {
  10416. svr_.stop();
  10417. t_.join();
  10418. }
  10419. #ifdef CPPHTTPLIB_SSL_ENABLED
  10420. SSLClient cli_;
  10421. SSLServer svr_;
  10422. #else
  10423. Client cli_;
  10424. Server svr_;
  10425. #endif
  10426. thread t_;
  10427. };
  10428. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  10429. auto res = cli_.Post("/test", "123456789", "text/plain");
  10430. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10431. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10432. res = cli_.Post("/test", "12345678", "text/plain");
  10433. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10434. EXPECT_EQ(StatusCode::OK_200, res->status);
  10435. }
  10436. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  10437. // Test chunked encoding with payload exceeding the 8-byte limit
  10438. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  10439. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  10440. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10441. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10442. }
  10443. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  10444. // Test chunked encoding with payload within the 8-byte limit
  10445. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  10446. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  10447. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10448. EXPECT_EQ(StatusCode::OK_200, res->status);
  10449. }
  10450. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  10451. // Test using send_request to send chunked data exceeding payload limit
  10452. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  10453. "Host: " +
  10454. std::string(HOST) + ":" + std::to_string(PORT) +
  10455. "\r\n"
  10456. "Transfer-Encoding: chunked\r\n"
  10457. "Connection: close\r\n"
  10458. "\r\n"
  10459. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  10460. "0123456789\r\n"
  10461. "0\r\n" // End chunk
  10462. "\r\n";
  10463. std::string response;
  10464. bool result = send_request(1, chunked_request, &response);
  10465. if (!result) {
  10466. // If send_request fails, it might be because the server closed the
  10467. // connection due to payload limit enforcement, which is acceptable
  10468. SUCCEED()
  10469. << "Server rejected oversized chunked request (connection closed)";
  10470. } else {
  10471. // If we got a response, check if it's an error response or connection was
  10472. // closed early Short response length indicates connection was closed due to
  10473. // payload limit
  10474. if (response.length() <= 10) {
  10475. SUCCEED() << "Server closed connection for oversized chunked request";
  10476. } else {
  10477. // Check for error status codes
  10478. EXPECT_TRUE(response.find("413") != std::string::npos ||
  10479. response.find("Payload Too Large") != std::string::npos ||
  10480. response.find("400") != std::string::npos);
  10481. }
  10482. }
  10483. }
  10484. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  10485. // Test request without Content-Length header exceeding payload limit
  10486. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10487. "Host: " +
  10488. std::string(HOST) + ":" +
  10489. std::to_string(PORT) +
  10490. "\r\n"
  10491. "Connection: close\r\n"
  10492. "\r\n";
  10493. // Add payload exceeding the 8-byte limit
  10494. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  10495. request_without_content_length += large_payload;
  10496. std::string response;
  10497. bool result = send_request(1, request_without_content_length, &response);
  10498. if (!result) {
  10499. // If send_request fails, server likely closed connection due to payload
  10500. // limit
  10501. SUCCEED() << "Server rejected oversized request without Content-Length "
  10502. "(connection closed)";
  10503. } else {
  10504. // Check if server responded with error or closed connection early
  10505. if (response.length() <= 10) {
  10506. SUCCEED() << "Server closed connection for oversized request without "
  10507. "Content-Length";
  10508. } else {
  10509. // Check for error status codes
  10510. EXPECT_TRUE(response.find("413") != std::string::npos ||
  10511. response.find("Payload Too Large") != std::string::npos ||
  10512. response.find("400") != std::string::npos);
  10513. }
  10514. }
  10515. }
  10516. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  10517. // Test request without Content-Length header within payload limit
  10518. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10519. "Host: " +
  10520. std::string(HOST) + ":" +
  10521. std::to_string(PORT) +
  10522. "\r\n"
  10523. "Connection: close\r\n"
  10524. "\r\n";
  10525. // Add payload within the 8-byte limit
  10526. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  10527. request_without_content_length += small_payload;
  10528. std::string response;
  10529. bool result = send_request(1, request_without_content_length, &response);
  10530. // For requests without Content-Length, the server may have different behavior
  10531. // The key is that it should not reject due to payload limit for small
  10532. // payloads
  10533. if (result) {
  10534. // Check for any HTTP response (success or error, but not connection closed)
  10535. if (response.length() > 10) {
  10536. SUCCEED()
  10537. << "Server processed request without Content-Length within limit";
  10538. } else {
  10539. // Short response might indicate connection closed, which is acceptable
  10540. SUCCEED() << "Server closed connection for request without "
  10541. "Content-Length (acceptable behavior)";
  10542. }
  10543. } else {
  10544. // Connection failure might be due to protocol requirements
  10545. SUCCEED() << "Connection issue with request without Content-Length "
  10546. "(environment-specific)";
  10547. }
  10548. }
  10549. class LargePayloadMaxLengthTest : public ::testing::Test {
  10550. protected:
  10551. LargePayloadMaxLengthTest()
  10552. : cli_(HOST, PORT)
  10553. #ifdef CPPHTTPLIB_SSL_ENABLED
  10554. ,
  10555. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10556. #endif
  10557. {
  10558. #ifdef CPPHTTPLIB_SSL_ENABLED
  10559. cli_.enable_server_certificate_verification(false);
  10560. #endif
  10561. }
  10562. virtual void SetUp() {
  10563. // Set 10MB payload limit
  10564. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  10565. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  10566. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  10567. res.set_content("Large payload test", "text/plain");
  10568. });
  10569. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  10570. svr_.wait_until_ready();
  10571. }
  10572. virtual void TearDown() {
  10573. svr_.stop();
  10574. t_.join();
  10575. }
  10576. #ifdef CPPHTTPLIB_SSL_ENABLED
  10577. SSLClient cli_;
  10578. SSLServer svr_;
  10579. #else
  10580. Client cli_;
  10581. Server svr_;
  10582. #endif
  10583. thread t_;
  10584. };
  10585. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  10586. // Test chunked encoding with payload within 10MB limit
  10587. std::string medium_payload(5 * 1024 * 1024,
  10588. 'A'); // 5MB payload, within 10MB limit
  10589. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  10590. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10591. EXPECT_EQ(StatusCode::OK_200, res->status);
  10592. }
  10593. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  10594. // Test chunked encoding with payload exceeding 10MB limit
  10595. std::string large_payload(12 * 1024 * 1024,
  10596. 'B'); // 12MB payload, exceeds 10MB limit
  10597. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  10598. // Server may either return 413 or close the connection
  10599. if (res) {
  10600. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10601. } else {
  10602. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  10603. }
  10604. }
  10605. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  10606. // Test request without Content-Length header within 10MB limit
  10607. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10608. "Host: " +
  10609. std::string(HOST) + ":" +
  10610. std::to_string(PORT) +
  10611. "\r\n"
  10612. "Connection: close\r\n"
  10613. "\r\n";
  10614. // Add 1MB payload (within 10MB limit)
  10615. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  10616. request_without_content_length += medium_payload;
  10617. std::string response;
  10618. bool result = send_request(5, request_without_content_length, &response);
  10619. if (result) {
  10620. // Should get a proper HTTP response for payloads within limit
  10621. if (response.length() > 10) {
  10622. SUCCEED() << "Server processed 1MB request without Content-Length within "
  10623. "10MB limit";
  10624. } else {
  10625. SUCCEED() << "Server closed connection (acceptable behavior for no "
  10626. "Content-Length)";
  10627. }
  10628. } else {
  10629. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  10630. }
  10631. }
  10632. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  10633. // Test request without Content-Length header exceeding 10MB limit
  10634. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10635. "Host: " +
  10636. std::string(HOST) + ":" +
  10637. std::to_string(PORT) +
  10638. "\r\n"
  10639. "Connection: close\r\n"
  10640. "\r\n";
  10641. // Add 12MB payload (exceeds 10MB limit)
  10642. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  10643. request_without_content_length += large_payload;
  10644. std::string response;
  10645. bool result = send_request(10, request_without_content_length, &response);
  10646. if (!result) {
  10647. // Server should close connection due to payload limit
  10648. SUCCEED() << "Server rejected 12MB request without Content-Length "
  10649. "(connection closed)";
  10650. } else {
  10651. // Check for error response
  10652. if (response.length() <= 10) {
  10653. SUCCEED()
  10654. << "Server closed connection for 12MB request exceeding 10MB limit";
  10655. } else {
  10656. EXPECT_TRUE(response.find("413") != std::string::npos ||
  10657. response.find("Payload Too Large") != std::string::npos ||
  10658. response.find("400") != std::string::npos);
  10659. }
  10660. }
  10661. }
  10662. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10663. // `payload_max_length` is not enforced on decompressed body in ContentReader
  10664. // path.
  10665. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  10666. Server svr;
  10667. const size_t LIMIT = 64 * 1024; // 64KB
  10668. svr.set_payload_max_length(LIMIT);
  10669. size_t total = 0;
  10670. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  10671. const ContentReader &content_reader) {
  10672. content_reader([&](const char * /*data*/, size_t len) {
  10673. total += len;
  10674. return true;
  10675. });
  10676. res.status = 200;
  10677. res.set_content("stream_ok", "text/plain");
  10678. });
  10679. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10680. auto se = detail::scope_exit([&] {
  10681. svr.stop();
  10682. thread.join();
  10683. ASSERT_FALSE(svr.is_running());
  10684. });
  10685. svr.wait_until_ready();
  10686. // Prepare 256KB raw data and gzip-compress it
  10687. std::string raw(256 * 1024, 'A');
  10688. std::string gz;
  10689. {
  10690. z_stream zs{};
  10691. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  10692. Z_DEFAULT_STRATEGY);
  10693. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  10694. zs.avail_in = static_cast<uInt>(raw.size());
  10695. char outbuf[4096];
  10696. int ret;
  10697. do {
  10698. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  10699. zs.avail_out = sizeof(outbuf);
  10700. ret = deflate(&zs, Z_FINISH);
  10701. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  10702. } while (ret != Z_STREAM_END);
  10703. deflateEnd(&zs);
  10704. }
  10705. Client cli(HOST, PORT);
  10706. cli.set_connection_timeout(std::chrono::seconds(5));
  10707. Headers headers = {{"Content-Encoding", "gzip"}};
  10708. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  10709. "application/octet-stream");
  10710. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10711. // Server must reject oversized decompressed payloads with 413.
  10712. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10713. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  10714. EXPECT_LE(total, LIMIT);
  10715. }
  10716. #ifndef CPPHTTPLIB_SSL_ENABLED
  10717. // For a request with neither Content-Length nor Transfer-Encoding, the
  10718. // non-SSL raw-socket fallback in read_content_core() used to hand the
  10719. // compressed wire bytes straight to the ContentReader without ever routing
  10720. // them through the decompressor, so payload_max_length_ only bounded the
  10721. // compressed size on the wire, not the decompressed size.
  10722. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  10723. Server svr;
  10724. const size_t LIMIT = 64 * 1024; // 64KB
  10725. svr.set_payload_max_length(LIMIT);
  10726. size_t total = 0;
  10727. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  10728. const ContentReader &content_reader) {
  10729. content_reader([&](const char * /*data*/, size_t len) {
  10730. total += len;
  10731. return true;
  10732. });
  10733. res.status = 200;
  10734. res.set_content("stream_ok", "text/plain");
  10735. });
  10736. auto port = svr.bind_to_any_port(HOST);
  10737. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  10738. auto se = detail::scope_exit([&] {
  10739. svr.stop();
  10740. thread.join();
  10741. ASSERT_FALSE(svr.is_running());
  10742. });
  10743. svr.wait_until_ready();
  10744. // Prepare 256KB raw data and gzip-compress it, same payload as the
  10745. // StreamingGzipDecompression test above.
  10746. std::string raw(256 * 1024, 'A');
  10747. std::string gz;
  10748. {
  10749. httplib::detail::gzip_compressor compressor;
  10750. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  10751. [&](const char *chunk, size_t len) {
  10752. gz.append(chunk, len);
  10753. return true;
  10754. });
  10755. ASSERT_TRUE(result);
  10756. }
  10757. // Send the gzip body over raw TCP with neither Content-Length nor
  10758. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  10759. // kicks in.
  10760. std::string req = "POST /stream HTTP/1.1\r\n"
  10761. "Host: " +
  10762. std::string(HOST) + ":" + std::to_string(port) +
  10763. "\r\n"
  10764. "Content-Encoding: gzip\r\n"
  10765. "Connection: close\r\n"
  10766. "\r\n" +
  10767. gz;
  10768. std::string response;
  10769. ASSERT_TRUE(send_request(5, req, &response, port));
  10770. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  10771. EXPECT_LE(total, LIMIT);
  10772. }
  10773. #endif
  10774. #endif
  10775. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  10776. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  10777. // the payload must be passed through untouched instead of being rejected.
  10778. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  10779. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  10780. Server svr;
  10781. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  10782. res.set_content(body, "image/jpeg");
  10783. res.set_header("Content-Encoding", "UTF-8");
  10784. });
  10785. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  10786. res.set_content(body, "image/jpeg");
  10787. res.set_header("Content-Encoding", "identity");
  10788. });
  10789. svr.Post("/echo", [](const Request &req, Response &res) {
  10790. res.set_content(req.body, "image/jpeg");
  10791. });
  10792. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10793. auto se = detail::scope_exit([&] {
  10794. svr.stop();
  10795. t.join();
  10796. ASSERT_FALSE(svr.is_running());
  10797. });
  10798. svr.wait_until_ready();
  10799. Client cli(HOST, PORT);
  10800. {
  10801. auto res = cli.Get("/image");
  10802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10803. EXPECT_EQ(StatusCode::OK_200, res->status);
  10804. EXPECT_EQ(body, res->body);
  10805. }
  10806. {
  10807. auto res = cli.Get("/identity");
  10808. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10809. EXPECT_EQ(StatusCode::OK_200, res->status);
  10810. EXPECT_EQ(body, res->body);
  10811. }
  10812. {
  10813. // The same applies to a request body reaching the server.
  10814. Headers headers = {{"Content-Encoding", "UTF-8"}};
  10815. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  10816. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10817. EXPECT_EQ(StatusCode::OK_200, res->status);
  10818. EXPECT_EQ(body, res->body);
  10819. }
  10820. }
  10821. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  10822. // gzip-encoded response even when the build has no zlib support.
  10823. static const char GZIPPED_HELLO_WORLD[] = {
  10824. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  10825. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  10826. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  10827. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  10828. // A content coding is a whole token, not something the field value merely
  10829. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  10830. // as "fibre" look like Brotli, and turned a multi-coding value like
  10831. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  10832. // it was never meant to see.
  10833. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  10834. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  10835. Server svr;
  10836. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  10837. res.set_content(body, "image/jpeg");
  10838. res.set_header("Content-Encoding", "fibre");
  10839. });
  10840. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  10841. res.set_content(body, "image/jpeg");
  10842. res.set_header("Content-Encoding", "gzip, br");
  10843. });
  10844. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  10845. res.set_content(body, "image/jpeg");
  10846. res.set_header("Content-Encoding", "x-zstd-ish");
  10847. });
  10848. auto port = svr.bind_to_any_port(HOST);
  10849. thread t = thread([&]() { svr.listen_after_bind(); });
  10850. auto se = detail::scope_exit([&] {
  10851. svr.stop();
  10852. t.join();
  10853. ASSERT_FALSE(svr.is_running());
  10854. });
  10855. svr.wait_until_ready();
  10856. Client cli(HOST, port);
  10857. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  10858. auto res = cli.Get(path);
  10859. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  10860. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  10861. // Not a coding we recognize, so the payload comes back untouched
  10862. EXPECT_EQ(body, res->body) << path;
  10863. }
  10864. }
  10865. // A content coding cpp-httplib recognizes but was not built with must be
  10866. // reported as such. Handing the still-compressed payload back to the caller
  10867. // would silently corrupt it.
  10868. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  10869. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  10870. Server svr;
  10871. // "image/jpeg" keeps the server from applying a content coding of its own,
  10872. // so the hand-crafted Content-Encoding below survives.
  10873. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  10874. res.set_content(gzipped, "image/jpeg");
  10875. res.set_header("Content-Encoding", "gzip");
  10876. });
  10877. // Content codings are case-insensitive (RFC 9110 8.4.1).
  10878. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  10879. res.set_content(gzipped, "image/jpeg");
  10880. res.set_header("Content-Encoding", "GZIP");
  10881. });
  10882. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10883. auto se = detail::scope_exit([&] {
  10884. svr.stop();
  10885. t.join();
  10886. ASSERT_FALSE(svr.is_running());
  10887. });
  10888. svr.wait_until_ready();
  10889. Client cli(HOST, PORT);
  10890. {
  10891. auto res = cli.Get("/gzipped");
  10892. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10893. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10894. EXPECT_EQ("Hello World!", res->body);
  10895. #else
  10896. ASSERT_FALSE(res);
  10897. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  10898. #endif
  10899. }
  10900. {
  10901. // open_stream() must behave the same way.
  10902. auto handle = cli.open_stream("GET", "/gzipped");
  10903. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10904. ASSERT_TRUE(handle.is_valid());
  10905. std::string received;
  10906. char buf[256];
  10907. ssize_t n;
  10908. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  10909. received.append(buf, static_cast<size_t>(n));
  10910. }
  10911. EXPECT_EQ("Hello World!", received);
  10912. #else
  10913. EXPECT_FALSE(handle.is_valid());
  10914. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  10915. #endif
  10916. }
  10917. {
  10918. // A differently-cased coding must not be mistaken for an unknown one, or
  10919. // the body would be handed back still compressed.
  10920. auto res = cli.Get("/gzipped-uppercase");
  10921. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10922. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10923. EXPECT_EQ("Hello World!", res->body);
  10924. #else
  10925. ASSERT_FALSE(res);
  10926. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  10927. #endif
  10928. }
  10929. }
  10930. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10931. // A handler serving pre-compressed content (e.g. build-time gzipped static
  10932. // assets) sets Content-Encoding itself. The server used to pick a coding from
  10933. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  10934. // body a second time and appending a second Content-Encoding field line, so
  10935. // clients that decode one coding per listed value handed back raw gzip bytes.
  10936. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  10937. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  10938. Server svr;
  10939. // text/plain is a compressible type, so only the pre-set Content-Encoding
  10940. // keeps the server from applying a coding of its own.
  10941. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  10942. res.set_content(gzipped, "text/plain");
  10943. res.set_header("Content-Encoding", "gzip");
  10944. });
  10945. auto port = svr.bind_to_any_port(HOST);
  10946. thread t = thread([&]() { svr.listen_after_bind(); });
  10947. auto se = detail::scope_exit([&] {
  10948. svr.stop();
  10949. t.join();
  10950. ASSERT_FALSE(svr.is_running());
  10951. });
  10952. svr.wait_until_ready();
  10953. Client cli(HOST, port);
  10954. Headers headers = {{"Accept-Encoding", "gzip"}};
  10955. auto res = cli.Get("/pre-gzipped", headers);
  10956. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10957. EXPECT_EQ(StatusCode::OK_200, res->status);
  10958. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  10959. EXPECT_EQ("Hello World!", res->body);
  10960. }
  10961. // A chunked provider settles its coding where the headers are written and
  10962. // reuses it at write time. Both ends of that have to hold: a handler's own
  10963. // Content-Encoding suppresses the coding, and a response without one is still
  10964. // compressed as it always was.
  10965. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  10966. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  10967. const std::string plain = "Hello World! Hello World! Hello World!";
  10968. Server svr;
  10969. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  10970. res.set_header("Content-Encoding", "gzip");
  10971. res.set_chunked_content_provider(
  10972. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  10973. sink.write(gzipped.data(), gzipped.size());
  10974. sink.done();
  10975. return true;
  10976. });
  10977. });
  10978. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  10979. res.set_chunked_content_provider(
  10980. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  10981. sink.write(plain.data(), plain.size());
  10982. sink.done();
  10983. return true;
  10984. });
  10985. });
  10986. auto port = svr.bind_to_any_port(HOST);
  10987. thread t = thread([&]() { svr.listen_after_bind(); });
  10988. auto se = detail::scope_exit([&] {
  10989. svr.stop();
  10990. t.join();
  10991. ASSERT_FALSE(svr.is_running());
  10992. });
  10993. svr.wait_until_ready();
  10994. Client cli(HOST, port);
  10995. Headers headers = {{"Accept-Encoding", "gzip"}};
  10996. {
  10997. auto res = cli.Get("/pre-gzipped", headers);
  10998. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10999. EXPECT_EQ(StatusCode::OK_200, res->status);
  11000. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  11001. EXPECT_EQ("Hello World!", res->body);
  11002. }
  11003. {
  11004. auto res = cli.Get("/negotiated", headers);
  11005. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11006. EXPECT_EQ(StatusCode::OK_200, res->status);
  11007. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  11008. EXPECT_EQ(plain, res->body);
  11009. }
  11010. }
  11011. #endif
  11012. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  11013. // the same message as the comma-joined one, so both have to be read the same
  11014. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  11015. // single gzip coding, and a body the sender says was encoded twice was handed
  11016. // back after one pass, still compressed but presented as decoded.
  11017. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  11018. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11019. Server svr;
  11020. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  11021. res.set_content(body, "image/jpeg");
  11022. res.headers.emplace("Content-Encoding", "gzip");
  11023. res.headers.emplace("Content-Encoding", "gzip");
  11024. });
  11025. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  11026. res.set_content(body, "image/jpeg");
  11027. res.set_header("Content-Encoding", "gzip, gzip");
  11028. });
  11029. auto port = svr.bind_to_any_port(HOST);
  11030. thread t = thread([&]() { svr.listen_after_bind(); });
  11031. auto se = detail::scope_exit([&] {
  11032. svr.stop();
  11033. t.join();
  11034. ASSERT_FALSE(svr.is_running());
  11035. });
  11036. svr.wait_until_ready();
  11037. Client cli(HOST, port);
  11038. // Two codings is not something cpp-httplib decodes, so both representations
  11039. // take the pass-through path rather than one of them being gunzipped once.
  11040. for (const char *path : {"/split", "/joined"}) {
  11041. auto res = cli.Get(path);
  11042. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  11043. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11044. EXPECT_EQ(body, res->body) << path;
  11045. }
  11046. }
  11047. // Regression test for DoS vulnerability: a malicious server sending a response
  11048. // without Content-Length header must not cause unbounded memory consumption on
  11049. // the client side. The client should stop reading after a reasonable limit,
  11050. // similar to the server-side set_payload_max_length protection.
  11051. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  11052. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  11053. #ifndef _WIN32
  11054. signal(SIGPIPE, SIG_IGN);
  11055. #endif
  11056. auto server_thread = std::thread([] {
  11057. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  11058. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11059. default_socket_options(srv);
  11060. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11061. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11062. sockaddr_in addr{};
  11063. addr.sin_family = AF_INET;
  11064. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11065. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11066. int opt = 1;
  11067. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11068. #ifdef _WIN32
  11069. reinterpret_cast<const char *>(&opt),
  11070. #else
  11071. &opt,
  11072. #endif
  11073. sizeof(opt));
  11074. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11075. ::listen(srv, 1);
  11076. sockaddr_in cli_addr{};
  11077. socklen_t cli_len = sizeof(cli_addr);
  11078. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11079. if (cli != INVALID_SOCKET) {
  11080. char buf[4096];
  11081. ::recv(cli, buf, sizeof(buf), 0);
  11082. // Malicious response: no Content-Length, no chunked encoding
  11083. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11084. "Connection: close\r\n"
  11085. "\r\n";
  11086. ::send(cli,
  11087. #ifdef _WIN32
  11088. static_cast<const char *>(response_header.c_str()),
  11089. static_cast<int>(response_header.size()),
  11090. #else
  11091. response_header.c_str(), response_header.size(),
  11092. #endif
  11093. 0);
  11094. // Send 10MB of data
  11095. std::string chunk(64 * 1024, 'A');
  11096. size_t total_sent = 0;
  11097. while (total_sent < MALICIOUS_DATA_SIZE) {
  11098. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  11099. auto sent = ::send(cli,
  11100. #ifdef _WIN32
  11101. static_cast<const char *>(chunk.c_str()),
  11102. static_cast<int>(to_send),
  11103. #else
  11104. chunk.c_str(), to_send,
  11105. #endif
  11106. 0);
  11107. if (sent <= 0) break;
  11108. total_sent += static_cast<size_t>(sent);
  11109. }
  11110. detail::close_socket(cli);
  11111. }
  11112. detail::close_socket(srv);
  11113. });
  11114. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11115. size_t total_read = 0;
  11116. {
  11117. Client cli("127.0.0.1", PORT + 2);
  11118. cli.set_read_timeout(5, 0);
  11119. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  11120. auto stream = cli.open_stream("GET", "/malicious");
  11121. ASSERT_TRUE(stream.is_valid());
  11122. char buffer[64 * 1024];
  11123. ssize_t n;
  11124. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11125. total_read += static_cast<size_t>(n);
  11126. }
  11127. } // StreamHandle and Client destroyed here, closing the socket
  11128. server_thread.join();
  11129. // With set_payload_max_length, the client must stop reading before consuming
  11130. // all 10MB. The read loop should be cut off at or near the configured limit.
  11131. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  11132. << "Client read " << total_read << " bytes, exceeding the configured "
  11133. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  11134. }
  11135. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  11136. // the entire response body without truncation.
  11137. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  11138. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  11139. #ifndef _WIN32
  11140. signal(SIGPIPE, SIG_IGN);
  11141. #endif
  11142. auto server_thread = std::thread([] {
  11143. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11144. default_socket_options(srv);
  11145. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11146. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11147. sockaddr_in addr{};
  11148. addr.sin_family = AF_INET;
  11149. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11150. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11151. int opt = 1;
  11152. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11153. #ifdef _WIN32
  11154. reinterpret_cast<const char *>(&opt),
  11155. #else
  11156. &opt,
  11157. #endif
  11158. sizeof(opt));
  11159. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11160. ::listen(srv, 1);
  11161. sockaddr_in cli_addr{};
  11162. socklen_t cli_len = sizeof(cli_addr);
  11163. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11164. if (cli != INVALID_SOCKET) {
  11165. char buf[4096];
  11166. ::recv(cli, buf, sizeof(buf), 0);
  11167. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11168. "Connection: close\r\n"
  11169. "\r\n";
  11170. ::send(cli,
  11171. #ifdef _WIN32
  11172. static_cast<const char *>(response_header.c_str()),
  11173. static_cast<int>(response_header.size()),
  11174. #else
  11175. response_header.c_str(), response_header.size(),
  11176. #endif
  11177. 0);
  11178. std::string chunk(64 * 1024, 'A');
  11179. size_t total_sent = 0;
  11180. while (total_sent < DATA_SIZE) {
  11181. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11182. auto sent = ::send(cli,
  11183. #ifdef _WIN32
  11184. static_cast<const char *>(chunk.c_str()),
  11185. static_cast<int>(to_send),
  11186. #else
  11187. chunk.c_str(), to_send,
  11188. #endif
  11189. 0);
  11190. if (sent <= 0) break;
  11191. total_sent += static_cast<size_t>(sent);
  11192. }
  11193. #ifdef _WIN32
  11194. ::shutdown(cli, SD_SEND);
  11195. #else
  11196. ::shutdown(cli, SHUT_WR);
  11197. #endif
  11198. // Drain until the client closes its end, ensuring all data is delivered
  11199. char drain[1024];
  11200. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  11201. detail::close_socket(cli);
  11202. }
  11203. detail::close_socket(srv);
  11204. });
  11205. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11206. size_t total_read = 0;
  11207. {
  11208. Client cli("127.0.0.1", PORT + 2);
  11209. cli.set_read_timeout(5, 0);
  11210. cli.set_payload_max_length(0); // 0 means no limit
  11211. auto stream = cli.open_stream("GET", "/data");
  11212. ASSERT_TRUE(stream.is_valid());
  11213. char buffer[64 * 1024];
  11214. ssize_t n;
  11215. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11216. total_read += static_cast<size_t>(n);
  11217. }
  11218. }
  11219. server_thread.join();
  11220. EXPECT_EQ(total_read, DATA_SIZE)
  11221. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  11222. << " bytes without truncation, but only read " << total_read << " bytes.";
  11223. }
  11224. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  11225. // enormous Content-Length must not cause the client to pre-allocate a huge
  11226. // response body buffer. The reservation is capped at payload_max_length_, and
  11227. // the read itself fails when the body exceeds the limit.
  11228. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  11229. #ifndef _WIN32
  11230. signal(SIGPIPE, SIG_IGN);
  11231. #endif
  11232. auto server_thread = std::thread([] {
  11233. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11234. default_socket_options(srv);
  11235. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11236. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11237. sockaddr_in addr{};
  11238. addr.sin_family = AF_INET;
  11239. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11240. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11241. int opt = 1;
  11242. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11243. #ifdef _WIN32
  11244. reinterpret_cast<const char *>(&opt),
  11245. #else
  11246. &opt,
  11247. #endif
  11248. sizeof(opt));
  11249. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11250. ::listen(srv, 1);
  11251. sockaddr_in cli_addr{};
  11252. socklen_t cli_len = sizeof(cli_addr);
  11253. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11254. if (cli != INVALID_SOCKET) {
  11255. char buf[4096];
  11256. ::recv(cli, buf, sizeof(buf), 0);
  11257. // Malicious response: claim a 20GB body but send only a tiny payload.
  11258. std::string response = "HTTP/1.1 200 OK\r\n"
  11259. "Content-Length: 20000000000\r\n"
  11260. "\r\n"
  11261. "abc";
  11262. ::send(cli,
  11263. #ifdef _WIN32
  11264. static_cast<const char *>(response.c_str()),
  11265. static_cast<int>(response.size()),
  11266. #else
  11267. response.c_str(), response.size(),
  11268. #endif
  11269. 0);
  11270. detail::close_socket(cli);
  11271. }
  11272. detail::close_socket(srv);
  11273. });
  11274. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11275. {
  11276. Client cli("127.0.0.1", PORT + 2);
  11277. cli.set_read_timeout(5, 0);
  11278. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  11279. // result in a 20GB pre-allocation. The Get() call is expected to fail
  11280. // (server claims more bytes than payload_max_length permits), but it must
  11281. // not exhaust memory before getting there.
  11282. auto res = cli.Get("/malicious");
  11283. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  11284. }
  11285. server_thread.join();
  11286. }
  11287. // Verify that content_receiver bypasses the default payload_max_length,
  11288. // allowing streaming downloads larger than 100MB without requiring an explicit
  11289. // set_payload_max_length call.
  11290. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  11291. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11292. #ifndef _WIN32
  11293. signal(SIGPIPE, SIG_IGN);
  11294. #endif
  11295. auto server_thread = std::thread([] {
  11296. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11297. default_socket_options(srv);
  11298. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11299. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11300. sockaddr_in addr{};
  11301. addr.sin_family = AF_INET;
  11302. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11303. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11304. int opt = 1;
  11305. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11306. #ifdef _WIN32
  11307. reinterpret_cast<const char *>(&opt),
  11308. #else
  11309. &opt,
  11310. #endif
  11311. sizeof(opt));
  11312. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11313. ::listen(srv, 1);
  11314. sockaddr_in cli_addr{};
  11315. socklen_t cli_len = sizeof(cli_addr);
  11316. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11317. if (cli != INVALID_SOCKET) {
  11318. char buf[4096];
  11319. ::recv(cli, buf, sizeof(buf), 0);
  11320. // Response with Content-Length larger than default 100MB limit
  11321. auto content_length = std::to_string(DATA_SIZE);
  11322. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11323. "Content-Length: " +
  11324. content_length +
  11325. "\r\n"
  11326. "Connection: close\r\n"
  11327. "\r\n";
  11328. ::send(cli,
  11329. #ifdef _WIN32
  11330. static_cast<const char *>(response_header.c_str()),
  11331. static_cast<int>(response_header.size()),
  11332. #else
  11333. response_header.c_str(), response_header.size(),
  11334. #endif
  11335. 0);
  11336. std::string chunk(64 * 1024, 'A');
  11337. size_t total_sent = 0;
  11338. while (total_sent < DATA_SIZE) {
  11339. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11340. auto sent = ::send(cli,
  11341. #ifdef _WIN32
  11342. static_cast<const char *>(chunk.c_str()),
  11343. static_cast<int>(to_send),
  11344. #else
  11345. chunk.c_str(), to_send,
  11346. #endif
  11347. 0);
  11348. if (sent <= 0) break;
  11349. total_sent += static_cast<size_t>(sent);
  11350. }
  11351. detail::close_socket(cli);
  11352. }
  11353. detail::close_socket(srv);
  11354. });
  11355. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11356. size_t total_received = 0;
  11357. {
  11358. Client cli("127.0.0.1", PORT + 2);
  11359. cli.set_read_timeout(10, 0);
  11360. // Do NOT call set_payload_max_length — use the default 100MB limit
  11361. auto res =
  11362. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11363. total_received += data_length;
  11364. return true;
  11365. });
  11366. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11367. EXPECT_EQ(StatusCode::OK_200, res->status);
  11368. }
  11369. server_thread.join();
  11370. EXPECT_EQ(total_received, DATA_SIZE)
  11371. << "With content_receiver, the client should read all " << DATA_SIZE
  11372. << " bytes despite the default 100MB payload_max_length, but only read "
  11373. << total_received << " bytes.";
  11374. }
  11375. // Verify that an explicit set_payload_max_length smaller than the response is
  11376. // enforced even when a content_receiver is used.
  11377. TEST(ClientVulnerabilityTest,
  11378. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  11379. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11380. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  11381. #ifndef _WIN32
  11382. signal(SIGPIPE, SIG_IGN);
  11383. #endif
  11384. auto server_thread = std::thread([] {
  11385. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11386. default_socket_options(srv);
  11387. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11388. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11389. sockaddr_in addr{};
  11390. addr.sin_family = AF_INET;
  11391. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11392. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11393. int opt = 1;
  11394. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11395. #ifdef _WIN32
  11396. reinterpret_cast<const char *>(&opt),
  11397. #else
  11398. &opt,
  11399. #endif
  11400. sizeof(opt));
  11401. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11402. ::listen(srv, 1);
  11403. sockaddr_in cli_addr{};
  11404. socklen_t cli_len = sizeof(cli_addr);
  11405. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11406. if (cli != INVALID_SOCKET) {
  11407. char buf[4096];
  11408. ::recv(cli, buf, sizeof(buf), 0);
  11409. auto content_length = std::to_string(DATA_SIZE);
  11410. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11411. "Content-Length: " +
  11412. content_length +
  11413. "\r\n"
  11414. "Connection: close\r\n"
  11415. "\r\n";
  11416. ::send(cli,
  11417. #ifdef _WIN32
  11418. static_cast<const char *>(response_header.c_str()),
  11419. static_cast<int>(response_header.size()),
  11420. #else
  11421. response_header.c_str(), response_header.size(),
  11422. #endif
  11423. 0);
  11424. std::string chunk(64 * 1024, 'A');
  11425. size_t total_sent = 0;
  11426. while (total_sent < DATA_SIZE) {
  11427. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11428. auto sent = ::send(cli,
  11429. #ifdef _WIN32
  11430. static_cast<const char *>(chunk.c_str()),
  11431. static_cast<int>(to_send),
  11432. #else
  11433. chunk.c_str(), to_send,
  11434. #endif
  11435. 0);
  11436. if (sent <= 0) break;
  11437. total_sent += static_cast<size_t>(sent);
  11438. }
  11439. detail::close_socket(cli);
  11440. }
  11441. detail::close_socket(srv);
  11442. });
  11443. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11444. size_t total_received = 0;
  11445. {
  11446. Client cli("127.0.0.1", PORT + 2);
  11447. cli.set_read_timeout(10, 0);
  11448. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  11449. auto res =
  11450. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11451. total_received += data_length;
  11452. return true;
  11453. });
  11454. // Should fail because 200MB exceeds the explicit 150MB limit
  11455. EXPECT_FALSE(res);
  11456. }
  11457. server_thread.join();
  11458. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  11459. << "Client with content_receiver should respect the explicit "
  11460. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  11461. << total_received << " bytes.";
  11462. }
  11463. // Verify that an explicit set_payload_max_length larger than the response
  11464. // allows the content_receiver to read all data successfully.
  11465. TEST(ClientVulnerabilityTest,
  11466. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  11467. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11468. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  11469. #ifndef _WIN32
  11470. signal(SIGPIPE, SIG_IGN);
  11471. #endif
  11472. auto server_thread = std::thread([] {
  11473. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11474. default_socket_options(srv);
  11475. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11476. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11477. sockaddr_in addr{};
  11478. addr.sin_family = AF_INET;
  11479. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11480. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11481. int opt = 1;
  11482. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11483. #ifdef _WIN32
  11484. reinterpret_cast<const char *>(&opt),
  11485. #else
  11486. &opt,
  11487. #endif
  11488. sizeof(opt));
  11489. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11490. ::listen(srv, 1);
  11491. sockaddr_in cli_addr{};
  11492. socklen_t cli_len = sizeof(cli_addr);
  11493. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11494. if (cli != INVALID_SOCKET) {
  11495. char buf[4096];
  11496. ::recv(cli, buf, sizeof(buf), 0);
  11497. auto content_length = std::to_string(DATA_SIZE);
  11498. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11499. "Content-Length: " +
  11500. content_length +
  11501. "\r\n"
  11502. "Connection: close\r\n"
  11503. "\r\n";
  11504. ::send(cli,
  11505. #ifdef _WIN32
  11506. static_cast<const char *>(response_header.c_str()),
  11507. static_cast<int>(response_header.size()),
  11508. #else
  11509. response_header.c_str(), response_header.size(),
  11510. #endif
  11511. 0);
  11512. std::string chunk(64 * 1024, 'A');
  11513. size_t total_sent = 0;
  11514. while (total_sent < DATA_SIZE) {
  11515. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11516. auto sent = ::send(cli,
  11517. #ifdef _WIN32
  11518. static_cast<const char *>(chunk.c_str()),
  11519. static_cast<int>(to_send),
  11520. #else
  11521. chunk.c_str(), to_send,
  11522. #endif
  11523. 0);
  11524. if (sent <= 0) break;
  11525. total_sent += static_cast<size_t>(sent);
  11526. }
  11527. #ifdef _WIN32
  11528. ::shutdown(cli, SD_SEND);
  11529. #else
  11530. ::shutdown(cli, SHUT_WR);
  11531. #endif
  11532. char drain[1024];
  11533. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  11534. detail::close_socket(cli);
  11535. }
  11536. detail::close_socket(srv);
  11537. });
  11538. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11539. size_t total_received = 0;
  11540. {
  11541. Client cli("127.0.0.1", PORT + 2);
  11542. cli.set_read_timeout(10, 0);
  11543. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  11544. auto res =
  11545. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11546. total_received += data_length;
  11547. return true;
  11548. });
  11549. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11550. EXPECT_EQ(StatusCode::OK_200, res->status);
  11551. }
  11552. server_thread.join();
  11553. EXPECT_EQ(total_received, DATA_SIZE)
  11554. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  11555. << " bytes (larger than " << DATA_SIZE
  11556. << " bytes response), content_receiver should read all data, but only "
  11557. "read "
  11558. << total_received << " bytes.";
  11559. }
  11560. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  11561. // Regression test for "zip bomb" attack on the client side: a malicious server
  11562. // sends a small gzip-compressed response that decompresses to a huge payload.
  11563. // The client must enforce payload_max_length on the decompressed size.
  11564. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  11565. constexpr size_t DECOMPRESSED_SIZE =
  11566. 10 * 1024 * 1024; // 10MB after decompression
  11567. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  11568. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  11569. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  11570. std::string compressed;
  11571. {
  11572. httplib::detail::gzip_compressor compressor;
  11573. bool ok =
  11574. compressor.compress(uncompressed.data(), uncompressed.size(),
  11575. /*last=*/true, [&](const char *buf, size_t len) {
  11576. compressed.append(buf, len);
  11577. return true;
  11578. });
  11579. ASSERT_TRUE(ok);
  11580. }
  11581. // Sanity: compressed data should be much smaller than the decompressed size
  11582. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  11583. #ifndef _WIN32
  11584. signal(SIGPIPE, SIG_IGN);
  11585. #endif
  11586. // Set up the listening socket in the main thread so the server is guaranteed
  11587. // to be ready before the client connects (eliminates race condition).
  11588. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11589. default_socket_options(srv);
  11590. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11591. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11592. sockaddr_in addr{};
  11593. addr.sin_family = AF_INET;
  11594. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  11595. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11596. int opt = 1;
  11597. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11598. #ifdef _WIN32
  11599. reinterpret_cast<const char *>(&opt),
  11600. #else
  11601. &opt,
  11602. #endif
  11603. sizeof(opt));
  11604. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  11605. ASSERT_EQ(0, ::listen(srv, 1));
  11606. auto server_thread = std::thread([&compressed, srv] {
  11607. sockaddr_in cli_addr{};
  11608. socklen_t cli_len = sizeof(cli_addr);
  11609. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11610. if (cli != INVALID_SOCKET) {
  11611. // Read the full HTTP request (until \r\n\r\n)
  11612. char buf[4096];
  11613. size_t total = 0;
  11614. while (total < sizeof(buf)) {
  11615. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  11616. if (n <= 0) break;
  11617. total += static_cast<size_t>(n);
  11618. // Check for end of headers
  11619. if (total >= 4) {
  11620. std::string req(buf, total);
  11621. if (req.find("\r\n\r\n") != std::string::npos) break;
  11622. }
  11623. }
  11624. // Malicious response: gzip-compressed body, no Content-Length
  11625. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11626. "Content-Encoding: gzip\r\n"
  11627. "Connection: close\r\n"
  11628. "\r\n";
  11629. ::send(cli,
  11630. #ifdef _WIN32
  11631. static_cast<const char *>(response_header.c_str()),
  11632. static_cast<int>(response_header.size()),
  11633. #else
  11634. response_header.c_str(), response_header.size(),
  11635. #endif
  11636. 0);
  11637. // Send the compressed payload (small on the wire, huge when decompressed)
  11638. size_t total_sent = 0;
  11639. while (total_sent < compressed.size()) {
  11640. auto to_send = std::min(compressed.size() - total_sent,
  11641. static_cast<size_t>(64 * 1024));
  11642. auto sent =
  11643. ::send(cli,
  11644. #ifdef _WIN32
  11645. static_cast<const char *>(compressed.c_str() + total_sent),
  11646. static_cast<int>(to_send),
  11647. #else
  11648. compressed.c_str() + total_sent, to_send,
  11649. #endif
  11650. 0);
  11651. if (sent <= 0) break;
  11652. total_sent += static_cast<size_t>(sent);
  11653. }
  11654. detail::close_socket(cli);
  11655. }
  11656. });
  11657. auto se = detail::scope_exit([&] {
  11658. detail::close_socket(srv);
  11659. server_thread.join();
  11660. });
  11661. size_t total_decompressed = 0;
  11662. {
  11663. Client cli("127.0.0.1", PORT + 3);
  11664. cli.set_read_timeout(5, 0);
  11665. cli.set_decompress(true);
  11666. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  11667. auto stream = cli.open_stream("GET", "/zipbomb");
  11668. ASSERT_TRUE(stream.is_valid());
  11669. char buffer[64 * 1024];
  11670. ssize_t n;
  11671. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11672. total_decompressed += static_cast<size_t>(n);
  11673. }
  11674. }
  11675. // The decompressed size must be capped by payload_max_length. Without
  11676. // protection, the client would decompress the full 10MB from a tiny
  11677. // compressed payload, enabling a zip bomb DoS attack.
  11678. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  11679. << "Client decompressed " << total_decompressed
  11680. << " bytes from a gzip response. The decompressed size should be "
  11681. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  11682. }
  11683. #endif
  11684. TEST(HostAndPortPropertiesTest, NoSSL) {
  11685. httplib::Client cli("www.google.com", 1234);
  11686. ASSERT_EQ("www.google.com", cli.host());
  11687. ASSERT_EQ(1234, cli.port());
  11688. }
  11689. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  11690. httplib::Client cli("www.google.com:1234");
  11691. ASSERT_EQ("www.google.com", cli.host());
  11692. ASSERT_EQ(1234, cli.port());
  11693. }
  11694. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  11695. // Port number that overflows int — should not crash, client becomes invalid
  11696. httplib::Client cli("http://www.google.com:99999999999999999999");
  11697. ASSERT_FALSE(cli.is_valid());
  11698. }
  11699. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  11700. // Port 99999 exceeds valid range (1-65535) — should not crash
  11701. httplib::Client cli("http://www.google.com:99999");
  11702. ASSERT_FALSE(cli.is_valid());
  11703. }
  11704. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  11705. httplib::Client cli("http://www.google.com:80abc");
  11706. ASSERT_FALSE(cli.is_valid());
  11707. }
  11708. #ifdef CPPHTTPLIB_SSL_ENABLED
  11709. TEST(HostAndPortPropertiesTest, SSL) {
  11710. httplib::SSLClient cli("www.google.com");
  11711. ASSERT_EQ("www.google.com", cli.host());
  11712. ASSERT_EQ(443, cli.port());
  11713. }
  11714. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  11715. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  11716. std::string cert;
  11717. read_file(CA_CERT_FILE, cert);
  11718. httplib::SSLClient httplib_client("www.google.com");
  11719. // Load CA store first time
  11720. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  11721. // Load CA store second time (update)
  11722. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  11723. // Verify client is still valid and can make connections
  11724. httplib_client.enable_server_certificate_verification(true);
  11725. auto res = httplib_client.Get("/");
  11726. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11727. // Google may return 200 or 301 depending on various factors
  11728. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  11729. res->status == StatusCode::MovedPermanently_301);
  11730. }
  11731. TEST(SSLClientTest, ServerNameIndication_Online) {
  11732. auto host = "httpbingo.org";
  11733. auto path = std::string{"/get"};
  11734. SSLClient cli(host, 443);
  11735. auto res = cli.Get(path);
  11736. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11737. ASSERT_EQ(StatusCode::OK_200, res->status);
  11738. }
  11739. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  11740. // Use a site that will cause SSL verification failure due to self-signed cert
  11741. SSLClient cli("self-signed.badssl.com", 443);
  11742. cli.enable_server_certificate_verification(true);
  11743. auto res = cli.Get("/");
  11744. ASSERT_TRUE(!res);
  11745. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11746. // Verify backend error is captured for SSLServerVerification
  11747. // This occurs when certificate verification fails
  11748. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  11749. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  11750. EXPECT_NE(0UL, res.ssl_backend_error());
  11751. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11752. // For OpenSSL, ssl_error is 0 for verification errors
  11753. EXPECT_EQ(0, res.ssl_error());
  11754. #if !defined(_WIN32) || \
  11755. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  11756. // On non-Windows or when Windows Schannel is disabled, the error comes
  11757. // from OpenSSL's verification
  11758. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  11759. res.ssl_backend_error());
  11760. #endif
  11761. #endif
  11762. }
  11763. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  11764. // Use a site where hostname doesn't match the certificate
  11765. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  11766. SSLClient cli("wrong.host.badssl.com", 443);
  11767. cli.enable_server_certificate_verification(true);
  11768. cli.enable_server_hostname_verification(true);
  11769. auto res = cli.Get("/");
  11770. ASSERT_TRUE(!res);
  11771. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  11772. // Verify backend error is captured for hostname verification failure
  11773. EXPECT_NE(0UL, res.ssl_backend_error());
  11774. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11775. // For OpenSSL, ssl_error is 0 for verification errors
  11776. EXPECT_EQ(0, res.ssl_error());
  11777. #if !defined(_WIN32) || \
  11778. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  11779. // On non-Windows or when Windows Schannel is disabled, the error comes
  11780. // from OpenSSL's hostname verification
  11781. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  11782. res.ssl_backend_error());
  11783. #endif
  11784. #endif
  11785. }
  11786. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  11787. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  11788. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  11789. SSLClient cli("www.google.com", 443);
  11790. cli.enable_server_certificate_verification(true);
  11791. auto res = cli.Get("/");
  11792. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  11793. }
  11794. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  11795. SSLClient cli("www.google.com", 443);
  11796. cli.enable_server_certificate_verification(true);
  11797. cli.enable_windows_certificate_verification(false);
  11798. auto res = cli.Get("/");
  11799. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  11800. }
  11801. // The server sends an intermediate cross-signed by a root Windows trusts,
  11802. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  11803. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  11804. SSLClient cli("accounts.spotify.com", 443);
  11805. auto res = cli.Get("/");
  11806. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  11807. << " ssl_backend_error=" << res.ssl_backend_error();
  11808. }
  11809. // Windows, not the backend, decides on the chain: the error carries a
  11810. // CryptoAPI trust status, which no backend error for a self-signed
  11811. // certificate has.
  11812. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  11813. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11814. ASSERT_TRUE(svr.is_valid());
  11815. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11816. auto se = detail::scope_exit([&] {
  11817. svr.stop();
  11818. t.join();
  11819. ASSERT_FALSE(svr.is_running());
  11820. });
  11821. svr.wait_until_ready();
  11822. SSLClient cli("127.0.0.1", PORT);
  11823. cli.set_connection_timeout(30);
  11824. auto res = cli.Get("/");
  11825. ASSERT_FALSE(res);
  11826. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11827. EXPECT_NE(0u, res.ssl_backend_error() & CERT_TRUST_IS_UNTRUSTED_ROOT)
  11828. << "ssl_backend_error=" << res.ssl_backend_error();
  11829. }
  11830. #endif
  11831. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  11832. Client cli("https://google.com");
  11833. auto res = cli.Get("/");
  11834. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11835. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11836. }
  11837. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  11838. SSLClient cli("google.com");
  11839. cli.set_ca_cert_path(CA_CERT_FILE);
  11840. auto res = cli.Get("/");
  11841. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11842. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11843. }
  11844. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  11845. SSLClient cli("google.com");
  11846. cli.enable_server_certificate_verification(true);
  11847. cli.set_ca_cert_path("hello");
  11848. auto res = cli.Get("/");
  11849. ASSERT_TRUE(!res);
  11850. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  11851. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  11852. // should be set
  11853. EXPECT_EQ(0, res.ssl_error());
  11854. // Verify backend error is captured for SSLLoadingCerts
  11855. // This error occurs when loading CA certificates fails
  11856. EXPECT_NE(0UL, res.ssl_backend_error());
  11857. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11858. // OpenSSL specific error codes:
  11859. // > openssl errstr 0x80000002
  11860. // error:80000002:system library::No such file or directory
  11861. // > openssl errstr 0xA000126
  11862. // error:0A000126:SSL routines::unexpected eof while reading
  11863. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  11864. res.ssl_backend_error() == 0xA000126);
  11865. #endif
  11866. }
  11867. TEST(SSLClientTest, ServerCertificateVerification4) {
  11868. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11869. ASSERT_TRUE(svr.is_valid());
  11870. svr.Get("/test", [&](const Request &, Response &res) {
  11871. res.set_content("test", "text/plain");
  11872. svr.stop();
  11873. ASSERT_TRUE(true);
  11874. });
  11875. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11876. auto se = detail::scope_exit([&] {
  11877. t.join();
  11878. ASSERT_FALSE(svr.is_running());
  11879. });
  11880. svr.wait_until_ready();
  11881. SSLClient cli("127.0.0.1", PORT);
  11882. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  11883. cli.enable_server_certificate_verification(true);
  11884. cli.set_connection_timeout(30);
  11885. auto res = cli.Get("/test");
  11886. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11887. ASSERT_EQ(StatusCode::OK_200, res->status);
  11888. }
  11889. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  11890. std::string cert;
  11891. read_file(CA_CERT_FILE, cert);
  11892. SSLClient cli("google.com");
  11893. cli.load_ca_cert_store(cert.data(), cert.size());
  11894. const auto res = cli.Get("/");
  11895. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11896. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11897. }
  11898. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  11899. // clang-format off
  11900. static constexpr char cert[] =
  11901. "GlobalSign Root CA\n"
  11902. "==================\n"
  11903. "-----BEGIN CERTIFICATE-----\n"
  11904. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  11905. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  11906. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  11907. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  11908. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  11909. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  11910. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  11911. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  11912. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  11913. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  11914. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  11915. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  11916. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  11917. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  11918. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  11919. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  11920. "-----END CERTIFICATE-----\n";
  11921. // clang-format on
  11922. SSLClient cli("google.com");
  11923. cli.load_ca_cert_store(cert, sizeof(cert));
  11924. const auto res = cli.Get("/");
  11925. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11926. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11927. }
  11928. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  11929. SSLClient cli("www.youtube.com");
  11930. cli.set_ca_cert_path(CA_CERT_FILE);
  11931. cli.enable_server_certificate_verification(true);
  11932. cli.set_follow_location(true);
  11933. auto res = cli.Get("/");
  11934. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11935. ASSERT_EQ(StatusCode::OK_200, res->status);
  11936. }
  11937. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  11938. SSLClient cli("wWw.YouTube.Com");
  11939. cli.set_ca_cert_path(CA_CERT_FILE);
  11940. cli.enable_server_certificate_verification(true);
  11941. cli.enable_server_hostname_verification(true);
  11942. cli.set_follow_location(true);
  11943. auto res = cli.Get("/");
  11944. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11945. ASSERT_EQ(StatusCode::OK_200, res->status);
  11946. }
  11947. TEST(SSLClientTest, HostNameMatchCase_Online) {
  11948. SSLClient cli("gOoGlE.COm");
  11949. cli.enable_server_certificate_verification(true);
  11950. cli.enable_server_hostname_verification(true);
  11951. cli.set_follow_location(true);
  11952. auto res = cli.Get("/");
  11953. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11954. ASSERT_EQ(StatusCode::OK_200, res->status);
  11955. }
  11956. TEST(SSLClientTest, Issue2004_Online) {
  11957. Client client("https://google.com");
  11958. client.set_follow_location(true);
  11959. auto res = client.Get("/");
  11960. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11961. ASSERT_EQ(StatusCode::OK_200, res->status);
  11962. auto body = res->body;
  11963. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  11964. }
  11965. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  11966. // Create SSLClient with invalid cert/key to make is_valid() return false
  11967. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  11968. "nonexistent_key.pem");
  11969. // is_valid() should be false due to cert loading failure
  11970. ASSERT_FALSE(cli.is_valid());
  11971. auto res = cli.Get("/");
  11972. ASSERT_FALSE(res);
  11973. EXPECT_EQ(Error::SSLConnection, res.error());
  11974. }
  11975. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  11976. // Test for Issue #2251: SSL error not properly reported when client cert
  11977. // and key paths are swapped or mismatched
  11978. // This simulates the scenario where user accidentally swaps the cert and key
  11979. // files
  11980. // Using client cert file as private key and vice versa (completely wrong)
  11981. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  11982. // Should fail validation due to cert/key mismatch
  11983. ASSERT_FALSE(cli.is_valid());
  11984. // Attempt to make a request should fail with proper error
  11985. auto res = cli.Get("/");
  11986. ASSERT_FALSE(res);
  11987. EXPECT_EQ(Error::SSLConnection, res.error());
  11988. // SSL error should be recorded in the Result object (this is the key fix for
  11989. // Issue #2251)
  11990. auto backend_error = res.ssl_backend_error();
  11991. EXPECT_NE(0u, backend_error);
  11992. }
  11993. // Tests cert/key mismatch detection at the TLS context level
  11994. TEST(TlsApiTest, ClientCertKeyMismatch) {
  11995. // Test that using mismatched cert/key causes connection failure.
  11996. // We verify this at the SSLClient level rather than through internal
  11997. // TLS API functions.
  11998. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  11999. cli.enable_server_certificate_verification(false);
  12000. cli.set_connection_timeout(2);
  12001. // The mismatch should cause a connection or handshake error
  12002. auto res = cli.Get("/test");
  12003. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  12004. // Either way, the request should fail
  12005. EXPECT_FALSE(res);
  12006. }
  12007. #endif
  12008. #if 0
  12009. TEST(SSLClientTest, SetInterfaceWithINET6) {
  12010. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  12011. ASSERT_TRUE(cli != nullptr);
  12012. cli->set_address_family(AF_INET6);
  12013. cli->set_interface("en0");
  12014. auto res = cli->Get("/get");
  12015. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12016. ASSERT_EQ(StatusCode::OK_200, res->status);
  12017. }
  12018. #endif
  12019. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  12020. #ifdef CPPHTTPLIB_SSL_ENABLED
  12021. void ClientCertPresent(
  12022. const std::string &client_cert_file,
  12023. const std::string &client_private_key_file,
  12024. const std::string &client_encrypted_private_key_pass = std::string()) {
  12025. using namespace httplib::tls;
  12026. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12027. CLIENT_CA_CERT_DIR);
  12028. ASSERT_TRUE(svr.is_valid());
  12029. svr.Get("/test", [&](const Request &req, Response &res) {
  12030. res.set_content("test", "text/plain");
  12031. auto cert = req.peer_cert();
  12032. ASSERT_TRUE(static_cast<bool>(cert));
  12033. std::string common_name = cert.subject_cn();
  12034. EXPECT_EQ("Common Name", common_name);
  12035. });
  12036. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12037. auto se = detail::scope_exit([&] {
  12038. svr.stop();
  12039. t.join();
  12040. ASSERT_FALSE(svr.is_running());
  12041. });
  12042. svr.wait_until_ready();
  12043. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  12044. client_encrypted_private_key_pass);
  12045. cli.enable_server_certificate_verification(false);
  12046. cli.set_connection_timeout(30);
  12047. auto res = cli.Get("/test");
  12048. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12049. ASSERT_EQ(StatusCode::OK_200, res->status);
  12050. }
  12051. TEST(SSLClientServerTest, ClientCertPresent) {
  12052. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12053. }
  12054. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  12055. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  12056. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  12057. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  12058. }
  12059. // PEM memory-based constructor tests (works with all TLS backends)
  12060. void PemMemoryClientCertPresent(
  12061. const std::string &client_cert_file,
  12062. const std::string &client_private_key_file,
  12063. const std::string &client_encrypted_private_key_pass = std::string()) {
  12064. // Read PEM files into memory
  12065. std::string server_cert_pem, server_key_pem;
  12066. std::string client_ca_pem;
  12067. std::string client_cert_pem, client_key_pem;
  12068. read_file(SERVER_CERT_FILE, server_cert_pem);
  12069. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  12070. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  12071. read_file(client_cert_file, client_cert_pem);
  12072. read_file(client_private_key_file, client_key_pem);
  12073. // Create server with PEM memory
  12074. SSLServer::PemMemory server_pem = {
  12075. server_cert_pem.c_str(),
  12076. server_cert_pem.size(),
  12077. server_key_pem.c_str(),
  12078. server_key_pem.size(),
  12079. client_ca_pem.c_str(),
  12080. client_ca_pem.size(),
  12081. nullptr // no password for server key
  12082. };
  12083. SSLServer svr(server_pem);
  12084. ASSERT_TRUE(svr.is_valid());
  12085. svr.Get("/test", [&](const Request &, Response &res) {
  12086. res.set_content("test", "text/plain");
  12087. });
  12088. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12089. auto se = detail::scope_exit([&] {
  12090. svr.stop();
  12091. t.join();
  12092. ASSERT_FALSE(svr.is_running());
  12093. });
  12094. svr.wait_until_ready();
  12095. // Create client with PEM memory
  12096. const char *password = client_encrypted_private_key_pass.empty()
  12097. ? nullptr
  12098. : client_encrypted_private_key_pass.c_str();
  12099. SSLClient::PemMemory client_pem = {
  12100. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  12101. client_key_pem.size(), password};
  12102. SSLClient cli(HOST, PORT, client_pem);
  12103. cli.enable_server_certificate_verification(false);
  12104. cli.set_connection_timeout(30);
  12105. auto res = cli.Get("/test");
  12106. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12107. ASSERT_EQ(StatusCode::OK_200, res->status);
  12108. }
  12109. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  12110. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12111. }
  12112. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  12113. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  12114. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  12115. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  12116. }
  12117. TEST(SSLClientServerTest, ClientCertMissing) {
  12118. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12119. CLIENT_CA_CERT_DIR);
  12120. ASSERT_TRUE(svr.is_valid());
  12121. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  12122. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12123. auto se = detail::scope_exit([&] {
  12124. svr.stop();
  12125. t.join();
  12126. ASSERT_FALSE(svr.is_running());
  12127. });
  12128. svr.wait_until_ready();
  12129. SSLClient cli(HOST, PORT);
  12130. cli.set_connection_timeout(30);
  12131. // cert.pem does not match HOST. Skip the hostname check, which runs before
  12132. // the chain check on Windows, so the result does not depend on the order.
  12133. cli.enable_server_hostname_verification(false);
  12134. auto res = cli.Get("/test");
  12135. ASSERT_TRUE(!res);
  12136. // When client cert is missing and server requires it, connection fails
  12137. // Error type depends on backend implementation
  12138. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  12139. res.error() == Error::SSLConnection);
  12140. // Verify backend error is captured
  12141. // Note: This test may have different error codes depending on the exact
  12142. // verification failure
  12143. EXPECT_NE(0UL, res.ssl_backend_error());
  12144. }
  12145. TEST(SSLClientServerTest, TrustDirOptional) {
  12146. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12147. ASSERT_TRUE(svr.is_valid());
  12148. svr.Get("/test", [&](const Request &, Response &res) {
  12149. res.set_content("test", "text/plain");
  12150. });
  12151. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12152. auto se = detail::scope_exit([&] {
  12153. svr.stop();
  12154. t.join();
  12155. ASSERT_FALSE(svr.is_running());
  12156. });
  12157. svr.wait_until_ready();
  12158. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12159. cli.enable_server_certificate_verification(false);
  12160. cli.set_connection_timeout(30);
  12161. auto res = cli.Get("/test");
  12162. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12163. ASSERT_EQ(StatusCode::OK_200, res->status);
  12164. }
  12165. TEST(SSLClientServerTest, SSLConnectTimeout) {
  12166. class NoListenSSLServer : public SSLServer {
  12167. public:
  12168. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  12169. const char *client_ca_cert_file_path,
  12170. const char *client_ca_cert_dir_path = nullptr)
  12171. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  12172. client_ca_cert_dir_path),
  12173. stop_(false) {}
  12174. std::atomic_bool stop_;
  12175. private:
  12176. bool process_and_close_socket(socket_t /*sock*/) override {
  12177. // Don't create SSL context
  12178. while (!stop_.load()) {
  12179. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  12180. }
  12181. return true;
  12182. }
  12183. };
  12184. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  12185. CLIENT_CA_CERT_FILE);
  12186. ASSERT_TRUE(svr.is_valid());
  12187. svr.Get("/test", [&](const Request &, Response &res) {
  12188. res.set_content("test", "text/plain");
  12189. });
  12190. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12191. auto se = detail::scope_exit([&] {
  12192. svr.stop_ = true;
  12193. svr.stop();
  12194. t.join();
  12195. ASSERT_FALSE(svr.is_running());
  12196. });
  12197. svr.wait_until_ready();
  12198. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12199. cli.enable_server_certificate_verification(false);
  12200. cli.set_connection_timeout(1);
  12201. auto res = cli.Get("/test");
  12202. ASSERT_TRUE(!res);
  12203. EXPECT_EQ(Error::SSLConnection, res.error());
  12204. // Timeout results in WantRead error code (maps to backend-specific value)
  12205. EXPECT_NE(0, res.ssl_error());
  12206. }
  12207. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  12208. // Test SSLServer with client certificate verification using the standard
  12209. // constructor (ContextSetupCallback is tested by backend-specific tests)
  12210. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12211. CLIENT_CA_CERT_DIR);
  12212. ASSERT_TRUE(svr.is_valid());
  12213. svr.Get("/test", [&](const Request &req, Response &res) {
  12214. res.set_content("test", "text/plain");
  12215. auto cert = req.peer_cert();
  12216. ASSERT_TRUE(static_cast<bool>(cert));
  12217. auto common_name = cert.subject_cn();
  12218. EXPECT_EQ("Common Name", common_name);
  12219. });
  12220. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12221. auto se = detail::scope_exit([&] {
  12222. svr.stop();
  12223. t.join();
  12224. ASSERT_FALSE(svr.is_running());
  12225. });
  12226. svr.wait_until_ready();
  12227. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12228. cli.enable_server_certificate_verification(false);
  12229. cli.set_connection_timeout(30);
  12230. auto res = cli.Get("/test");
  12231. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12232. ASSERT_EQ(StatusCode::OK_200, res->status);
  12233. }
  12234. // Test verify_hostname for both OpenSSL and MbedTLS backends
  12235. // Verifies that wildcard matching and exact matching work consistently
  12236. TEST(SSLClientServerTest, TlsVerifyHostname) {
  12237. using namespace httplib::tls;
  12238. // We need a running server to test against
  12239. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12240. ASSERT_TRUE(svr.is_valid());
  12241. svr.Get("/test", [](const Request &, Response &res) {
  12242. res.set_content("ok", "text/plain");
  12243. });
  12244. thread t([&]() { svr.listen(HOST, PORT); });
  12245. auto se = detail::scope_exit([&] {
  12246. svr.stop();
  12247. t.join();
  12248. });
  12249. svr.wait_until_ready();
  12250. bool verify_callback_called = false;
  12251. bool verify_result_wrong = false;
  12252. SSLClient cli(HOST, PORT);
  12253. cli.enable_server_certificate_verification(true);
  12254. cli.set_ca_cert_path(CA_CERT_FILE);
  12255. cli.set_connection_timeout(5);
  12256. // Note: Test certificate has CN="Common Name", not "localhost"
  12257. bool verify_result_cn = false;
  12258. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12259. verify_callback_called = true;
  12260. if (!ctx.cert) return false;
  12261. // Test 1: "Common Name" should match (our test server cert CN)
  12262. verify_result_cn = ctx.check_hostname("Common Name");
  12263. // Test 2: wrong hostname should not match
  12264. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  12265. return true; // Accept for the purpose of this test
  12266. });
  12267. auto res = cli.Get("/test");
  12268. // The request may succeed or fail depending on cert configuration
  12269. // but the callback should have been called
  12270. ASSERT_TRUE(verify_callback_called)
  12271. << "Verify callback should have been called";
  12272. // CN="Common Name" should match our test certificate
  12273. //
  12274. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  12275. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  12276. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  12277. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  12278. // <openssl/base.h>, which is included transitively when
  12279. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  12280. #if defined(OPENSSL_IS_BORINGSSL)
  12281. EXPECT_FALSE(verify_result_cn)
  12282. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  12283. #else
  12284. EXPECT_TRUE(verify_result_cn)
  12285. << "verify_hostname should match 'Common Name' (certificate CN)";
  12286. #endif
  12287. // Wrong hostname should not match
  12288. EXPECT_FALSE(verify_result_wrong)
  12289. << "verify_hostname should not match 'wronghost.example.com'";
  12290. }
  12291. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  12292. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  12293. // X509_check_ip behavior and must hold for every backend.
  12294. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  12295. using namespace httplib::tls;
  12296. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  12297. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  12298. ASSERT_TRUE(svr.is_valid());
  12299. svr.Get("/test", [](const Request &, Response &res) {
  12300. res.set_content("ok", "text/plain");
  12301. });
  12302. thread t([&]() { svr.listen(HOST, PORT); });
  12303. auto se = detail::scope_exit([&] {
  12304. svr.stop();
  12305. t.join();
  12306. });
  12307. svr.wait_until_ready();
  12308. bool verify_callback_called = false;
  12309. bool ip_matched_via_cn = true;
  12310. SSLClient cli(HOST, PORT);
  12311. cli.enable_server_certificate_verification(true);
  12312. cli.set_ca_cert_path(CA_CERT_FILE);
  12313. cli.set_connection_timeout(5);
  12314. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12315. verify_callback_called = true;
  12316. if (!ctx.cert) return false;
  12317. // The IP appears only in the CN, so it must NOT be accepted.
  12318. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  12319. return true; // Accept for the purpose of this test
  12320. });
  12321. cli.Get("/test");
  12322. ASSERT_TRUE(verify_callback_called)
  12323. << "Verify callback should have been called";
  12324. EXPECT_FALSE(ip_matched_via_cn)
  12325. << "An IP host must not be authenticated via the certificate CN";
  12326. }
  12327. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  12328. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  12329. using namespace httplib::tls;
  12330. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  12331. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  12332. ASSERT_TRUE(svr.is_valid());
  12333. svr.Get("/test", [](const Request &, Response &res) {
  12334. res.set_content("ok", "text/plain");
  12335. });
  12336. thread t([&]() { svr.listen(HOST, PORT); });
  12337. auto se = detail::scope_exit([&] {
  12338. svr.stop();
  12339. t.join();
  12340. });
  12341. svr.wait_until_ready();
  12342. bool verify_callback_called = false;
  12343. bool san_matched = false;
  12344. bool wrong_ipv6_matched = true;
  12345. bool cn_ipv6_matched = true;
  12346. SSLClient cli(HOST, PORT);
  12347. cli.enable_server_certificate_verification(true);
  12348. cli.set_ca_cert_path(CA_CERT_FILE);
  12349. cli.set_connection_timeout(5);
  12350. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12351. verify_callback_called = true;
  12352. if (!ctx.cert) return false;
  12353. // Matches the IPv6 iPAddress SAN.
  12354. san_matched = ctx.check_hostname("2001:db8::1");
  12355. // A different IPv6 address must not match.
  12356. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  12357. // "::1" lives only in the CN, so it must not be accepted.
  12358. cn_ipv6_matched = ctx.check_hostname("::1");
  12359. return true; // Accept for the purpose of this test
  12360. });
  12361. cli.Get("/test");
  12362. ASSERT_TRUE(verify_callback_called)
  12363. << "Verify callback should have been called";
  12364. EXPECT_TRUE(san_matched)
  12365. << "verify_hostname should match an IPv6 iPAddress SAN";
  12366. EXPECT_FALSE(wrong_ipv6_matched)
  12367. << "verify_hostname should not match a non-matching IPv6 address";
  12368. EXPECT_FALSE(cn_ipv6_matched)
  12369. << "An IPv6 host must not be authenticated via the certificate CN";
  12370. }
  12371. #endif
  12372. // mbedTLS-specific callback constructor test
  12373. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  12374. #ifdef CPPHTTPLIB_SSL_ENABLED
  12375. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  12376. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12377. ASSERT_TRUE(svr.is_valid());
  12378. // Set up a handler to verify client certificate is present
  12379. bool client_cert_verified = false;
  12380. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  12381. // Verify that client certificate was provided
  12382. client_cert_verified = true;
  12383. res.set_content("success", "text/plain");
  12384. });
  12385. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12386. auto se = detail::scope_exit([&] {
  12387. svr.stop();
  12388. t.join();
  12389. ASSERT_FALSE(svr.is_running());
  12390. });
  12391. svr.wait_until_ready();
  12392. // Client with certificate
  12393. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12394. cli.enable_server_certificate_verification(false);
  12395. cli.set_connection_timeout(30);
  12396. auto res = cli.Get("/test");
  12397. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12398. ASSERT_EQ(StatusCode::OK_200, res->status);
  12399. ASSERT_TRUE(client_cert_verified);
  12400. EXPECT_EQ("success", res->body);
  12401. }
  12402. #endif
  12403. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  12404. // backends
  12405. #ifdef CPPHTTPLIB_SSL_ENABLED
  12406. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  12407. using namespace httplib::tls;
  12408. // Test that when client CA cert file is provided,
  12409. // the server properly requests and validates client certificates
  12410. // Create a server with client authentication
  12411. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12412. ASSERT_TRUE(svr.is_valid());
  12413. bool handler_called = false;
  12414. svr.Get("/test", [&](const Request &req, Response &res) {
  12415. handler_called = true;
  12416. // Verify that a client certificate was provided
  12417. auto cert = req.peer_cert();
  12418. ASSERT_TRUE(static_cast<bool>(cert));
  12419. // Get the issuer name
  12420. std::string issuer_str = cert.issuer_name();
  12421. ASSERT_FALSE(issuer_str.empty());
  12422. // The client certificate should be issued by our test CA
  12423. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  12424. res.set_content("authenticated", "text/plain");
  12425. });
  12426. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12427. auto se = detail::scope_exit([&] {
  12428. svr.stop();
  12429. t.join();
  12430. ASSERT_FALSE(svr.is_running());
  12431. });
  12432. svr.wait_until_ready();
  12433. // Connect with a client certificate issued by the CA
  12434. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12435. cli.enable_server_certificate_verification(false);
  12436. cli.set_connection_timeout(30);
  12437. auto res = cli.Get("/test");
  12438. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12439. ASSERT_EQ(StatusCode::OK_200, res->status);
  12440. ASSERT_TRUE(handler_called);
  12441. EXPECT_EQ("authenticated", res->body);
  12442. }
  12443. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  12444. using namespace httplib::tls;
  12445. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12446. ASSERT_TRUE(svr.is_valid());
  12447. svr.Get("/test", [](const Request &, Response &res) {
  12448. res.set_content("ok", "text/plain");
  12449. });
  12450. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12451. auto se = detail::scope_exit([&] {
  12452. svr.stop();
  12453. t.join();
  12454. });
  12455. svr.wait_until_ready();
  12456. SSLClient cli(HOST, PORT);
  12457. cli.enable_server_certificate_verification(false);
  12458. cli.set_connection_timeout(30);
  12459. bool cert_checked = false;
  12460. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12461. if (ctx.cert) {
  12462. auto sans = ctx.sans();
  12463. // Test certificate may or may not have SANs - just verify the API
  12464. // works If SANs exist, verify the types are valid
  12465. for (const auto &san : sans) {
  12466. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  12467. san.type == SanType::EMAIL || san.type == SanType::URI ||
  12468. san.type == SanType::OTHER);
  12469. EXPECT_FALSE(san.value.empty());
  12470. }
  12471. cert_checked = true;
  12472. }
  12473. return true;
  12474. });
  12475. auto res = cli.Get("/test");
  12476. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12477. EXPECT_TRUE(cert_checked);
  12478. }
  12479. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  12480. using namespace httplib::tls;
  12481. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12482. ASSERT_TRUE(svr.is_valid());
  12483. svr.Get("/test", [](const Request &, Response &res) {
  12484. res.set_content("ok", "text/plain");
  12485. });
  12486. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12487. auto se = detail::scope_exit([&] {
  12488. svr.stop();
  12489. t.join();
  12490. });
  12491. svr.wait_until_ready();
  12492. SSLClient cli(HOST, PORT);
  12493. cli.enable_server_certificate_verification(false);
  12494. cli.set_connection_timeout(30);
  12495. bool validity_checked = false;
  12496. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12497. if (ctx.cert) {
  12498. time_t not_before = 0, not_after = 0;
  12499. bool result = ctx.validity(not_before, not_after);
  12500. EXPECT_TRUE(result);
  12501. // Verify that not_before < now < not_after for a valid cert
  12502. time_t now = time(nullptr);
  12503. EXPECT_LT(not_before, now);
  12504. EXPECT_GT(not_after, now);
  12505. validity_checked = true;
  12506. }
  12507. return true;
  12508. });
  12509. auto res = cli.Get("/test");
  12510. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12511. EXPECT_TRUE(validity_checked);
  12512. }
  12513. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  12514. using namespace httplib::tls;
  12515. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12516. ASSERT_TRUE(svr.is_valid());
  12517. svr.Get("/test", [](const Request &, Response &res) {
  12518. res.set_content("ok", "text/plain");
  12519. });
  12520. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12521. auto se = detail::scope_exit([&] {
  12522. svr.stop();
  12523. t.join();
  12524. });
  12525. svr.wait_until_ready();
  12526. SSLClient cli(HOST, PORT);
  12527. cli.enable_server_certificate_verification(false);
  12528. cli.set_connection_timeout(30);
  12529. bool serial_checked = false;
  12530. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12531. if (ctx.cert) {
  12532. std::string serial = ctx.serial();
  12533. EXPECT_FALSE(serial.empty());
  12534. // Serial should be a hex string
  12535. for (char c : serial) {
  12536. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  12537. (c >= 'a' && c <= 'f'));
  12538. }
  12539. serial_checked = true;
  12540. }
  12541. return true;
  12542. });
  12543. auto res = cli.Get("/test");
  12544. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12545. EXPECT_TRUE(serial_checked);
  12546. }
  12547. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  12548. // Test 1: Valid CA file - no error should be recorded
  12549. {
  12550. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  12551. CLIENT_CA_CERT_FILE);
  12552. ASSERT_TRUE(svr.is_valid());
  12553. // With valid setup, last_ssl_error should be 0
  12554. EXPECT_EQ(0, svr.ssl_last_error());
  12555. }
  12556. // Test 2: Invalid CA file content
  12557. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  12558. {
  12559. // Create a temporary file with completely invalid content
  12560. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  12561. {
  12562. std::ofstream ofs(temp_invalid_ca);
  12563. ofs << "This is not a certificate file at all\n";
  12564. ofs << "Just plain text content\n";
  12565. }
  12566. // Create server with invalid CA file
  12567. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  12568. // Clean up temporary file
  12569. std::remove(temp_invalid_ca);
  12570. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  12571. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  12572. // Note: SSL_CTX_load_verify_locations typically fails first,
  12573. // but our error handling code path is still exercised
  12574. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  12575. }
  12576. }
  12577. TEST(VerifyCallbackTest, VerifyContextFields) {
  12578. using namespace httplib::tls;
  12579. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12580. ASSERT_TRUE(svr.is_valid());
  12581. svr.Get("/test", [](const Request &, Response &res) {
  12582. res.set_content("ok", "text/plain");
  12583. });
  12584. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12585. auto se = detail::scope_exit([&] {
  12586. svr.stop();
  12587. t.join();
  12588. });
  12589. svr.wait_until_ready();
  12590. SSLClient cli(HOST, PORT);
  12591. cli.enable_server_certificate_verification(false);
  12592. cli.set_connection_timeout(30);
  12593. int callback_count = 0;
  12594. bool saw_leaf_cert = false;
  12595. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12596. if (ctx.cert) {
  12597. callback_count++;
  12598. // We should see at least one certificate (the leaf)
  12599. std::string cn = ctx.subject_cn();
  12600. if (!cn.empty()) { saw_leaf_cert = true; }
  12601. // Verify context fields are populated
  12602. EXPECT_NE(ctx.session, nullptr);
  12603. EXPECT_GE(ctx.depth, 0);
  12604. }
  12605. return true;
  12606. });
  12607. auto res = cli.Get("/test");
  12608. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12609. EXPECT_GT(callback_count, 0);
  12610. EXPECT_TRUE(saw_leaf_cert);
  12611. }
  12612. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  12613. using httplib::tls::TlsError;
  12614. // Test that verify_error_to_string returns empty for success
  12615. std::string success_str = TlsError::verify_error_to_string(0);
  12616. EXPECT_TRUE(success_str.empty());
  12617. // Test that verify_error_to_string returns non-empty for error codes
  12618. // Using a common error code (certificate expired)
  12619. std::string error_str =
  12620. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  12621. EXPECT_FALSE(error_str.empty());
  12622. }
  12623. TEST(SessionVerifierTest, CertificateAccepted) {
  12624. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12625. ASSERT_TRUE(svr.is_valid());
  12626. svr.Get("/test", [](const Request &, Response &res) {
  12627. res.set_content("ok", "text/plain");
  12628. });
  12629. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12630. auto se = detail::scope_exit([&] {
  12631. svr.stop();
  12632. t.join();
  12633. });
  12634. svr.wait_until_ready();
  12635. SSLClient cli(HOST, PORT);
  12636. cli.enable_server_certificate_verification(false);
  12637. cli.set_connection_timeout(30);
  12638. bool callback_called = false;
  12639. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12640. EXPECT_NE(session, nullptr);
  12641. callback_called = true;
  12642. return SSLVerifierResponse::CertificateAccepted;
  12643. });
  12644. auto res = cli.Get("/test");
  12645. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12646. EXPECT_EQ(200, res->status);
  12647. EXPECT_TRUE(callback_called);
  12648. }
  12649. TEST(SessionVerifierTest, CertificateRejected) {
  12650. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12651. ASSERT_TRUE(svr.is_valid());
  12652. svr.Get("/test", [](const Request &, Response &res) {
  12653. res.set_content("ok", "text/plain");
  12654. });
  12655. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12656. auto se = detail::scope_exit([&] {
  12657. svr.stop();
  12658. t.join();
  12659. });
  12660. svr.wait_until_ready();
  12661. SSLClient cli(HOST, PORT);
  12662. cli.enable_server_certificate_verification(false);
  12663. cli.set_connection_timeout(30);
  12664. bool callback_called = false;
  12665. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12666. EXPECT_NE(session, nullptr);
  12667. callback_called = true;
  12668. return SSLVerifierResponse::CertificateRejected;
  12669. });
  12670. auto res = cli.Get("/test");
  12671. EXPECT_FALSE(res);
  12672. EXPECT_TRUE(callback_called);
  12673. }
  12674. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  12675. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12676. ASSERT_TRUE(svr.is_valid());
  12677. svr.Get("/test", [](const Request &, Response &res) {
  12678. res.set_content("ok", "text/plain");
  12679. });
  12680. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12681. auto se = detail::scope_exit([&] {
  12682. svr.stop();
  12683. t.join();
  12684. });
  12685. svr.wait_until_ready();
  12686. // NoDecisionMade with verification disabled should succeed (no default check)
  12687. SSLClient cli(HOST, PORT);
  12688. cli.enable_server_certificate_verification(false);
  12689. cli.set_connection_timeout(30);
  12690. bool callback_called = false;
  12691. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12692. EXPECT_NE(session, nullptr);
  12693. callback_called = true;
  12694. return SSLVerifierResponse::NoDecisionMade;
  12695. });
  12696. auto res = cli.Get("/test");
  12697. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12698. EXPECT_EQ(200, res->status);
  12699. EXPECT_TRUE(callback_called);
  12700. }
  12701. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  12702. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12703. ASSERT_TRUE(svr.is_valid());
  12704. svr.Get("/test", [](const Request &, Response &res) {
  12705. res.set_content("ok", "text/plain");
  12706. });
  12707. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12708. auto se = detail::scope_exit([&] {
  12709. svr.stop();
  12710. t.join();
  12711. });
  12712. svr.wait_until_ready();
  12713. // NoDecisionMade with verification enabled should fail (self-signed cert).
  12714. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  12715. // so we only check that the request fails, not whether the callback was
  12716. // called.
  12717. SSLClient cli(HOST, PORT);
  12718. cli.enable_server_certificate_verification(true);
  12719. cli.set_connection_timeout(30);
  12720. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12721. EXPECT_NE(session, nullptr);
  12722. return SSLVerifierResponse::NoDecisionMade;
  12723. });
  12724. auto res = cli.Get("/test");
  12725. EXPECT_FALSE(res);
  12726. }
  12727. TEST(SSLClientServerTest, ClientCAListFromPem) {
  12728. // Test SSL server using PemMemory constructor with client CA certificates
  12729. // Read PEM files
  12730. std::string server_cert_pem, server_key_pem, client_ca_pem;
  12731. read_file(SERVER_CERT_FILE, server_cert_pem);
  12732. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  12733. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  12734. // Create SSLServer with PemMemory constructor including client CA
  12735. SSLServer::PemMemory server_pem = {
  12736. server_cert_pem.c_str(),
  12737. server_cert_pem.size(),
  12738. server_key_pem.c_str(),
  12739. server_key_pem.size(),
  12740. client_ca_pem.c_str(),
  12741. client_ca_pem.size(),
  12742. nullptr // no password for server key
  12743. };
  12744. SSLServer svr(server_pem);
  12745. ASSERT_TRUE(svr.is_valid());
  12746. // No SSL error should be recorded for valid setup
  12747. EXPECT_EQ(0, svr.ssl_last_error());
  12748. // Set up server endpoints
  12749. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  12750. res.set_content("ok", "text/plain");
  12751. });
  12752. // Start server in a thread
  12753. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  12754. svr.wait_until_ready();
  12755. // Connect with client certificate (using constructor with paths)
  12756. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12757. cli.enable_server_certificate_verification(false);
  12758. auto res = cli.Get("/test-pem-ca");
  12759. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12760. EXPECT_EQ(200, res->status);
  12761. EXPECT_EQ("ok", res->body);
  12762. svr.stop();
  12763. server_thread.join();
  12764. }
  12765. #endif
  12766. #ifdef _WIN32
  12767. TEST(CleanupTest, WSACleanup) {
  12768. int ret = WSACleanup();
  12769. ASSERT_EQ(0, ret);
  12770. }
  12771. #endif
  12772. #ifndef CPPHTTPLIB_SSL_ENABLED
  12773. TEST(NoSSLSupport, SimpleInterface) {
  12774. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  12775. }
  12776. #endif
  12777. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  12778. TEST(InvalidScheme, SimpleInterface) {
  12779. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  12780. }
  12781. #endif
  12782. TEST(NoScheme, SimpleInterface) {
  12783. Client cli("yahoo.com:80");
  12784. ASSERT_TRUE(cli.is_valid());
  12785. }
  12786. TEST(SendAPI, SimpleInterface_Online) {
  12787. Client cli("http://yahoo.com");
  12788. Request req;
  12789. req.method = "GET";
  12790. req.path = "/";
  12791. auto res = cli.send(req);
  12792. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12793. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  12794. }
  12795. TEST(SendAPI, WithParamsInRequest) {
  12796. Server svr;
  12797. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  12798. EXPECT_TRUE(req.has_param("test"));
  12799. EXPECT_EQ("test_value", req.get_param_value("test"));
  12800. });
  12801. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12802. auto se = detail::scope_exit([&] {
  12803. svr.stop();
  12804. t.join();
  12805. ASSERT_FALSE(svr.is_running());
  12806. });
  12807. svr.wait_until_ready();
  12808. Client cli(HOST, PORT);
  12809. {
  12810. Request req;
  12811. req.method = "GET";
  12812. req.path = "/";
  12813. req.params.emplace("test", "test_value");
  12814. auto res = cli.send(req);
  12815. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12816. }
  12817. {
  12818. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  12819. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12820. }
  12821. }
  12822. TEST(ClientImplMethods, GetSocketTest) {
  12823. httplib::Server svr;
  12824. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  12825. res.status = StatusCode::OK_200;
  12826. });
  12827. auto port = svr.bind_to_any_port("127.0.0.1");
  12828. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  12829. auto se = detail::scope_exit([&] {
  12830. svr.stop();
  12831. thread.join();
  12832. ASSERT_FALSE(svr.is_running());
  12833. });
  12834. svr.wait_until_ready();
  12835. {
  12836. httplib::Client cli("127.0.0.1", port);
  12837. cli.set_keep_alive(true);
  12838. // Use the behavior of cpp-httplib of opening the connection
  12839. // only when the first request happens. If that changes,
  12840. // this test would be obsolete.
  12841. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  12842. // This also implicitly tests the server. But other tests would fail much
  12843. // earlier than this one to be considered.
  12844. auto res = cli.Get("/");
  12845. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12846. EXPECT_EQ(StatusCode::OK_200, res->status);
  12847. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  12848. }
  12849. }
  12850. #ifdef CPPHTTPLIB_SSL_ENABLED
  12851. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  12852. Client cli("http://yahoo.com");
  12853. auto res = cli.Get("/");
  12854. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12855. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  12856. cli.set_follow_location(true);
  12857. res = cli.Get("/");
  12858. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12859. EXPECT_EQ(StatusCode::OK_200, res->status);
  12860. EXPECT_EQ("https://www.yahoo.com/", res->location);
  12861. }
  12862. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  12863. Client cli("https://yahoo.com");
  12864. auto res = cli.Get("/");
  12865. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12866. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  12867. cli.set_follow_location(true);
  12868. res = cli.Get("/");
  12869. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12870. EXPECT_EQ(StatusCode::OK_200, res->status);
  12871. EXPECT_EQ("https://www.yahoo.com/", res->location);
  12872. }
  12873. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  12874. Client cli("https://yahoo.com");
  12875. auto res = cli.Get("/");
  12876. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12877. ASSERT_FALSE(!res);
  12878. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12879. ASSERT_FALSE(res == nullptr);
  12880. ASSERT_TRUE(res != nullptr);
  12881. EXPECT_EQ(Error::Success, res.error());
  12882. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  12883. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  12884. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  12885. cli.set_follow_location(true);
  12886. res = cli.Get("/");
  12887. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12888. EXPECT_EQ(Error::Success, res.error());
  12889. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  12890. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  12891. EXPECT_EQ(StatusCode::OK_200, res->status);
  12892. EXPECT_EQ("https://www.yahoo.com/", res->location);
  12893. }
  12894. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  12895. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  12896. Client cli("https://cdnjs.cloudflare.com");
  12897. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  12898. Headers{{"Accept-Encoding", "br"}});
  12899. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12900. EXPECT_EQ(StatusCode::OK_200, res->status);
  12901. EXPECT_EQ(287630U, res->body.size());
  12902. EXPECT_EQ("application/javascript; charset=utf-8",
  12903. res->get_header_value("Content-Type"));
  12904. }
  12905. #endif
  12906. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  12907. #undef REDIR_HOST // Silence compiler warning
  12908. #define REDIR_HOST "https://httpbingo.org"
  12909. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  12910. Client cli(REDIR_HOST);
  12911. cli.set_follow_location(true);
  12912. auto res =
  12913. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  12914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12915. EXPECT_EQ(StatusCode::OK_200, res->status);
  12916. }
  12917. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  12918. Client cli(REDIR_HOST);
  12919. cli.set_follow_location(true);
  12920. Params params;
  12921. params.emplace("url", "http://example.com");
  12922. params.emplace("status_code", "302");
  12923. auto res = cli.Get(REDIR_PATH, params, Headers{});
  12924. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12925. EXPECT_EQ(StatusCode::OK_200, res->status);
  12926. }
  12927. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  12928. Client cli(REDIR_HOST);
  12929. cli.set_follow_location(true);
  12930. Params params;
  12931. params.emplace("url", "http://example.com");
  12932. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  12933. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12934. EXPECT_EQ(StatusCode::OK_200, res->status);
  12935. }
  12936. TEST(HttpToHttpsRedirectTest, CertFile) {
  12937. auto ssl_port = PORT + 1;
  12938. Server svr;
  12939. ASSERT_TRUE(svr.is_valid());
  12940. svr.Get("/index", [&](const Request &, Response &res) {
  12941. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  12942. "/index");
  12943. svr.stop();
  12944. });
  12945. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12946. ASSERT_TRUE(ssl_svr.is_valid());
  12947. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  12948. res.set_content("test", "text/plain");
  12949. ssl_svr.stop();
  12950. });
  12951. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12952. thread t2 =
  12953. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  12954. auto se = detail::scope_exit([&] {
  12955. t2.join();
  12956. t.join();
  12957. ASSERT_FALSE(svr.is_running());
  12958. });
  12959. svr.wait_until_ready();
  12960. ssl_svr.wait_until_ready();
  12961. Client cli("127.0.0.1", PORT);
  12962. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  12963. cli.enable_server_certificate_verification(true);
  12964. cli.set_follow_location(true);
  12965. cli.set_connection_timeout(30);
  12966. auto res = cli.Get("/index");
  12967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12968. ASSERT_EQ(StatusCode::OK_200, res->status);
  12969. }
  12970. TEST(SSLClientRedirectTest, CertFile) {
  12971. auto ssl_port = PORT + 1;
  12972. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12973. ASSERT_TRUE(ssl_svr1.is_valid());
  12974. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  12975. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  12976. "/index");
  12977. ssl_svr1.stop();
  12978. });
  12979. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12980. ASSERT_TRUE(ssl_svr2.is_valid());
  12981. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  12982. res.set_content("test", "text/plain");
  12983. ssl_svr2.stop();
  12984. });
  12985. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  12986. thread t2 =
  12987. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  12988. auto se = detail::scope_exit([&] {
  12989. t2.join();
  12990. t.join();
  12991. ASSERT_FALSE(ssl_svr1.is_running());
  12992. });
  12993. ssl_svr1.wait_until_ready();
  12994. ssl_svr2.wait_until_ready();
  12995. SSLClient cli("127.0.0.1", PORT);
  12996. std::string cert;
  12997. read_file(SERVER_CERT2_FILE, cert);
  12998. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12999. cli.enable_server_certificate_verification(true);
  13000. cli.set_follow_location(true);
  13001. cli.set_connection_timeout(30);
  13002. auto res = cli.Get("/index");
  13003. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13004. ASSERT_EQ(StatusCode::OK_200, res->status);
  13005. }
  13006. #endif
  13007. #ifdef CPPHTTPLIB_SSL_ENABLED
  13008. // Test that set_ca_cert_store() skips system certs (consistent with
  13009. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  13010. // should be trusted - system certs should NOT be loaded.
  13011. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  13012. // Load a specific cert that is NOT a system CA cert
  13013. std::string cert;
  13014. read_file(SERVER_CERT2_FILE, cert);
  13015. SSLClient cli("google.com");
  13016. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13017. cli.enable_server_certificate_verification(true);
  13018. // This should FAIL because:
  13019. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  13020. // 2. System certs should NOT be loaded when custom store is set
  13021. // If system certs WERE loaded, this would succeed
  13022. auto res = cli.Get("/");
  13023. ASSERT_FALSE(res);
  13024. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13025. }
  13026. // Same as above, but through the native store handle path. Regression test:
  13027. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  13028. // merged system certs into the user-provided store.
  13029. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  13030. std::string cert;
  13031. read_file(SERVER_CERT2_FILE, cert);
  13032. SSLClient cli("google.com");
  13033. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  13034. cli.enable_server_certificate_verification(true);
  13035. auto res = cli.Get("/");
  13036. ASSERT_FALSE(res);
  13037. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13038. }
  13039. // A custom store set via the native handle must still verify a server whose
  13040. // cert it does contain.
  13041. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  13042. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13043. ASSERT_TRUE(svr.is_valid());
  13044. svr.Get("/test", [&](const Request &, Response &res) {
  13045. res.set_content("test", "text/plain");
  13046. });
  13047. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13048. auto se = detail::scope_exit([&] {
  13049. svr.stop();
  13050. t.join();
  13051. ASSERT_FALSE(svr.is_running());
  13052. });
  13053. svr.wait_until_ready();
  13054. SSLClient cli("127.0.0.1", PORT);
  13055. std::string cert;
  13056. read_file(SERVER_CERT2_FILE, cert);
  13057. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  13058. cli.enable_server_certificate_verification(true);
  13059. cli.set_connection_timeout(30);
  13060. auto res = cli.Get("/test");
  13061. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13062. ASSERT_EQ(StatusCode::OK_200, res->status);
  13063. }
  13064. // CA certs loaded through the universal Client must be transferred to the
  13065. // client created internally for following an HTTPS redirect. Regression test:
  13066. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  13067. // the CA data for redirect transfer.
  13068. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  13069. auto ssl_port = PORT + 1;
  13070. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13071. ASSERT_TRUE(ssl_svr1.is_valid());
  13072. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  13073. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13074. "/index");
  13075. });
  13076. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13077. ASSERT_TRUE(ssl_svr2.is_valid());
  13078. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  13079. res.set_content("test", "text/plain");
  13080. });
  13081. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  13082. thread t2 =
  13083. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  13084. auto se = detail::scope_exit([&] {
  13085. ssl_svr2.stop();
  13086. ssl_svr1.stop();
  13087. t2.join();
  13088. t.join();
  13089. ASSERT_FALSE(ssl_svr1.is_running());
  13090. });
  13091. ssl_svr1.wait_until_ready();
  13092. ssl_svr2.wait_until_ready();
  13093. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  13094. std::string cert;
  13095. read_file(SERVER_CERT2_FILE, cert);
  13096. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13097. cli.enable_server_certificate_verification(true);
  13098. cli.set_follow_location(true);
  13099. cli.set_connection_timeout(30);
  13100. auto res = cli.Get("/index");
  13101. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13102. ASSERT_EQ(StatusCode::OK_200, res->status);
  13103. }
  13104. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  13105. // so a host signed by a system CA verifies even though a custom CA is set
  13106. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  13107. std::string cert;
  13108. read_file(SERVER_CERT2_FILE, cert);
  13109. SSLClient cli("google.com");
  13110. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13111. cli.enable_system_ca(true);
  13112. cli.enable_server_certificate_verification(true);
  13113. auto res = cli.Get("/");
  13114. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13115. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13116. }
  13117. // The custom CA remains effective when combined with the system CA
  13118. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  13119. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13120. ASSERT_TRUE(svr.is_valid());
  13121. svr.Get("/test", [&](const Request &, Response &res) {
  13122. res.set_content("test", "text/plain");
  13123. });
  13124. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13125. auto se = detail::scope_exit([&] {
  13126. svr.stop();
  13127. t.join();
  13128. ASSERT_FALSE(svr.is_running());
  13129. });
  13130. svr.wait_until_ready();
  13131. SSLClient cli("127.0.0.1", PORT);
  13132. std::string cert;
  13133. read_file(SERVER_CERT2_FILE, cert);
  13134. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13135. cli.enable_system_ca(true);
  13136. cli.enable_server_certificate_verification(true);
  13137. cli.set_connection_timeout(30);
  13138. auto res = cli.Get("/test");
  13139. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13140. ASSERT_EQ(StatusCode::OK_200, res->status);
  13141. }
  13142. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  13143. // skip chain verification entirely (only the certificate identity was
  13144. // checked), so a server presenting an untrusted certificate with a matching
  13145. // IP SAN was accepted. The chain must be validated for IP hosts too.
  13146. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  13147. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13148. ASSERT_TRUE(svr.is_valid());
  13149. svr.Get("/test", [&](const Request &, Response &res) {
  13150. res.set_content("test", "text/plain");
  13151. });
  13152. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13153. auto se = detail::scope_exit([&] {
  13154. svr.stop();
  13155. t.join();
  13156. ASSERT_FALSE(svr.is_running());
  13157. });
  13158. svr.wait_until_ready();
  13159. SSLClient cli("127.0.0.1", PORT);
  13160. std::string cert;
  13161. // A trusted CA that did not sign the server certificate. The server cert
  13162. // (cert2) carries the matching IP SAN, so only chain validation can reject
  13163. // this connection.
  13164. read_file(CLIENT_CA_CERT_FILE, cert);
  13165. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13166. cli.enable_server_certificate_verification(true);
  13167. cli.set_connection_timeout(30);
  13168. auto res = cli.Get("/test");
  13169. ASSERT_FALSE(res);
  13170. }
  13171. // enable_system_ca(false) prevents system CA loading entirely
  13172. TEST(SSLClientTest, DisableSystemCa_Online) {
  13173. SSLClient cli("google.com");
  13174. cli.enable_system_ca(false);
  13175. cli.enable_server_certificate_verification(true);
  13176. auto res = cli.Get("/");
  13177. ASSERT_FALSE(res);
  13178. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  13179. // itself when the CA chain is empty
  13180. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  13181. res.error() == Error::SSLConnection);
  13182. }
  13183. // The universal Client forwards enable_system_ca()
  13184. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  13185. std::string cert;
  13186. read_file(SERVER_CERT2_FILE, cert);
  13187. Client cli("https://google.com");
  13188. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13189. cli.enable_system_ca(true);
  13190. cli.enable_server_certificate_verification(true);
  13191. auto res = cli.Get("/");
  13192. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13193. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13194. }
  13195. // The system CA policy must carry over to the client created internally for
  13196. // following a cross-host HTTPS redirect
  13197. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  13198. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13199. ASSERT_TRUE(svr.is_valid());
  13200. svr.Get("/index", [&](const Request &, Response &res) {
  13201. res.set_redirect("https://www.google.com/");
  13202. });
  13203. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13204. auto se = detail::scope_exit([&] {
  13205. svr.stop();
  13206. t.join();
  13207. ASSERT_FALSE(svr.is_running());
  13208. });
  13209. svr.wait_until_ready();
  13210. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  13211. std::string cert;
  13212. read_file(SERVER_CERT2_FILE, cert);
  13213. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13214. cli.enable_system_ca(true);
  13215. cli.enable_server_certificate_verification(true);
  13216. cli.set_follow_location(true);
  13217. cli.set_connection_timeout(30);
  13218. // Receiving any response proves the redirect client completed the TLS
  13219. // handshake with a system-CA-signed host
  13220. auto res = cli.Get("/index");
  13221. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13222. }
  13223. TEST(MultipartFormDataTest, LargeData) {
  13224. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13225. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  13226. const ContentReader &content_reader) {
  13227. if (req.is_multipart_form_data()) {
  13228. std::vector<FormData> items;
  13229. content_reader(
  13230. [&](const FormData &file) {
  13231. items.push_back(file);
  13232. return true;
  13233. },
  13234. [&](const char *data, size_t data_length) {
  13235. items.back().content.append(data, data_length);
  13236. return true;
  13237. });
  13238. EXPECT_TRUE(std::string(items[0].name) == "document");
  13239. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13240. EXPECT_TRUE(items[0].filename == "2MB_data");
  13241. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13242. EXPECT_TRUE(items[1].name == "hello");
  13243. EXPECT_TRUE(items[1].content == "world");
  13244. EXPECT_TRUE(items[1].filename == "");
  13245. EXPECT_TRUE(items[1].content_type == "");
  13246. } else {
  13247. std::string body;
  13248. content_reader([&](const char *data, size_t data_length) {
  13249. body.append(data, data_length);
  13250. return true;
  13251. });
  13252. }
  13253. });
  13254. auto port = svr.bind_to_any_port(HOST);
  13255. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13256. auto se = detail::scope_exit([&] {
  13257. svr.stop();
  13258. t.join();
  13259. ASSERT_FALSE(svr.is_running());
  13260. });
  13261. svr.wait_until_ready();
  13262. {
  13263. std::string data(1024 * 1024 * 2, '.');
  13264. std::stringstream buffer;
  13265. buffer << data;
  13266. SSLClient cli(HOST, port);
  13267. cli.enable_server_certificate_verification(false);
  13268. UploadFormDataItems items{
  13269. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13270. {"hello", "world", "", ""},
  13271. };
  13272. auto res = cli.Post("/post", items);
  13273. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13274. ASSERT_EQ(StatusCode::OK_200, res->status);
  13275. }
  13276. }
  13277. TEST(MultipartFormDataTest, DataProviderItems) {
  13278. std::random_device seed_gen;
  13279. std::mt19937 random(seed_gen());
  13280. std::string rand1;
  13281. rand1.resize(1000);
  13282. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  13283. std::string rand2;
  13284. rand2.resize(3000);
  13285. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  13286. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13287. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  13288. const ContentReader &content_reader) {
  13289. ASSERT_FALSE(req.is_multipart_form_data());
  13290. std::string body;
  13291. content_reader([&](const char *data, size_t data_length) {
  13292. body.append(data, data_length);
  13293. return true;
  13294. });
  13295. EXPECT_EQ(body, "");
  13296. });
  13297. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  13298. const ContentReader &content_reader) {
  13299. ASSERT_TRUE(req.is_multipart_form_data());
  13300. std::vector<FormData> items;
  13301. content_reader(
  13302. [&](const FormData &file) {
  13303. items.push_back(file);
  13304. return true;
  13305. },
  13306. [&](const char *data, size_t data_length) {
  13307. items.back().content.append(data, data_length);
  13308. return true;
  13309. });
  13310. ASSERT_TRUE(items.size() == 2);
  13311. EXPECT_EQ(std::string(items[0].name), "name1");
  13312. EXPECT_EQ(items[0].content, "Testing123");
  13313. EXPECT_EQ(items[0].filename, "filename1");
  13314. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  13315. EXPECT_EQ(items[1].name, "name2");
  13316. EXPECT_EQ(items[1].content, "Testing456");
  13317. EXPECT_EQ(items[1].filename, "");
  13318. EXPECT_EQ(items[1].content_type, "");
  13319. });
  13320. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  13321. const ContentReader &content_reader) {
  13322. ASSERT_TRUE(req.is_multipart_form_data());
  13323. std::vector<FormData> items;
  13324. content_reader(
  13325. [&](const FormData &file) {
  13326. items.push_back(file);
  13327. return true;
  13328. },
  13329. [&](const char *data, size_t data_length) {
  13330. items.back().content.append(data, data_length);
  13331. return true;
  13332. });
  13333. ASSERT_TRUE(items.size() == 2);
  13334. EXPECT_EQ(items[0].name, "name3");
  13335. EXPECT_EQ(items[0].content, rand1);
  13336. EXPECT_EQ(items[0].filename, "filename3");
  13337. EXPECT_EQ(items[0].content_type, "");
  13338. EXPECT_EQ(items[1].name, "name4");
  13339. EXPECT_EQ(items[1].content, rand2);
  13340. EXPECT_EQ(items[1].filename, "filename4");
  13341. EXPECT_EQ(items[1].content_type, "");
  13342. });
  13343. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  13344. const ContentReader &content_reader) {
  13345. ASSERT_TRUE(req.is_multipart_form_data());
  13346. std::vector<FormData> items;
  13347. content_reader(
  13348. [&](const FormData &file) {
  13349. items.push_back(file);
  13350. return true;
  13351. },
  13352. [&](const char *data, size_t data_length) {
  13353. items.back().content.append(data, data_length);
  13354. return true;
  13355. });
  13356. ASSERT_TRUE(items.size() == 4);
  13357. EXPECT_EQ(std::string(items[0].name), "name1");
  13358. EXPECT_EQ(items[0].content, "Testing123");
  13359. EXPECT_EQ(items[0].filename, "filename1");
  13360. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  13361. EXPECT_EQ(items[1].name, "name2");
  13362. EXPECT_EQ(items[1].content, "Testing456");
  13363. EXPECT_EQ(items[1].filename, "");
  13364. EXPECT_EQ(items[1].content_type, "");
  13365. EXPECT_EQ(items[2].name, "name3");
  13366. EXPECT_EQ(items[2].content, rand1);
  13367. EXPECT_EQ(items[2].filename, "filename3");
  13368. EXPECT_EQ(items[2].content_type, "");
  13369. EXPECT_EQ(items[3].name, "name4");
  13370. EXPECT_EQ(items[3].content, rand2);
  13371. EXPECT_EQ(items[3].filename, "filename4");
  13372. EXPECT_EQ(items[3].content_type, "");
  13373. });
  13374. auto port = svr.bind_to_any_port("localhost");
  13375. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13376. auto se = detail::scope_exit([&] {
  13377. svr.stop();
  13378. t.join();
  13379. ASSERT_FALSE(svr.is_running());
  13380. });
  13381. svr.wait_until_ready();
  13382. {
  13383. SSLClient cli("localhost", port);
  13384. cli.enable_server_certificate_verification(false);
  13385. UploadFormDataItems items{
  13386. {"name1", "Testing123", "filename1", "application/octet-stream"},
  13387. {"name2", "Testing456", "", ""}, // not a file
  13388. };
  13389. {
  13390. auto res = cli.Post("/post-none", {}, {}, {});
  13391. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13392. ASSERT_EQ(StatusCode::OK_200, res->status);
  13393. }
  13394. FormDataProviderItems providers;
  13395. {
  13396. auto res =
  13397. cli.Post("/post-items", {}, items, providers); // empty providers
  13398. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13399. ASSERT_EQ(StatusCode::OK_200, res->status);
  13400. }
  13401. providers.push_back({"name3",
  13402. [&](size_t offset, httplib::DataSink &sink) -> bool {
  13403. // test the offset is given correctly at each step
  13404. if (!offset)
  13405. sink.os.write(rand1.data(), 30);
  13406. else if (offset == 30)
  13407. sink.os.write(rand1.data() + 30, 300);
  13408. else if (offset == 330)
  13409. sink.os.write(rand1.data() + 330, 670);
  13410. else if (offset == rand1.size())
  13411. sink.done();
  13412. return true;
  13413. },
  13414. "filename3",
  13415. {}});
  13416. providers.push_back({"name4",
  13417. [&](size_t offset, httplib::DataSink &sink) -> bool {
  13418. // test the offset is given correctly at each step
  13419. if (!offset)
  13420. sink.os.write(rand2.data(), 2000);
  13421. else if (offset == 2000)
  13422. sink.os.write(rand2.data() + 2000, 1);
  13423. else if (offset == 2001)
  13424. sink.os.write(rand2.data() + 2001, 999);
  13425. else if (offset == rand2.size())
  13426. sink.done();
  13427. return true;
  13428. },
  13429. "filename4",
  13430. {}});
  13431. {
  13432. auto res = cli.Post("/post-providers", {}, {}, providers);
  13433. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13434. ASSERT_EQ(StatusCode::OK_200, res->status);
  13435. }
  13436. {
  13437. auto res = cli.Post("/post-both", {}, items, providers);
  13438. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13439. ASSERT_EQ(StatusCode::OK_200, res->status);
  13440. }
  13441. }
  13442. }
  13443. TEST(MultipartFormDataTest, BadHeader) {
  13444. Server svr;
  13445. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  13446. res.set_content("ok", "text/plain");
  13447. });
  13448. thread t = thread([&] { svr.listen(HOST, PORT); });
  13449. auto se = detail::scope_exit([&] {
  13450. svr.stop();
  13451. t.join();
  13452. ASSERT_FALSE(svr.is_running());
  13453. });
  13454. svr.wait_until_ready();
  13455. const std::string body =
  13456. "This is the preamble. It is to be ignored, though it\r\n"
  13457. "is a handy place for composition agents to include an\r\n"
  13458. "explanatory note to non-MIME conformant readers.\r\n"
  13459. "\r\n"
  13460. "\r\n"
  13461. "--simple boundary\r\n"
  13462. "Content-Disposition: form-data; name=\"field1\"\r\n"
  13463. ": BAD...\r\n"
  13464. "\r\n"
  13465. "value1\r\n"
  13466. "--simple boundary\r\n"
  13467. "Content-Disposition: form-data; name=\"field2\"; "
  13468. "filename=\"example.txt\"\r\n"
  13469. "\r\n"
  13470. "value2\r\n"
  13471. "--simple boundary--\r\n"
  13472. "This is the epilogue. It is also to be ignored.\r\n";
  13473. std::string content_type =
  13474. R"(multipart/form-data; boundary="simple boundary")";
  13475. Client cli(HOST, PORT);
  13476. auto res = cli.Post("/post", body, content_type.c_str());
  13477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13478. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  13479. }
  13480. TEST(MultipartFormDataTest, WithPreamble) {
  13481. Server svr;
  13482. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  13483. res.set_content("ok", "text/plain");
  13484. });
  13485. thread t = thread([&] { svr.listen(HOST, PORT); });
  13486. auto se = detail::scope_exit([&] {
  13487. svr.stop();
  13488. t.join();
  13489. ASSERT_FALSE(svr.is_running());
  13490. });
  13491. svr.wait_until_ready();
  13492. const std::string body =
  13493. "This is the preamble. It is to be ignored, though it\r\n"
  13494. "is a handy place for composition agents to include an\r\n"
  13495. "explanatory note to non-MIME conformant readers.\r\n"
  13496. "\r\n"
  13497. "\r\n"
  13498. "--simple boundary\r\n"
  13499. "Content-Disposition: form-data; name=\"field1\"\r\n"
  13500. "\r\n"
  13501. "value1\r\n"
  13502. "--simple boundary\r\n"
  13503. "Content-Disposition: form-data; name=\"field2\"; "
  13504. "filename=\"example.txt\"\r\n"
  13505. "\r\n"
  13506. "value2\r\n"
  13507. "--simple boundary--\r\n"
  13508. "This is the epilogue. It is also to be ignored.\r\n";
  13509. std::string content_type =
  13510. R"(multipart/form-data; boundary="simple boundary")";
  13511. Client cli(HOST, PORT);
  13512. auto res = cli.Post("/post", body, content_type.c_str());
  13513. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13514. EXPECT_EQ(StatusCode::OK_200, res->status);
  13515. }
  13516. TEST(MultipartFormDataTest, PostCustomBoundary) {
  13517. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13518. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  13519. const ContentReader &content_reader) {
  13520. if (req.is_multipart_form_data()) {
  13521. std::vector<FormData> items;
  13522. content_reader(
  13523. [&](const FormData &file) {
  13524. items.push_back(file);
  13525. return true;
  13526. },
  13527. [&](const char *data, size_t data_length) {
  13528. items.back().content.append(data, data_length);
  13529. return true;
  13530. });
  13531. EXPECT_TRUE(std::string(items[0].name) == "document");
  13532. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13533. EXPECT_TRUE(items[0].filename == "2MB_data");
  13534. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13535. EXPECT_TRUE(items[1].name == "hello");
  13536. EXPECT_TRUE(items[1].content == "world");
  13537. EXPECT_TRUE(items[1].filename == "");
  13538. EXPECT_TRUE(items[1].content_type == "");
  13539. } else {
  13540. std::string body;
  13541. content_reader([&](const char *data, size_t data_length) {
  13542. body.append(data, data_length);
  13543. return true;
  13544. });
  13545. }
  13546. });
  13547. auto port = svr.bind_to_any_port("localhost");
  13548. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13549. auto se = detail::scope_exit([&] {
  13550. svr.stop();
  13551. t.join();
  13552. ASSERT_FALSE(svr.is_running());
  13553. });
  13554. svr.wait_until_ready();
  13555. {
  13556. std::string data(1024 * 1024 * 2, '.');
  13557. std::stringstream buffer;
  13558. buffer << data;
  13559. SSLClient cli("localhost", port);
  13560. cli.enable_server_certificate_verification(false);
  13561. UploadFormDataItems items{
  13562. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13563. {"hello", "world", "", ""},
  13564. };
  13565. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  13566. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13567. ASSERT_EQ(StatusCode::OK_200, res->status);
  13568. }
  13569. }
  13570. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  13571. std::string data(1024 * 1024 * 2, '&');
  13572. std::stringstream buffer;
  13573. buffer << data;
  13574. Client cli("https://localhost:8080");
  13575. UploadFormDataItems items{
  13576. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13577. {"hello", "world", "", ""},
  13578. };
  13579. for (const char &c : " \t\r\n") {
  13580. auto res =
  13581. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  13582. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  13583. ASSERT_FALSE(res);
  13584. }
  13585. }
  13586. TEST(MultipartFormDataTest, PutFormData) {
  13587. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13588. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  13589. const ContentReader &content_reader) {
  13590. if (req.is_multipart_form_data()) {
  13591. std::vector<FormData> items;
  13592. content_reader(
  13593. [&](const FormData &file) {
  13594. items.push_back(file);
  13595. return true;
  13596. },
  13597. [&](const char *data, size_t data_length) {
  13598. items.back().content.append(data, data_length);
  13599. return true;
  13600. });
  13601. EXPECT_TRUE(std::string(items[0].name) == "document");
  13602. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13603. EXPECT_TRUE(items[0].filename == "2MB_data");
  13604. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13605. EXPECT_TRUE(items[1].name == "hello");
  13606. EXPECT_TRUE(items[1].content == "world");
  13607. EXPECT_TRUE(items[1].filename == "");
  13608. EXPECT_TRUE(items[1].content_type == "");
  13609. } else {
  13610. std::string body;
  13611. content_reader([&](const char *data, size_t data_length) {
  13612. body.append(data, data_length);
  13613. return true;
  13614. });
  13615. }
  13616. });
  13617. auto port = svr.bind_to_any_port("localhost");
  13618. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13619. auto se = detail::scope_exit([&] {
  13620. svr.stop();
  13621. t.join();
  13622. ASSERT_FALSE(svr.is_running());
  13623. });
  13624. svr.wait_until_ready();
  13625. {
  13626. std::string data(1024 * 1024 * 2, '&');
  13627. std::stringstream buffer;
  13628. buffer << data;
  13629. SSLClient cli("localhost", port);
  13630. cli.enable_server_certificate_verification(false);
  13631. UploadFormDataItems items{
  13632. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13633. {"hello", "world", "", ""},
  13634. };
  13635. auto res = cli.Put("/put", items);
  13636. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13637. ASSERT_EQ(StatusCode::OK_200, res->status);
  13638. }
  13639. }
  13640. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  13641. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13642. svr.Put("/put_customboundary",
  13643. [&](const Request &req, const Response & /*res*/,
  13644. const ContentReader &content_reader) {
  13645. if (req.is_multipart_form_data()) {
  13646. std::vector<FormData> items;
  13647. content_reader(
  13648. [&](const FormData &file) {
  13649. items.push_back(file);
  13650. return true;
  13651. },
  13652. [&](const char *data, size_t data_length) {
  13653. items.back().content.append(data, data_length);
  13654. return true;
  13655. });
  13656. EXPECT_TRUE(std::string(items[0].name) == "document");
  13657. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13658. EXPECT_TRUE(items[0].filename == "2MB_data");
  13659. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13660. EXPECT_TRUE(items[1].name == "hello");
  13661. EXPECT_TRUE(items[1].content == "world");
  13662. EXPECT_TRUE(items[1].filename == "");
  13663. EXPECT_TRUE(items[1].content_type == "");
  13664. } else {
  13665. std::string body;
  13666. content_reader([&](const char *data, size_t data_length) {
  13667. body.append(data, data_length);
  13668. return true;
  13669. });
  13670. }
  13671. });
  13672. auto port = svr.bind_to_any_port("localhost");
  13673. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13674. auto se = detail::scope_exit([&] {
  13675. svr.stop();
  13676. t.join();
  13677. ASSERT_FALSE(svr.is_running());
  13678. });
  13679. svr.wait_until_ready();
  13680. {
  13681. std::string data(1024 * 1024 * 2, '&');
  13682. std::stringstream buffer;
  13683. buffer << data;
  13684. SSLClient cli("localhost", port);
  13685. cli.enable_server_certificate_verification(false);
  13686. UploadFormDataItems items{
  13687. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13688. {"hello", "world", "", ""},
  13689. };
  13690. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  13691. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13692. ASSERT_EQ(StatusCode::OK_200, res->status);
  13693. }
  13694. }
  13695. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  13696. std::string data(1024 * 1024 * 2, '&');
  13697. std::stringstream buffer;
  13698. buffer << data;
  13699. Client cli("https://localhost:8080");
  13700. cli.enable_server_certificate_verification(false);
  13701. UploadFormDataItems items{
  13702. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13703. {"hello", "world", "", ""},
  13704. };
  13705. for (const char &c : " \t\r\n") {
  13706. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  13707. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  13708. ASSERT_FALSE(res);
  13709. }
  13710. }
  13711. TEST(MultipartFormDataTest, AlternateFilename) {
  13712. auto handled = false;
  13713. Server svr;
  13714. svr.Post("/test", [&](const Request &req, Response &res) {
  13715. ASSERT_EQ(2u, req.form.files.size());
  13716. ASSERT_EQ(1u, req.form.fields.size());
  13717. // Test files
  13718. const auto &file1 = req.form.get_file("file1");
  13719. ASSERT_EQ("file1", file1.name);
  13720. ASSERT_EQ("A.txt", file1.filename);
  13721. ASSERT_EQ("text/plain", file1.content_type);
  13722. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  13723. const auto &file2 = req.form.get_file("file2");
  13724. ASSERT_EQ("file2", file2.name);
  13725. ASSERT_EQ("a.html", file2.filename);
  13726. ASSERT_EQ("text/html", file2.content_type);
  13727. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  13728. file2.content);
  13729. // Test text field
  13730. const auto &text = req.form.get_field("text");
  13731. ASSERT_EQ("text default", text);
  13732. res.set_content("ok", "text/plain");
  13733. handled = true;
  13734. });
  13735. thread t = thread([&] { svr.listen(HOST, PORT); });
  13736. auto se = detail::scope_exit([&] {
  13737. svr.stop();
  13738. t.join();
  13739. ASSERT_FALSE(svr.is_running());
  13740. ASSERT_TRUE(handled);
  13741. });
  13742. svr.wait_until_ready();
  13743. auto req = "POST /test HTTP/1.1\r\n"
  13744. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13745. "Content-Length: 399\r\n"
  13746. "\r\n"
  13747. "----------\r\n"
  13748. "Content-Disposition: form-data; name=\"text\"\r\n"
  13749. "\r\n"
  13750. "text default\r\n"
  13751. "----------\r\n"
  13752. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  13753. "filename=\"a.txt\"; name=\"file1\"\r\n"
  13754. "Content-Type: text/plain\r\n"
  13755. "\r\n"
  13756. "Content of a.txt.\r\n"
  13757. "\r\n"
  13758. "----------\r\n"
  13759. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  13760. "\"a.html\"\r\n"
  13761. "Content-Type: text/html\r\n"
  13762. "\r\n"
  13763. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  13764. "\r\n"
  13765. "------------\r\n";
  13766. ASSERT_TRUE(send_request(1, req));
  13767. }
  13768. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  13769. auto handled = false;
  13770. Server svr;
  13771. svr.Post("/test", [&](const Request &req, Response &res) {
  13772. // Case-insensitive "utf-8''" prefix with a long value
  13773. const auto &file = req.form.get_file("file1");
  13774. ASSERT_EQ("file1", file.name);
  13775. // 8000 chars exercises both the Content-Disposition parser and the
  13776. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  13777. // Prior to the fix, std::regex_match on this header would cause O(N)
  13778. // stack recursion in libstdc++, leading to SIGSEGV.
  13779. std::string expected_filename(8000, 'A');
  13780. ASSERT_EQ(expected_filename, file.filename);
  13781. res.set_content("ok", "text/plain");
  13782. handled = true;
  13783. });
  13784. thread t = thread([&] { svr.listen(HOST, PORT); });
  13785. auto se = detail::scope_exit([&] {
  13786. svr.stop();
  13787. t.join();
  13788. ASSERT_FALSE(svr.is_running());
  13789. ASSERT_TRUE(handled);
  13790. });
  13791. svr.wait_until_ready();
  13792. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  13793. // Regression test for GHSA-qq6v-r583-3h69
  13794. std::string long_filename(8000, 'A');
  13795. std::string body = "----------\r\n"
  13796. "Content-Disposition: form-data; name=\"file1\"; "
  13797. "filename*=\"Utf-8''" +
  13798. long_filename +
  13799. "\"\r\n"
  13800. "\r\n"
  13801. "hello\r\n"
  13802. "------------\r\n";
  13803. auto req = "POST /test HTTP/1.1\r\n"
  13804. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13805. "Content-Length: " +
  13806. std::to_string(body.size()) + "\r\n\r\n" + body;
  13807. ASSERT_TRUE(send_request(1, req));
  13808. }
  13809. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  13810. auto handled = false;
  13811. Server svr;
  13812. svr.Post("/test", [&](const Request &req, Response &) {
  13813. ASSERT_EQ(2u, req.form.fields.size());
  13814. const auto &text1 = req.form.get_field("text1");
  13815. ASSERT_EQ("text1", text1);
  13816. const auto &text2 = req.form.get_field("text2");
  13817. ASSERT_EQ("text2", text2);
  13818. handled = true;
  13819. });
  13820. thread t = thread([&] { svr.listen(HOST, PORT); });
  13821. auto se = detail::scope_exit([&] {
  13822. svr.stop();
  13823. t.join();
  13824. ASSERT_FALSE(svr.is_running());
  13825. ASSERT_TRUE(handled);
  13826. });
  13827. svr.wait_until_ready();
  13828. auto req = "POST /test HTTP/1.1\r\n"
  13829. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13830. "Content-Length: 146\r\n"
  13831. "\r\n----------\r\n"
  13832. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13833. "\r\n"
  13834. "text1"
  13835. "\r\n----------\r\n"
  13836. "Content-Disposition: form-data; name=\"text2\"\r\n"
  13837. "\r\n"
  13838. "text2"
  13839. "\r\n------------";
  13840. std::string response;
  13841. ASSERT_TRUE(send_request(1, req, &response));
  13842. ASSERT_EQ("200", response.substr(9, 3));
  13843. }
  13844. TEST(MultipartFormDataTest, ContentLength) {
  13845. auto handled = false;
  13846. Server svr;
  13847. svr.Post("/test", [&](const Request &req, Response &) {
  13848. ASSERT_EQ(2u, req.form.fields.size());
  13849. const auto &text1 = req.form.get_field("text1");
  13850. ASSERT_EQ("text1", text1);
  13851. const auto &text2 = req.form.get_field("text2");
  13852. ASSERT_EQ("text2", text2);
  13853. handled = true;
  13854. });
  13855. thread t = thread([&] { svr.listen(HOST, PORT); });
  13856. auto se = detail::scope_exit([&] {
  13857. svr.stop();
  13858. t.join();
  13859. ASSERT_FALSE(svr.is_running());
  13860. ASSERT_TRUE(handled);
  13861. });
  13862. svr.wait_until_ready();
  13863. auto req = "POST /test HTTP/1.1\r\n"
  13864. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13865. "Content-Length: 167\r\n"
  13866. "\r\n----------\r\n"
  13867. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13868. "Content-Length: 5\r\n"
  13869. "\r\n"
  13870. "text1"
  13871. "\r\n----------\r\n"
  13872. "Content-Disposition: form-data; name=\"text2\"\r\n"
  13873. "\r\n"
  13874. "text2"
  13875. "\r\n------------\r\n";
  13876. std::string response;
  13877. ASSERT_TRUE(send_request(1, req, &response));
  13878. ASSERT_EQ("200", response.substr(9, 3));
  13879. }
  13880. TEST(MultipartFormDataTest, AccessPartHeaders) {
  13881. auto handled = false;
  13882. Server svr;
  13883. svr.Post("/test", [&](const Request &req, Response &) {
  13884. ASSERT_EQ(2u, req.form.fields.size());
  13885. const auto &text1 = req.form.get_field("text1");
  13886. ASSERT_EQ("text1", text1);
  13887. // TODO: Add header access for text fields if needed
  13888. const auto &text2 = req.form.get_field("text2");
  13889. ASSERT_EQ("text2", text2);
  13890. // TODO: Header access for text fields needs to be implemented
  13891. // auto &headers = it->second.headers;
  13892. // ASSERT_EQ(3U, headers.size());
  13893. // auto custom_header = headers.find("x-whatever");
  13894. // ASSERT_TRUE(custom_header != headers.end());
  13895. // ASSERT_NE("customvalue", custom_header->second);
  13896. // ASSERT_EQ("CustomValue", custom_header->second);
  13897. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  13898. handled = true;
  13899. });
  13900. thread t = thread([&] { svr.listen(HOST, PORT); });
  13901. auto se = detail::scope_exit([&] {
  13902. svr.stop();
  13903. t.join();
  13904. ASSERT_FALSE(svr.is_running());
  13905. ASSERT_TRUE(handled);
  13906. });
  13907. svr.wait_until_ready();
  13908. auto req = "POST /test HTTP/1.1\r\n"
  13909. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13910. "Content-Length: 232\r\n"
  13911. "\r\n----------\r\n"
  13912. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13913. "Content-Length: 5\r\n"
  13914. "X-Test: 1\r\n"
  13915. "\r\n"
  13916. "text1"
  13917. "\r\n----------\r\n"
  13918. "Content-Disposition: form-data; name=\"text2\"\r\n"
  13919. "Content-Type: text/plain\r\n"
  13920. "X-Whatever: CustomValue\r\n"
  13921. "\r\n"
  13922. "text2"
  13923. "\r\n------------\r\n"
  13924. "That should be disregarded. Not even read";
  13925. std::string response;
  13926. ASSERT_TRUE(send_request(1, req, &response));
  13927. ASSERT_EQ("200", response.substr(9, 3));
  13928. }
  13929. TEST(MultipartFormDataTest, LargeHeader) {
  13930. auto handled = false;
  13931. Server svr;
  13932. svr.Post("/test", [&](const Request &req, Response &) {
  13933. ASSERT_EQ(1u, req.form.fields.size());
  13934. const auto &text = req.form.get_field("name1");
  13935. ASSERT_EQ("text1", text);
  13936. handled = true;
  13937. });
  13938. thread t = thread([&] { svr.listen(HOST, PORT); });
  13939. auto se = detail::scope_exit([&] {
  13940. svr.stop();
  13941. t.join();
  13942. ASSERT_FALSE(svr.is_running());
  13943. ASSERT_TRUE(handled);
  13944. });
  13945. svr.wait_until_ready();
  13946. auto boundary = std::string("cpp-httplib-multipart-data");
  13947. std::string content = "--" + boundary +
  13948. "\r\n"
  13949. "Content-Disposition: form-data; name=\"name1\"\r\n"
  13950. "\r\n"
  13951. "text1\r\n"
  13952. "--" +
  13953. boundary + "--\r\n";
  13954. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  13955. "Content-Type: multipart/form-data;boundary=" +
  13956. boundary +
  13957. "\r\n"
  13958. "Content-Length: " +
  13959. std::to_string(content.size()) +
  13960. "\r\n"
  13961. "Dummy-Header: ";
  13962. std::string header_suffix = "\r\n"
  13963. "\r\n";
  13964. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  13965. size_t header_dummy_size =
  13966. read_buff_size -
  13967. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  13968. auto header_dummy = std::string(header_dummy_size, '@');
  13969. auto req = header_prefix + header_dummy + header_suffix + content;
  13970. std::string response;
  13971. ASSERT_TRUE(send_request(1, req, &response));
  13972. ASSERT_EQ("200", response.substr(9, 3));
  13973. }
  13974. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  13975. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  13976. // (not chunked Transfer-Encoding) after the streaming refactor.
  13977. auto handled = false;
  13978. Server svr;
  13979. svr.Post("/upload", [&](const Request &req, Response &res) {
  13980. auto cl_it = req.headers.find("Content-Length");
  13981. EXPECT_TRUE(cl_it != req.headers.end());
  13982. auto te_it = req.headers.find("Transfer-Encoding");
  13983. EXPECT_TRUE(te_it == req.headers.end());
  13984. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  13985. res.set_content("ok", "text/plain");
  13986. handled = true;
  13987. });
  13988. auto port = svr.bind_to_any_port(HOST);
  13989. auto t = thread([&] { svr.listen_after_bind(); });
  13990. auto se = detail::scope_exit([&] {
  13991. svr.stop();
  13992. t.join();
  13993. ASSERT_FALSE(svr.is_running());
  13994. ASSERT_TRUE(handled);
  13995. });
  13996. svr.wait_until_ready();
  13997. UploadFormDataItems items = {
  13998. {"field1", "hello", "", "text/plain"},
  13999. {"file1", "world", "test.txt", "application/octet-stream"},
  14000. };
  14001. Client cli(HOST, port);
  14002. auto res = cli.Post("/upload", {}, items);
  14003. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14004. EXPECT_EQ(StatusCode::OK_200, res->status);
  14005. }
  14006. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  14007. // Verify that make_multipart_content_provider coalesces many small segments
  14008. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  14009. constexpr size_t kItemCount = 1000;
  14010. UploadFormDataItems items;
  14011. items.reserve(kItemCount);
  14012. for (size_t i = 0; i < kItemCount; i++) {
  14013. items.push_back(
  14014. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  14015. }
  14016. const std::string boundary = "----test-boundary";
  14017. auto content_length = detail::get_multipart_content_length(items, boundary);
  14018. auto provider = detail::make_multipart_content_provider(items, boundary);
  14019. // Drive the provider the same way write_content_with_progress does
  14020. size_t write_count = 0;
  14021. size_t total_bytes = 0;
  14022. DataSink sink;
  14023. size_t offset = 0;
  14024. sink.write = [&](const char *d, size_t l) -> bool {
  14025. (void)d;
  14026. write_count++;
  14027. total_bytes += l;
  14028. offset += l;
  14029. return true;
  14030. };
  14031. sink.is_writable = []() -> bool { return true; };
  14032. while (offset < content_length) {
  14033. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  14034. }
  14035. EXPECT_EQ(content_length, total_bytes);
  14036. // The total number of segments is 3 * kItemCount + 1 = 3001.
  14037. // With buffering into 64KB blocks, write_count should be much smaller.
  14038. auto segment_count = 3 * kItemCount + 1;
  14039. EXPECT_LT(write_count, segment_count / 10);
  14040. }
  14041. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  14042. // Integration test: send many UploadFormDataItems and verify the server
  14043. // receives all of them correctly (#2410).
  14044. constexpr size_t kItemCount = 500;
  14045. auto handled = false;
  14046. Server svr;
  14047. svr.Post("/upload", [&](const Request &req, Response &res) {
  14048. EXPECT_EQ(kItemCount, req.form.fields.size());
  14049. for (size_t i = 0; i < kItemCount; i++) {
  14050. auto key = "field" + std::to_string(i);
  14051. auto val = "value" + std::to_string(i);
  14052. auto it = req.form.fields.find(key);
  14053. if (it != req.form.fields.end()) {
  14054. EXPECT_EQ(val, it->second.content);
  14055. } else {
  14056. ADD_FAILURE() << "Missing field: " << key;
  14057. }
  14058. }
  14059. res.set_content("ok", "text/plain");
  14060. handled = true;
  14061. });
  14062. auto port = svr.bind_to_any_port(HOST);
  14063. auto t = thread([&] { svr.listen_after_bind(); });
  14064. auto se = detail::scope_exit([&] {
  14065. svr.stop();
  14066. t.join();
  14067. ASSERT_FALSE(svr.is_running());
  14068. ASSERT_TRUE(handled);
  14069. });
  14070. svr.wait_until_ready();
  14071. UploadFormDataItems items;
  14072. items.reserve(kItemCount);
  14073. for (size_t i = 0; i < kItemCount; i++) {
  14074. items.push_back(
  14075. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  14076. }
  14077. Client cli(HOST, port);
  14078. auto res = cli.Post("/upload", items);
  14079. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14080. EXPECT_EQ(StatusCode::OK_200, res->status);
  14081. }
  14082. TEST(MultipartFormDataTest, MakeFileProvider) {
  14083. // Verify make_file_provider sends a file's contents correctly.
  14084. const std::string file_content(4096, 'Z');
  14085. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  14086. {
  14087. std::ofstream ofs(tmp_path, std::ios::binary);
  14088. ofs.write(file_content.data(),
  14089. static_cast<std::streamsize>(file_content.size()));
  14090. }
  14091. auto handled = false;
  14092. Server svr;
  14093. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  14094. const ContentReader &content_reader) {
  14095. ASSERT_TRUE(req.is_multipart_form_data());
  14096. std::vector<FormData> items;
  14097. content_reader(
  14098. [&](const FormData &file) {
  14099. items.push_back(file);
  14100. return true;
  14101. },
  14102. [&](const char *data, size_t data_length) {
  14103. items.back().content.append(data, data_length);
  14104. return true;
  14105. });
  14106. ASSERT_EQ(1u, items.size());
  14107. EXPECT_EQ("myfile", items[0].name);
  14108. EXPECT_EQ("data.bin", items[0].filename);
  14109. EXPECT_EQ("application/octet-stream", items[0].content_type);
  14110. EXPECT_EQ(file_content, items[0].content);
  14111. handled = true;
  14112. });
  14113. auto port = svr.bind_to_any_port(HOST);
  14114. auto t = thread([&] { svr.listen_after_bind(); });
  14115. auto se = detail::scope_exit([&] {
  14116. svr.stop();
  14117. t.join();
  14118. ASSERT_FALSE(svr.is_running());
  14119. ASSERT_TRUE(handled);
  14120. std::remove(tmp_path.c_str());
  14121. });
  14122. svr.wait_until_ready();
  14123. FormDataProviderItems providers;
  14124. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  14125. "application/octet-stream"));
  14126. Client cli(HOST, port);
  14127. auto res = cli.Post("/upload", {}, {}, providers);
  14128. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14129. EXPECT_EQ(StatusCode::OK_200, res->status);
  14130. }
  14131. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  14132. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  14133. // (100) headers is rejected with a 400 Bad Request response.
  14134. Server svr;
  14135. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14136. res.set_content("ok", "text/plain");
  14137. });
  14138. thread t = thread([&] { svr.listen(HOST, PORT); });
  14139. auto se = detail::scope_exit([&] {
  14140. svr.stop();
  14141. t.join();
  14142. ASSERT_FALSE(svr.is_running());
  14143. });
  14144. svr.wait_until_ready();
  14145. // Build a multipart part with 101 custom headers (exceeding
  14146. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  14147. std::stringstream body;
  14148. body << "--simpleboundary\r\n"
  14149. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  14150. for (int i = 0; i < 101; i++) {
  14151. body << "X-Custom-Header-" << i << ": value\r\n";
  14152. }
  14153. body << "\r\n"
  14154. << "value1\r\n"
  14155. << "--simpleboundary--\r\n";
  14156. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  14157. Client cli(HOST, PORT);
  14158. auto res = cli.Post("/post", body.str(), content_type.c_str());
  14159. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14160. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14161. }
  14162. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  14163. // A body that never contains the declared boundary must not be accumulated
  14164. // while the parser waits for it. Buffering it would also make every read
  14165. // rescan everything seen so far, which is quadratic in the body size.
  14166. Server svr;
  14167. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  14168. res.set_content("ok", "text/plain");
  14169. });
  14170. auto port = svr.bind_to_any_port(HOST);
  14171. thread t = thread([&] { svr.listen_after_bind(); });
  14172. auto se = detail::scope_exit([&] {
  14173. svr.stop();
  14174. t.join();
  14175. ASSERT_FALSE(svr.is_running());
  14176. });
  14177. svr.wait_until_ready();
  14178. Client cli(HOST, port);
  14179. cli.set_read_timeout(60, 0);
  14180. cli.set_write_timeout(60, 0);
  14181. // '-' is the worst case: it matches the first character of the boundary, so
  14182. // every position has to be checked against it.
  14183. auto post_dashes = [&](size_t size) {
  14184. const std::string body(size, '-');
  14185. auto start = std::chrono::steady_clock::now();
  14186. auto res =
  14187. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  14188. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  14189. std::chrono::steady_clock::now() - start)
  14190. .count();
  14191. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  14192. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  14193. return ms;
  14194. };
  14195. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  14196. // Windows.
  14197. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  14198. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  14199. // Comparing the two sizes rather than checking an absolute duration keeps
  14200. // this meaningful across build types and CI load, both of which move the
  14201. // absolute numbers by more than an order of magnitude. Four times the bytes
  14202. // costs about four times the time when parsing is linear, and about sixteen
  14203. // times when the body is buffered and rescanned.
  14204. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  14205. EXPECT_LT(ms_16mb, ms_4mb * 10)
  14206. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  14207. << "ms, which suggests the body is being buffered and rescanned";
  14208. }
  14209. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  14210. // A boundary can only be followed by CRLF or by "--", so anything else is
  14211. // malformed no matter what comes next. The parser must say so right away
  14212. // instead of buffering the rest of the declared body.
  14213. Server svr;
  14214. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  14215. res.set_content("ok", "text/plain");
  14216. });
  14217. auto port = svr.bind_to_any_port(HOST);
  14218. thread t = thread([&] { svr.listen_after_bind(); });
  14219. auto se = detail::scope_exit([&] {
  14220. svr.stop();
  14221. t.join();
  14222. ASSERT_FALSE(svr.is_running());
  14223. });
  14224. svr.wait_until_ready();
  14225. // Announce a 1 MB body but send only the malformed prefix. A parser that
  14226. // buffers instead of failing would still be waiting for the remaining bytes.
  14227. const std::string body = "--zzzz\r\n"
  14228. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14229. "\r\n"
  14230. "text1"
  14231. "\r\n--zzzzXX";
  14232. const std::string req = "POST /post HTTP/1.1\r\n"
  14233. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  14234. "Content-Length: 1048576\r\n"
  14235. "\r\n" +
  14236. body;
  14237. std::string response;
  14238. ASSERT_TRUE(send_request(3, req, &response, port));
  14239. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  14240. EXPECT_EQ("400", response.substr(9, 3));
  14241. }
  14242. // Posts a multipart body split into two writes, so that the server sees the
  14243. // split at whatever offset the caller chose, and expects the single "text1"
  14244. // field to come through.
  14245. static void expect_split_multipart_ok(const std::string &body1,
  14246. const std::string &body2) {
  14247. auto handled = false;
  14248. Server svr;
  14249. svr.Post("/post", [&](const Request &req, Response &) {
  14250. EXPECT_EQ(1u, req.form.fields.size());
  14251. EXPECT_EQ("text1", req.form.get_field("text1"));
  14252. handled = true;
  14253. });
  14254. auto port = svr.bind_to_any_port(HOST);
  14255. thread t = thread([&] { svr.listen_after_bind(); });
  14256. auto se = detail::scope_exit([&] {
  14257. svr.stop();
  14258. t.join();
  14259. ASSERT_FALSE(svr.is_running());
  14260. ASSERT_TRUE(handled);
  14261. });
  14262. svr.wait_until_ready();
  14263. // "Connection: close" makes the server close once it has answered, so the
  14264. // response drain ends immediately instead of idling until the read timeout.
  14265. const std::string head =
  14266. "POST /post HTTP/1.1\r\n"
  14267. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  14268. "Connection: close\r\n"
  14269. "Content-Length: " +
  14270. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  14271. std::string response;
  14272. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  14273. ASSERT_GE(response.size(), 12u) << "no response";
  14274. EXPECT_EQ("200", response.substr(9, 3));
  14275. }
  14276. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  14277. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  14278. // ignored, including when it does not arrive in the same read as the
  14279. // close-delimiter itself.
  14280. expect_split_multipart_ok("--zzzz\r\n"
  14281. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14282. "\r\n"
  14283. "text1"
  14284. "\r\n--zzzz--",
  14285. "\r\nthis epilogue must be ignored\r\n");
  14286. }
  14287. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  14288. // The initial boundary may be preceded by a preamble of any length and may
  14289. // straddle a read boundary. Discarding data while waiting for it must not
  14290. // throw away a partial boundary sitting at the end of the buffer.
  14291. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  14292. "zz\r\n"
  14293. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14294. "\r\n"
  14295. "text1"
  14296. "\r\n--zzzz--\r\n");
  14297. }
  14298. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  14299. // The received boundary was only checked for being non-empty, so it could be
  14300. // as long as a header is allowed to be. The parser scans the body for
  14301. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  14302. // costs a nearly full comparison at nearly every position, making the
  14303. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  14304. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  14305. Server svr;
  14306. svr.Post("/post", [](const Request &req, Response &res) {
  14307. EXPECT_EQ(1u, req.form.fields.size());
  14308. EXPECT_EQ("text1", req.form.get_field("text1"));
  14309. res.set_content("ok", "text/plain");
  14310. });
  14311. auto port = svr.bind_to_any_port(HOST);
  14312. thread t = thread([&] { svr.listen_after_bind(); });
  14313. auto se = detail::scope_exit([&] {
  14314. svr.stop();
  14315. t.join();
  14316. ASSERT_FALSE(svr.is_running());
  14317. });
  14318. svr.wait_until_ready();
  14319. Client cli(HOST, port);
  14320. auto post_with_boundary_of_length = [&](size_t len) {
  14321. const std::string boundary(len, 'a');
  14322. const std::string body =
  14323. "--" + boundary +
  14324. "\r\n"
  14325. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14326. "\r\n"
  14327. "text1"
  14328. "\r\n--" +
  14329. boundary + "--\r\n";
  14330. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  14331. };
  14332. auto res = post_with_boundary_of_length(70);
  14333. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14334. EXPECT_EQ(StatusCode::OK_200, res->status);
  14335. res = post_with_boundary_of_length(71);
  14336. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14337. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14338. }
  14339. TEST(MakeFileBodyTest, Basic) {
  14340. const std::string file_content(4096, 'Z');
  14341. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  14342. {
  14343. std::ofstream ofs(tmp_path, std::ios::binary);
  14344. ofs.write(file_content.data(),
  14345. static_cast<std::streamsize>(file_content.size()));
  14346. }
  14347. auto handled = false;
  14348. Server svr;
  14349. svr.Post("/upload", [&](const Request &req, Response &res) {
  14350. EXPECT_EQ(file_content, req.body);
  14351. handled = true;
  14352. res.status = StatusCode::OK_200;
  14353. });
  14354. auto port = svr.bind_to_any_port(HOST);
  14355. auto t = thread([&] { svr.listen_after_bind(); });
  14356. auto se = detail::scope_exit([&] {
  14357. svr.stop();
  14358. t.join();
  14359. ASSERT_FALSE(svr.is_running());
  14360. ASSERT_TRUE(handled);
  14361. std::remove(tmp_path.c_str());
  14362. });
  14363. svr.wait_until_ready();
  14364. auto fb = make_file_body(tmp_path);
  14365. ASSERT_GT(fb.first, 0u);
  14366. Client cli(HOST, port);
  14367. auto res =
  14368. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  14369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14370. EXPECT_EQ(StatusCode::OK_200, res->status);
  14371. }
  14372. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  14373. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  14374. {
  14375. std::ofstream ofs(path, std::ios::binary);
  14376. const std::string content(100, 'A');
  14377. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  14378. }
  14379. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  14380. auto body = make_file_body(path);
  14381. ASSERT_EQ(100u, body.first);
  14382. ASSERT_TRUE(static_cast<bool>(body.second));
  14383. // Rewritten shorter after its length was measured - and, on a server, after
  14384. // that length has already gone out as Content-Length.
  14385. {
  14386. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  14387. const std::string content(10, 'A');
  14388. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  14389. }
  14390. std::string written;
  14391. DataSink sink;
  14392. sink.write = [&](const char *d, size_t l) {
  14393. written.append(d, l);
  14394. return true;
  14395. };
  14396. // The provider has to report failure. write_content_with_progress() advances
  14397. // its offset only by what was written, so a provider that returns true
  14398. // without completing the length it promised is called again straight away,
  14399. // and again.
  14400. EXPECT_FALSE(body.second(0, body.first, sink));
  14401. EXPECT_EQ(std::string(10, 'A'), written);
  14402. }
  14403. TEST(MakeFileBodyTest, WholeFileIsSent) {
  14404. const std::string path = "./httplib_test_make_file_body_whole.bin";
  14405. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  14406. {
  14407. std::ofstream ofs(path, std::ios::binary);
  14408. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  14409. }
  14410. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  14411. auto body = make_file_body(path);
  14412. ASSERT_EQ(content.size(), body.first);
  14413. ASSERT_TRUE(static_cast<bool>(body.second));
  14414. std::string written;
  14415. DataSink sink;
  14416. sink.write = [&](const char *d, size_t l) {
  14417. written.append(d, l);
  14418. return true;
  14419. };
  14420. EXPECT_TRUE(body.second(0, body.first, sink));
  14421. EXPECT_EQ(content, written);
  14422. }
  14423. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  14424. static constexpr unsigned int number_of_tasks{1000000};
  14425. std::atomic_uint count{0};
  14426. std::unique_ptr<TaskQueue> task_queue{
  14427. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  14428. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  14429. auto queued = task_queue->enqueue(
  14430. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  14431. EXPECT_TRUE(queued);
  14432. }
  14433. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14434. task_queue->shutdown();
  14435. #else
  14436. EXPECT_NO_THROW(task_queue->shutdown());
  14437. #endif
  14438. EXPECT_EQ(number_of_tasks, count.load());
  14439. }
  14440. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  14441. static constexpr unsigned int number_of_tasks{1000000};
  14442. static constexpr unsigned int qlimit{2};
  14443. unsigned int queued_count{0};
  14444. std::atomic_uint count{0};
  14445. std::unique_ptr<TaskQueue> task_queue{
  14446. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  14447. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  14448. if (task_queue->enqueue(
  14449. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  14450. queued_count++;
  14451. }
  14452. }
  14453. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14454. task_queue->shutdown();
  14455. #else
  14456. EXPECT_NO_THROW(task_queue->shutdown());
  14457. #endif
  14458. EXPECT_EQ(queued_count, count.load());
  14459. EXPECT_TRUE(queued_count <= number_of_tasks);
  14460. EXPECT_TRUE(queued_count >= qlimit);
  14461. }
  14462. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  14463. // Use a short idle timeout so a dynamic thread spawns, times out and
  14464. // exits during the test, and the pool keeps working afterwards.
  14465. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  14466. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  14467. /*idle_timeout_sec=*/1}};
  14468. std::atomic_uint count{0};
  14469. std::condition_variable cv;
  14470. std::mutex mtx;
  14471. bool release = false;
  14472. // Block the base thread so the second task spawns a dynamic thread.
  14473. EXPECT_TRUE(task_queue->enqueue([&] {
  14474. std::unique_lock<std::mutex> lock(mtx);
  14475. while (!release) {
  14476. cv.wait(lock);
  14477. }
  14478. count++;
  14479. }));
  14480. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  14481. // Let the dynamic thread finish its task and exceed the idle timeout.
  14482. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  14483. {
  14484. std::unique_lock<std::mutex> lock(mtx);
  14485. release = true;
  14486. }
  14487. cv.notify_all();
  14488. // The pool must still accept and run tasks after the dynamic thread exited.
  14489. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  14490. task_queue->shutdown();
  14491. EXPECT_EQ(3u, count.load());
  14492. }
  14493. TEST(TaskQueueTest, MaxQueuedRequests) {
  14494. static constexpr unsigned int qlimit{3};
  14495. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  14496. std::condition_variable sem_cv;
  14497. std::mutex sem_mtx;
  14498. int credits = 0;
  14499. bool queued;
  14500. /* Fill up the queue with tasks that will block until we give them credits to
  14501. * complete. */
  14502. for (unsigned int n = 0; n <= qlimit;) {
  14503. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  14504. std::unique_lock<std::mutex> lock(sem_mtx);
  14505. while (credits <= 0) {
  14506. sem_cv.wait(lock);
  14507. }
  14508. /* Consume the credit and signal the test code if they are all gone. */
  14509. if (--credits == 0) { sem_cv.notify_one(); }
  14510. });
  14511. if (n < qlimit) {
  14512. /* The first qlimit enqueues must succeed. */
  14513. EXPECT_TRUE(queued);
  14514. } else {
  14515. /* The last one will succeed only when the worker thread
  14516. * starts and dequeues the first blocking task. Although
  14517. * not necessary for the correctness of this test, we sleep for
  14518. * a short while to avoid busy waiting. */
  14519. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  14520. }
  14521. if (queued) { n++; }
  14522. }
  14523. /* Further enqueues must fail since the queue is full. */
  14524. for (auto i = 0; i < 4; i++) {
  14525. queued = task_queue->enqueue([] {});
  14526. EXPECT_FALSE(queued);
  14527. }
  14528. /* Give the credits to allow the previous tasks to complete. */
  14529. {
  14530. std::unique_lock<std::mutex> lock(sem_mtx);
  14531. credits += qlimit + 1;
  14532. }
  14533. sem_cv.notify_all();
  14534. /* Wait for all the credits to be consumed. */
  14535. {
  14536. std::unique_lock<std::mutex> lock(sem_mtx);
  14537. while (credits > 0) {
  14538. sem_cv.wait(lock);
  14539. }
  14540. }
  14541. /* Check that we are able again to enqueue at least qlimit tasks. */
  14542. for (unsigned int i = 0; i < qlimit; i++) {
  14543. queued = task_queue->enqueue([] {});
  14544. EXPECT_TRUE(queued);
  14545. }
  14546. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14547. task_queue->shutdown();
  14548. #else
  14549. EXPECT_NO_THROW(task_queue->shutdown());
  14550. #endif
  14551. }
  14552. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  14553. Server svr;
  14554. svr.Get("/", [](const Request & /*req*/, Response &res) {
  14555. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  14556. });
  14557. svr.Get("/hello", [](const Request &req, Response &res) {
  14558. res.set_content(req.get_param_value("key"), "text/plain");
  14559. });
  14560. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14561. auto se = detail::scope_exit([&] {
  14562. svr.stop();
  14563. thread.join();
  14564. ASSERT_FALSE(svr.is_running());
  14565. });
  14566. svr.wait_until_ready();
  14567. {
  14568. Client cli(HOST, PORT);
  14569. cli.set_follow_location(true);
  14570. auto res = cli.Get("/");
  14571. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14572. EXPECT_EQ(StatusCode::OK_200, res->status);
  14573. EXPECT_EQ("val&key2=val2", res->body);
  14574. }
  14575. }
  14576. #endif
  14577. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  14578. Server svr;
  14579. svr.Get("/", [](const Request & /*req*/, Response &res) {
  14580. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  14581. });
  14582. svr.Get("/hello", [](const Request &req, Response &res) {
  14583. res.set_content(req.get_param_value("key"), "text/plain");
  14584. });
  14585. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14586. auto se = detail::scope_exit([&] {
  14587. svr.stop();
  14588. thread.join();
  14589. ASSERT_FALSE(svr.is_running());
  14590. });
  14591. svr.wait_until_ready();
  14592. {
  14593. Client cli(HOST, PORT);
  14594. cli.set_follow_location(true);
  14595. auto res = cli.Get("/");
  14596. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14597. EXPECT_EQ(StatusCode::OK_200, res->status);
  14598. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  14599. }
  14600. }
  14601. TEST(RedirectTest, RedirectWithPlusInPath) {
  14602. Server svr;
  14603. svr.Get("/", [](const Request & /*req*/, Response &res) {
  14604. res.set_redirect("/a+b");
  14605. });
  14606. // Route pattern uses regex; escape + as \\+
  14607. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  14608. res.set_content(req.path, "text/plain");
  14609. });
  14610. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14611. auto se = detail::scope_exit([&] {
  14612. svr.stop();
  14613. thread.join();
  14614. ASSERT_FALSE(svr.is_running());
  14615. });
  14616. svr.wait_until_ready();
  14617. {
  14618. Client cli(HOST, PORT);
  14619. cli.set_follow_location(true);
  14620. auto res = cli.Get("/");
  14621. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14622. EXPECT_EQ(StatusCode::OK_200, res->status);
  14623. EXPECT_EQ("/a+b", res->body);
  14624. }
  14625. }
  14626. TEST(RedirectTest, ResolveRelativeLocation) {
  14627. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  14628. const std::vector<std::pair<std::string, std::string>> cases = {
  14629. {"g", "/b/c/g"},
  14630. {"./g", "/b/c/g"},
  14631. {"g/", "/b/c/g/"},
  14632. {"?y", "/b/c/d;p?y"},
  14633. {"g?y", "/b/c/g?y"},
  14634. {"#s", "/b/c/d;p?q#s"},
  14635. {"g#s", "/b/c/g#s"},
  14636. {"g?y#s", "/b/c/g?y#s"},
  14637. {";x", "/b/c/;x"},
  14638. {"g;x", "/b/c/g;x"},
  14639. {".", "/b/c/"},
  14640. {"./", "/b/c/"},
  14641. {"..", "/b/"},
  14642. {"../", "/b/"},
  14643. {"../g", "/b/g"},
  14644. {"../..", "/"},
  14645. {"../../", "/"},
  14646. {"../../g", "/g"},
  14647. {"../../../g", "/g"},
  14648. {"g.", "/b/c/g."},
  14649. {".g", "/b/c/.g"},
  14650. {"g..", "/b/c/g.."},
  14651. {"..g", "/b/c/..g"},
  14652. {"./../g", "/b/g"},
  14653. {"./g/.", "/b/c/g/"},
  14654. {"g/./h", "/b/c/g/h"},
  14655. {"g/../h", "/b/c/h"},
  14656. {"g;x=1/./y", "/b/c/g;x=1/y"},
  14657. {"g;x=1/../y", "/b/c/y"},
  14658. {"g?y/./x", "/b/c/g?y/./x"},
  14659. {"g#s/../x", "/b/c/g#s/../x"},
  14660. // Not relative-path references, so left for parse_url.
  14661. {"/g", "/g"},
  14662. {"//g", "//g"},
  14663. {"http://g/x", "http://g/x"},
  14664. {"g:h", "g:h"},
  14665. };
  14666. for (const auto &c : cases) {
  14667. EXPECT_EQ(c.second,
  14668. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  14669. << c.first;
  14670. }
  14671. }
  14672. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  14673. Server svr;
  14674. svr.Get("/dir/page", [](const Request &req, Response &res) {
  14675. res.set_redirect(req.get_param_value("to"));
  14676. });
  14677. svr.Get("/dir/next", [](const Request &req, Response &res) {
  14678. res.set_content(req.target, "text/plain");
  14679. });
  14680. svr.Get("/other", [](const Request &req, Response &res) {
  14681. res.set_content(req.target, "text/plain");
  14682. });
  14683. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14684. auto se = detail::scope_exit([&] {
  14685. svr.stop();
  14686. thread.join();
  14687. ASSERT_FALSE(svr.is_running());
  14688. });
  14689. svr.wait_until_ready();
  14690. const std::vector<std::pair<std::string, std::string>> cases = {
  14691. {"next", "/dir/next"},
  14692. {"./next?x=1", "/dir/next?x=1"},
  14693. {"../other", "/other"},
  14694. };
  14695. for (const auto &c : cases) {
  14696. Client cli(HOST, PORT);
  14697. cli.set_follow_location(true);
  14698. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  14699. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  14700. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  14701. EXPECT_EQ(c.second, res->body) << c.first;
  14702. }
  14703. }
  14704. #ifdef CPPHTTPLIB_SSL_ENABLED
  14705. TEST(RedirectTest, Issue2185_Online) {
  14706. SSLClient client("github.com");
  14707. client.set_follow_location(true);
  14708. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  14709. "Coollab-Windows.zip");
  14710. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14711. EXPECT_EQ(StatusCode::OK_200, res->status);
  14712. EXPECT_EQ(9920427U, res->body.size());
  14713. }
  14714. #endif
  14715. TEST(VulnerabilityTest, CRLFInjection) {
  14716. Server svr;
  14717. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  14718. res.set_content("Hello 1", "text/plain");
  14719. });
  14720. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  14721. res.set_content("Hello 2", "text/plain");
  14722. });
  14723. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  14724. res.set_content("Hello 3", "text/plain");
  14725. });
  14726. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  14727. res.set_content("Hello 4", "text/plain");
  14728. });
  14729. svr.set_logger([](const Request &req, const Response & /*res*/) {
  14730. for (const auto &x : req.headers) {
  14731. auto key = x.first;
  14732. EXPECT_STRNE("evil", key.c_str());
  14733. }
  14734. });
  14735. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14736. auto se = detail::scope_exit([&] {
  14737. svr.stop();
  14738. thread.join();
  14739. ASSERT_FALSE(svr.is_running());
  14740. });
  14741. svr.wait_until_ready();
  14742. {
  14743. Client cli(HOST, PORT);
  14744. cli.Post("/test1", "A=B",
  14745. "application/x-www-form-urlencoded\r\nevil: hello1");
  14746. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  14747. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  14748. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  14749. }
  14750. }
  14751. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  14752. auto server_thread = std::thread([] {
  14753. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  14754. default_socket_options(srv);
  14755. sockaddr_in addr{};
  14756. addr.sin_family = AF_INET;
  14757. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  14758. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  14759. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  14760. ::listen(srv, 1);
  14761. sockaddr_in cli_addr{};
  14762. socklen_t cli_len = sizeof(cli_addr);
  14763. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  14764. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  14765. std::string buf_all;
  14766. char buf[2048];
  14767. ssize_t n;
  14768. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  14769. buf_all.append(buf, static_cast<size_t>(n));
  14770. size_t pos;
  14771. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  14772. auto request_block = buf_all.substr(0, pos + 4); // include separator
  14773. auto e = request_block.find("\r\n");
  14774. if (e != std::string::npos) {
  14775. auto request_line = request_block.substr(0, e);
  14776. std::string msg =
  14777. "CRLF injection detected in request line: '" + request_line + "'";
  14778. EXPECT_FALSE(true) << msg;
  14779. }
  14780. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  14781. ::send(cli,
  14782. #ifdef _WIN32
  14783. static_cast<const char *>(resp.c_str()),
  14784. static_cast<int>(resp.size()),
  14785. #else
  14786. resp.c_str(), resp.size(),
  14787. #endif
  14788. 0);
  14789. buf_all.erase(0, pos + 4);
  14790. }
  14791. }
  14792. detail::close_socket(cli);
  14793. detail::close_socket(srv);
  14794. });
  14795. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  14796. auto cli = Client("127.0.0.1", PORT + 1);
  14797. auto headers = Headers{
  14798. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  14799. {"Connection", "keep-alive"}};
  14800. auto res = cli.Get("/hi", headers);
  14801. EXPECT_FALSE(res);
  14802. EXPECT_EQ(Error::InvalidHeaders, res.error());
  14803. server_thread.join();
  14804. }
  14805. // A request rejected before any byte reaches the socket must fail right away
  14806. // instead of waiting for a response the server will never send.
  14807. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  14808. // The kernel completes the TCP handshake from the listen backlog, so the
  14809. // client connects, but nothing ever reads, responds or closes.
  14810. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  14811. default_socket_options(srv);
  14812. sockaddr_in addr{};
  14813. addr.sin_family = AF_INET;
  14814. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  14815. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  14816. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  14817. ASSERT_EQ(0, ::listen(srv, 8));
  14818. auto cli = Client("127.0.0.1", PORT + 1);
  14819. cli.set_read_timeout(10, 0);
  14820. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  14821. return std::chrono::duration_cast<std::chrono::milliseconds>(
  14822. std::chrono::steady_clock::now() - start)
  14823. .count();
  14824. };
  14825. {
  14826. Request req;
  14827. req.method = "GE T";
  14828. req.path = "/";
  14829. auto start = std::chrono::steady_clock::now();
  14830. auto res = cli.send(req);
  14831. EXPECT_FALSE(res);
  14832. EXPECT_EQ(Error::Write, res.error());
  14833. EXPECT_LT(elapsed_ms(start), 1000);
  14834. }
  14835. {
  14836. auto start = std::chrono::steady_clock::now();
  14837. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  14838. EXPECT_FALSE(res);
  14839. EXPECT_EQ(Error::InvalidHeaders, res.error());
  14840. EXPECT_LT(elapsed_ms(start), 1000);
  14841. }
  14842. EXPECT_FALSE(cli.is_socket_open());
  14843. detail::close_socket(srv);
  14844. }
  14845. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  14846. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  14847. default_socket_options(srv);
  14848. sockaddr_in addr{};
  14849. addr.sin_family = AF_INET;
  14850. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  14851. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  14852. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  14853. ASSERT_EQ(0, ::listen(srv, 1));
  14854. std::string received;
  14855. auto server_thread = std::thread([&] {
  14856. auto sock = ::accept(srv, nullptr, nullptr);
  14857. if (sock == INVALID_SOCKET) { return; }
  14858. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  14859. char buf[2048];
  14860. ssize_t n;
  14861. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  14862. received.append(buf, static_cast<size_t>(n));
  14863. }
  14864. detail::close_socket(sock);
  14865. });
  14866. {
  14867. auto cli = Client("127.0.0.1", PORT + 1);
  14868. // "Z" sorts after the default headers, so writing straight to the socket
  14869. // would have sent the request line and those headers before the rejection.
  14870. auto handle =
  14871. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  14872. EXPECT_FALSE(handle.is_valid());
  14873. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  14874. }
  14875. server_thread.join();
  14876. detail::close_socket(srv);
  14877. EXPECT_TRUE(received.empty()) << received;
  14878. }
  14879. TEST(PathParamsTest, StaticMatch) {
  14880. const auto pattern = "/users/all";
  14881. detail::PathParamsMatcher matcher(pattern);
  14882. Request request;
  14883. request.path = "/users/all";
  14884. ASSERT_TRUE(matcher.match(request));
  14885. std::unordered_map<std::string, std::string> expected_params = {};
  14886. EXPECT_EQ(request.path_params, expected_params);
  14887. }
  14888. TEST(PathParamsTest, StaticMismatch) {
  14889. const auto pattern = "/users/all";
  14890. detail::PathParamsMatcher matcher(pattern);
  14891. Request request;
  14892. request.path = "/users/1";
  14893. ASSERT_FALSE(matcher.match(request));
  14894. }
  14895. TEST(PathParamsTest, SingleParamInTheMiddle) {
  14896. const auto pattern = "/users/:id/subscriptions";
  14897. detail::PathParamsMatcher matcher(pattern);
  14898. Request request;
  14899. request.path = "/users/42/subscriptions";
  14900. ASSERT_TRUE(matcher.match(request));
  14901. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  14902. EXPECT_EQ(request.path_params, expected_params);
  14903. }
  14904. TEST(PathParamsTest, SingleParamInTheEnd) {
  14905. const auto pattern = "/users/:id";
  14906. detail::PathParamsMatcher matcher(pattern);
  14907. Request request;
  14908. request.path = "/users/24";
  14909. ASSERT_TRUE(matcher.match(request));
  14910. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  14911. EXPECT_EQ(request.path_params, expected_params);
  14912. }
  14913. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  14914. const auto pattern = "/users/:id/";
  14915. detail::PathParamsMatcher matcher(pattern);
  14916. Request request;
  14917. request.path = "/users/42/";
  14918. ASSERT_TRUE(matcher.match(request));
  14919. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  14920. EXPECT_EQ(request.path_params, expected_params);
  14921. }
  14922. TEST(PathParamsTest, EmptyParam) {
  14923. const auto pattern = "/users/:id/";
  14924. detail::PathParamsMatcher matcher(pattern);
  14925. Request request;
  14926. request.path = "/users//";
  14927. ASSERT_TRUE(matcher.match(request));
  14928. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  14929. EXPECT_EQ(request.path_params, expected_params);
  14930. }
  14931. TEST(PathParamsTest, FragmentMismatch) {
  14932. const auto pattern = "/users/:id/";
  14933. detail::PathParamsMatcher matcher(pattern);
  14934. Request request;
  14935. request.path = "/admins/24/";
  14936. ASSERT_FALSE(matcher.match(request));
  14937. }
  14938. TEST(PathParamsTest, ExtraFragments) {
  14939. const auto pattern = "/users/:id";
  14940. detail::PathParamsMatcher matcher(pattern);
  14941. Request request;
  14942. request.path = "/users/42/subscriptions";
  14943. ASSERT_FALSE(matcher.match(request));
  14944. }
  14945. TEST(PathParamsTest, MissingTrailingParam) {
  14946. const auto pattern = "/users/:id";
  14947. detail::PathParamsMatcher matcher(pattern);
  14948. Request request;
  14949. request.path = "/users";
  14950. ASSERT_FALSE(matcher.match(request));
  14951. }
  14952. TEST(PathParamsTest, MissingParamInTheMiddle) {
  14953. const auto pattern = "/users/:id/subscriptions";
  14954. detail::PathParamsMatcher matcher(pattern);
  14955. Request request;
  14956. request.path = "/users/subscriptions";
  14957. ASSERT_FALSE(matcher.match(request));
  14958. }
  14959. TEST(PathParamsTest, MultipleParams) {
  14960. const auto pattern = "/users/:userid/subscriptions/:subid";
  14961. detail::PathParamsMatcher matcher(pattern);
  14962. Request request;
  14963. request.path = "/users/42/subscriptions/2";
  14964. ASSERT_TRUE(matcher.match(request));
  14965. std::unordered_map<std::string, std::string> expected_params = {
  14966. {"userid", "42"}, {"subid", "2"}};
  14967. EXPECT_EQ(request.path_params, expected_params);
  14968. }
  14969. TEST(PathParamsTest, SequenceOfParams) {
  14970. const auto pattern = "/values/:x/:y/:z";
  14971. detail::PathParamsMatcher matcher(pattern);
  14972. Request request;
  14973. request.path = "/values/1/2/3";
  14974. ASSERT_TRUE(matcher.match(request));
  14975. std::unordered_map<std::string, std::string> expected_params = {
  14976. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  14977. EXPECT_EQ(request.path_params, expected_params);
  14978. }
  14979. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  14980. const auto pattern = "/prefix:suffix";
  14981. detail::PathParamsMatcher matcher(pattern);
  14982. Request request;
  14983. request.path = "/prefix:suffix";
  14984. ASSERT_TRUE(matcher.match(request));
  14985. const std::unordered_map<std::string, std::string> expected_params = {};
  14986. EXPECT_EQ(request.path_params, expected_params);
  14987. }
  14988. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  14989. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  14990. // calling thread's stack on a long enough path for a quantified pattern;
  14991. // RegexMatcher must refuse to run regex matching on paths beyond
  14992. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  14993. detail::RegexMatcher matcher("/files/(.*)");
  14994. Request within_limit;
  14995. within_limit.path = "/files/" + std::string(10, 'A');
  14996. EXPECT_TRUE(matcher.match(within_limit));
  14997. Request over_limit;
  14998. over_limit.path =
  14999. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  15000. EXPECT_FALSE(matcher.match(over_limit));
  15001. }
  15002. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  15003. Server svr;
  15004. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  15005. res.set_content("ok", "text/plain");
  15006. });
  15007. auto port = svr.bind_to_any_port(HOST);
  15008. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15009. auto se = detail::scope_exit([&] {
  15010. svr.stop();
  15011. thread.join();
  15012. ASSERT_FALSE(svr.is_running());
  15013. });
  15014. svr.wait_until_ready();
  15015. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  15016. // request URI limit; this used to be able to crash the process.
  15017. std::string path =
  15018. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  15019. std::string req = "GET " + path +
  15020. " HTTP/1.1\r\n"
  15021. "Host: " +
  15022. std::string(HOST) + ":" + std::to_string(port) +
  15023. "\r\n"
  15024. "Connection: close\r\n"
  15025. "\r\n";
  15026. std::string response;
  15027. ASSERT_TRUE(send_request(5, req, &response, port));
  15028. EXPECT_NE(std::string::npos, response.find("404"));
  15029. }
  15030. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  15031. Server svr;
  15032. auto handler = [](const Request & /*req*/, Response &res) {
  15033. res.set_content("hit", "text/plain");
  15034. };
  15035. // No regex metacharacter, so this one is compared literally
  15036. svr.Get("/literal/route", handler);
  15037. // '.' is a regex metacharacter, so this one must keep regex semantics
  15038. svr.Get("/a.c", handler);
  15039. auto port = svr.bind_to_any_port(HOST);
  15040. std::thread t([&]() { svr.listen_after_bind(); });
  15041. auto se = detail::scope_exit([&] {
  15042. svr.stop();
  15043. t.join();
  15044. ASSERT_FALSE(svr.is_running());
  15045. });
  15046. svr.wait_until_ready();
  15047. Client cli(HOST, port);
  15048. struct {
  15049. const char *path;
  15050. int status;
  15051. } cases[] = {
  15052. {"/literal/route", StatusCode::OK_200},
  15053. {"/literal/routes", StatusCode::NotFound_404},
  15054. {"/literal/rout", StatusCode::NotFound_404},
  15055. {"/abc", StatusCode::OK_200},
  15056. {"/a.c", StatusCode::OK_200},
  15057. };
  15058. for (const auto &x : cases) {
  15059. auto res = cli.Get(x.path);
  15060. ASSERT_TRUE(res) << x.path;
  15061. EXPECT_EQ(x.status, res->status) << x.path;
  15062. }
  15063. }
  15064. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  15065. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  15066. // from exhausting the stack, so it must only constrain routes that actually
  15067. // run a regular expression. A literal route is matched by comparison and
  15068. // stays usable at any length.
  15069. Server svr;
  15070. const std::string pattern =
  15071. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  15072. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  15073. res.set_content("hit", "text/plain");
  15074. });
  15075. auto port = svr.bind_to_any_port(HOST);
  15076. std::thread t([&]() { svr.listen_after_bind(); });
  15077. auto se = detail::scope_exit([&] {
  15078. svr.stop();
  15079. t.join();
  15080. ASSERT_FALSE(svr.is_running());
  15081. });
  15082. svr.wait_until_ready();
  15083. Client cli(HOST, port);
  15084. auto res = cli.Get(pattern);
  15085. ASSERT_TRUE(res);
  15086. EXPECT_EQ(StatusCode::OK_200, res->status);
  15087. }
  15088. TEST(ParseUrlTest, VariousPatterns) {
  15089. {
  15090. detail::UrlComponents uc;
  15091. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  15092. EXPECT_EQ("http", uc.scheme);
  15093. EXPECT_EQ("example.com", uc.host);
  15094. EXPECT_EQ("8080", uc.port);
  15095. EXPECT_EQ("/path", uc.path);
  15096. EXPECT_EQ("?q=1", uc.query);
  15097. }
  15098. {
  15099. detail::UrlComponents uc;
  15100. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  15101. EXPECT_EQ("https", uc.scheme);
  15102. EXPECT_EQ("example.com", uc.host);
  15103. EXPECT_TRUE(uc.port.empty());
  15104. EXPECT_EQ("/path", uc.path);
  15105. }
  15106. {
  15107. detail::UrlComponents uc;
  15108. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  15109. EXPECT_EQ("::1", uc.host);
  15110. EXPECT_EQ("8080", uc.port);
  15111. EXPECT_EQ("/path", uc.path);
  15112. }
  15113. {
  15114. detail::UrlComponents uc;
  15115. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  15116. }
  15117. {
  15118. // Bytes after the IPv6 literal must be a delimiter, not folded into
  15119. // the path while the connection still targets the bracketed host.
  15120. detail::UrlComponents uc;
  15121. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  15122. }
  15123. {
  15124. detail::UrlComponents uc;
  15125. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  15126. }
  15127. {
  15128. detail::UrlComponents uc;
  15129. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  15130. EXPECT_EQ("::1", uc.host);
  15131. EXPECT_TRUE(uc.port.empty());
  15132. EXPECT_EQ("/path", uc.path);
  15133. }
  15134. {
  15135. detail::UrlComponents uc;
  15136. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  15137. EXPECT_TRUE(uc.scheme.empty());
  15138. EXPECT_EQ("example.com", uc.host);
  15139. EXPECT_EQ("/path", uc.path);
  15140. EXPECT_EQ("?q=1", uc.query);
  15141. }
  15142. {
  15143. detail::UrlComponents uc;
  15144. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  15145. EXPECT_TRUE(uc.host.empty());
  15146. EXPECT_EQ("/path", uc.path);
  15147. EXPECT_EQ("?q=1", uc.query);
  15148. }
  15149. {
  15150. detail::UrlComponents uc;
  15151. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  15152. EXPECT_EQ("example.com", uc.host);
  15153. EXPECT_EQ("8080", uc.port);
  15154. }
  15155. {
  15156. // Unix socket path — must not be parsed as host
  15157. detail::UrlComponents uc;
  15158. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  15159. EXPECT_TRUE(uc.host.empty());
  15160. }
  15161. {
  15162. detail::UrlComponents uc;
  15163. ASSERT_TRUE(detail::parse_url("", uc));
  15164. EXPECT_TRUE(uc.host.empty());
  15165. EXPECT_TRUE(uc.path.empty());
  15166. }
  15167. {
  15168. detail::UrlComponents uc;
  15169. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  15170. }
  15171. {
  15172. detail::UrlComponents uc;
  15173. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  15174. }
  15175. {
  15176. // Accepted by parse_url; callers restrict to http/https
  15177. detail::UrlComponents uc;
  15178. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  15179. EXPECT_EQ("ftp", uc.scheme);
  15180. }
  15181. {
  15182. detail::UrlComponents uc;
  15183. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  15184. }
  15185. {
  15186. detail::UrlComponents uc;
  15187. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  15188. }
  15189. }
  15190. TEST(ParseUrlTest, FragmentHandling) {
  15191. {
  15192. detail::UrlComponents uc;
  15193. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  15194. EXPECT_EQ("/path", uc.path);
  15195. EXPECT_TRUE(uc.query.empty());
  15196. }
  15197. {
  15198. detail::UrlComponents uc;
  15199. ASSERT_TRUE(detail::parse_url("#frag", uc));
  15200. EXPECT_TRUE(uc.path.empty());
  15201. EXPECT_TRUE(uc.query.empty());
  15202. }
  15203. }
  15204. TEST(ParseUrlTest, UserinfoHandling) {
  15205. // Userinfo with @ but no colon — host includes @
  15206. detail::UrlComponents uc;
  15207. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  15208. EXPECT_EQ("user@host.com", uc.host);
  15209. EXPECT_EQ("/path", uc.path);
  15210. }
  15211. TEST(ParseUrlTest, IPv6EdgeCases) {
  15212. {
  15213. detail::UrlComponents uc;
  15214. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  15215. EXPECT_TRUE(uc.scheme.empty());
  15216. EXPECT_EQ("::1", uc.host);
  15217. EXPECT_EQ("8080", uc.port);
  15218. }
  15219. {
  15220. // Zone ID '%25' is not in [a-fA-F0-9:]
  15221. detail::UrlComponents uc;
  15222. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  15223. }
  15224. }
  15225. TEST(ParseUrlTest, SchemeEdgeCases) {
  15226. {
  15227. detail::UrlComponents uc;
  15228. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  15229. }
  15230. {
  15231. detail::UrlComponents uc;
  15232. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  15233. }
  15234. {
  15235. detail::UrlComponents uc;
  15236. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  15237. }
  15238. }
  15239. TEST(ParseUrlTest, PortEdgeCases) {
  15240. {
  15241. detail::UrlComponents uc;
  15242. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  15243. EXPECT_TRUE(uc.port.empty());
  15244. EXPECT_EQ("/path", uc.path);
  15245. }
  15246. {
  15247. // parse_url accepts any port string; validation is done by parse_port
  15248. detail::UrlComponents uc;
  15249. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  15250. EXPECT_EQ("abc", uc.port);
  15251. }
  15252. }
  15253. TEST(ParseUrlTest, WebSocketPatterns) {
  15254. {
  15255. detail::UrlComponents uc;
  15256. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  15257. EXPECT_EQ("ws", uc.scheme);
  15258. EXPECT_EQ("echo.example.com", uc.host);
  15259. EXPECT_EQ("8080", uc.port);
  15260. EXPECT_EQ("/ws", uc.path);
  15261. }
  15262. {
  15263. detail::UrlComponents uc;
  15264. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  15265. EXPECT_EQ("wss", uc.scheme);
  15266. EXPECT_EQ("echo.example.com", uc.host);
  15267. EXPECT_TRUE(uc.port.empty());
  15268. EXPECT_EQ("/ws", uc.path);
  15269. }
  15270. }
  15271. TEST(ParseUrlTest, QueryOnly) {
  15272. detail::UrlComponents uc;
  15273. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  15274. EXPECT_TRUE(uc.host.empty());
  15275. EXPECT_TRUE(uc.path.empty());
  15276. EXPECT_EQ("?q=1&r=2", uc.query);
  15277. }
  15278. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  15279. detail::UrlComponents uc;
  15280. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  15281. EXPECT_TRUE(uc.scheme.empty());
  15282. EXPECT_EQ("example.com", uc.host);
  15283. EXPECT_EQ("443", uc.port);
  15284. EXPECT_EQ("/path", uc.path);
  15285. }
  15286. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  15287. // If ipv6 regex working, regex match codepath is taken.
  15288. // else port will default to 80 in Client impl
  15289. int clientImplMagicPort = 80;
  15290. int port = 4321;
  15291. // above ports must be different to avoid false negative
  15292. EXPECT_NE(clientImplMagicPort, port);
  15293. std::string ipV6TestURL = "http://[ff06::c3]";
  15294. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  15295. CLIENT_PRIVATE_KEY_FILE);
  15296. EXPECT_EQ(cli.port(), port);
  15297. }
  15298. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  15299. auto file_path = "./www/dir/index.html";
  15300. auto dir_path = "./www/dir";
  15301. detail::FileStat stat_file(file_path);
  15302. EXPECT_TRUE(stat_file.is_file());
  15303. EXPECT_FALSE(stat_file.is_dir());
  15304. detail::FileStat stat_dir(dir_path);
  15305. EXPECT_FALSE(stat_dir.is_file());
  15306. EXPECT_TRUE(stat_dir.is_dir());
  15307. }
  15308. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  15309. // IPv4 with default HTTP port (80)
  15310. EXPECT_EQ("example.com",
  15311. detail::make_host_and_port_string("example.com", 80, false));
  15312. // IPv4 with default HTTPS port (443)
  15313. EXPECT_EQ("example.com",
  15314. detail::make_host_and_port_string("example.com", 443, true));
  15315. // IPv4 with non-default HTTP port
  15316. EXPECT_EQ("example.com:8080",
  15317. detail::make_host_and_port_string("example.com", 8080, false));
  15318. // IPv4 with non-default HTTPS port
  15319. EXPECT_EQ("example.com:8443",
  15320. detail::make_host_and_port_string("example.com", 8443, true));
  15321. // IPv6 with default HTTP port (80)
  15322. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  15323. // IPv6 with default HTTPS port (443)
  15324. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  15325. // IPv6 with non-default HTTP port
  15326. EXPECT_EQ("[::1]:8080",
  15327. detail::make_host_and_port_string("::1", 8080, false));
  15328. // IPv6 with non-default HTTPS port
  15329. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  15330. // IPv6 full address with default port
  15331. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  15332. detail::make_host_and_port_string(
  15333. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  15334. // IPv6 full address with non-default port
  15335. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  15336. detail::make_host_and_port_string(
  15337. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  15338. // IPv6 localhost with non-default port
  15339. EXPECT_EQ("[::1]:3000",
  15340. detail::make_host_and_port_string("::1", 3000, false));
  15341. // IPv6 with zone ID (link-local address) with default port
  15342. EXPECT_EQ("[fe80::1%eth0]",
  15343. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  15344. // IPv6 with zone ID (link-local address) with non-default port
  15345. EXPECT_EQ("[fe80::1%eth0]:8080",
  15346. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  15347. // Edge case: Port 443 with is_ssl=false (should add port)
  15348. EXPECT_EQ("example.com:443",
  15349. detail::make_host_and_port_string("example.com", 443, false));
  15350. // Edge case: Port 80 with is_ssl=true (should add port)
  15351. EXPECT_EQ("example.com:80",
  15352. detail::make_host_and_port_string("example.com", 80, true));
  15353. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  15354. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  15355. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  15356. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  15357. // Security fix: Already bracketed IPv6 should not get double brackets
  15358. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  15359. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  15360. EXPECT_EQ("[::1]:8080",
  15361. detail::make_host_and_port_string("[::1]", 8080, false));
  15362. EXPECT_EQ("[2001:db8::1]:8080",
  15363. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  15364. EXPECT_EQ("[fe80::1%eth0]",
  15365. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  15366. EXPECT_EQ("[fe80::1%eth0]:8080",
  15367. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  15368. // Edge case: Empty host (should return as-is)
  15369. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  15370. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  15371. // This is a known limitation but shouldn't crash
  15372. EXPECT_EQ("[host:name]",
  15373. detail::make_host_and_port_string("host:name", 80, false));
  15374. // Port number edge cases (no validation, but should not crash)
  15375. EXPECT_EQ("example.com:0",
  15376. detail::make_host_and_port_string("example.com", 0, false));
  15377. EXPECT_EQ("example.com:-1",
  15378. detail::make_host_and_port_string("example.com", -1, false));
  15379. EXPECT_EQ("example.com:65535",
  15380. detail::make_host_and_port_string("example.com", 65535, false));
  15381. EXPECT_EQ("example.com:65536",
  15382. detail::make_host_and_port_string("example.com", 65536, false));
  15383. }
  15384. #ifdef CPPHTTPLIB_SSL_ENABLED
  15385. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  15386. httplib::SSLClient cli("roblox.com", 443);
  15387. cli.set_follow_location(true);
  15388. auto res = cli.Get("/");
  15389. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15390. EXPECT_EQ(StatusCode::OK_200, res->status);
  15391. }
  15392. #endif
  15393. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  15394. Server svr;
  15395. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  15396. EXPECT_EQ(res.status, 400);
  15397. });
  15398. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15399. auto se = detail::scope_exit([&] {
  15400. svr.stop();
  15401. thread.join();
  15402. ASSERT_FALSE(svr.is_running());
  15403. });
  15404. svr.wait_until_ready();
  15405. Client cli(HOST, PORT);
  15406. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  15407. }
  15408. TEST(InvalidHeaderCharsTest, is_field_name) {
  15409. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  15410. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  15411. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  15412. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  15413. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  15414. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  15415. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  15416. EXPECT_FALSE(detail::fields::is_field_name(""));
  15417. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  15418. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  15419. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  15420. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  15421. }
  15422. TEST(InvalidHeaderCharsTest, is_field_value) {
  15423. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  15424. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  15425. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  15426. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  15427. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  15428. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  15429. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  15430. EXPECT_TRUE(detail::fields::is_field_value(""));
  15431. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  15432. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  15433. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  15434. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  15435. EXPECT_TRUE(detail::fields::is_field_value("0"));
  15436. }
  15437. TEST(InvalidHeaderCharsTest, OnServer) {
  15438. Server svr;
  15439. svr.Get("/test_name", [&](const Request &req, Response &res) {
  15440. std::string header = "Not Set";
  15441. if (req.has_param("header")) { header = req.get_param_value("header"); }
  15442. res.set_header(header, "value");
  15443. res.set_content("Page Content Page Content", "text/plain");
  15444. });
  15445. svr.Get("/test_value", [&](const Request &req, Response &res) {
  15446. std::string header = "Not Set";
  15447. if (req.has_param("header")) { header = req.get_param_value("header"); }
  15448. res.set_header("X-Test", header);
  15449. res.set_content("Page Content Page Content", "text/plain");
  15450. });
  15451. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15452. auto se = detail::scope_exit([&] {
  15453. svr.stop();
  15454. thread.join();
  15455. ASSERT_FALSE(svr.is_running());
  15456. });
  15457. svr.wait_until_ready();
  15458. Client cli(HOST, PORT);
  15459. {
  15460. auto res = cli.Get(
  15461. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  15462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15463. EXPECT_EQ("Page Content Page Content", res->body);
  15464. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  15465. }
  15466. {
  15467. auto res = cli.Get(
  15468. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  15469. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15470. EXPECT_EQ("Page Content Page Content", res->body);
  15471. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  15472. }
  15473. }
  15474. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  15475. auto handled = false;
  15476. Server svr;
  15477. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  15478. thread t = thread([&] { svr.listen(HOST, PORT); });
  15479. auto se = detail::scope_exit([&] {
  15480. svr.stop();
  15481. t.join();
  15482. ASSERT_FALSE(svr.is_running());
  15483. ASSERT_FALSE(handled);
  15484. });
  15485. svr.wait_until_ready();
  15486. auto req = "POST /test HTTP/1.1\r\n"
  15487. "Content-Length: x\r\n"
  15488. "\r\n";
  15489. std::string response;
  15490. ASSERT_TRUE(send_request(1, req, &response));
  15491. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  15492. response.substr(0, response.find("\r\n")));
  15493. }
  15494. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  15495. // case-insensitive, and a server that receives a 100-continue expectation in
  15496. // an HTTP/1.0 request MUST ignore it.
  15497. static void probe_expect(int port, const std::string &req, bool *got_100) {
  15498. std::string response;
  15499. ASSERT_TRUE(send_request(1, req, &response, port));
  15500. *got_100 = response.find("100 Continue") != std::string::npos;
  15501. }
  15502. class ExpectTokenTest : public ::testing::Test {
  15503. protected:
  15504. void SetUp() override {
  15505. svr_.Post("/p", [](const Request &, Response &res) {
  15506. res.set_content("ok", "text/plain");
  15507. });
  15508. port_ = svr_.bind_to_any_port(HOST);
  15509. thread_ = thread([&]() { svr_.listen_after_bind(); });
  15510. svr_.wait_until_ready();
  15511. }
  15512. void TearDown() override {
  15513. svr_.stop();
  15514. if (thread_.joinable()) { thread_.join(); }
  15515. }
  15516. std::string request(const char *version, const char *expect_value) const {
  15517. return std::string("POST /p ") + version +
  15518. "\r\n"
  15519. "Host: localhost\r\n"
  15520. "Content-Length: 2\r\n"
  15521. "Connection: close\r\n"
  15522. "Expect: " +
  15523. expect_value +
  15524. "\r\n"
  15525. "\r\n"
  15526. "hi";
  15527. }
  15528. Server svr_;
  15529. int port_ = 0;
  15530. thread thread_;
  15531. };
  15532. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  15533. bool got_100 = false;
  15534. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  15535. EXPECT_TRUE(got_100);
  15536. }
  15537. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  15538. bool got_100 = true;
  15539. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  15540. EXPECT_FALSE(got_100);
  15541. }
  15542. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  15543. bool got_100 = false;
  15544. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  15545. EXPECT_TRUE(got_100);
  15546. }
  15547. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  15548. bool got_100 = false;
  15549. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  15550. EXPECT_TRUE(got_100);
  15551. }
  15552. // `100 Continue` is sent only when the server starts reading the body, so a
  15553. // request rejected before that never invites the client to send it. The
  15554. // requests below carry the expectation but withhold the body, as a client
  15555. // waiting for `100 Continue` would.
  15556. // A POST that expects `100 Continue` and withholds its two-byte body.
  15557. static std::string expect_headers_only(const std::string &path) {
  15558. return "POST " + path +
  15559. " HTTP/1.1\r\n"
  15560. "Host: localhost\r\n"
  15561. "Content-Length: 2\r\n"
  15562. "Expect: 100-continue\r\n"
  15563. "\r\n";
  15564. }
  15565. class ExpectLazyContinueTest : public ::testing::Test {
  15566. protected:
  15567. void SetUp() override {
  15568. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  15569. if (req.path == "/pre-routing") {
  15570. res.status = StatusCode::Unauthorized_401;
  15571. return Server::HandlerResponse::Handled;
  15572. }
  15573. return Server::HandlerResponse::Unhandled;
  15574. });
  15575. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  15576. if (req.matched_route == "/pre-request") {
  15577. res.status = StatusCode::Forbidden_403;
  15578. return Server::HandlerResponse::Handled;
  15579. }
  15580. return Server::HandlerResponse::Unhandled;
  15581. });
  15582. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  15583. res.set_content("ok", "text/plain");
  15584. });
  15585. svr_.Post("/pre-request", [](const Request &, Response &res) {
  15586. res.set_content("ok", "text/plain");
  15587. });
  15588. svr_.Post("/reader-used", [](const Request &, Response &res,
  15589. const ContentReader &content_reader) {
  15590. std::string body;
  15591. content_reader([&](const char *data, size_t len) {
  15592. body.append(data, len);
  15593. return true;
  15594. });
  15595. res.set_content(body, "text/plain");
  15596. });
  15597. svr_.Post("/reader-unused",
  15598. [](const Request &, Response &res, const ContentReader &) {
  15599. res.set_content("ignored", "text/plain");
  15600. });
  15601. port_ = svr_.bind_to_any_port(HOST);
  15602. thread_ = thread([&]() { svr_.listen_after_bind(); });
  15603. svr_.wait_until_ready();
  15604. }
  15605. void TearDown() override {
  15606. svr_.stop();
  15607. if (thread_.joinable()) { thread_.join(); }
  15608. }
  15609. // Sends `req` and reads until the server closes the connection. Returns
  15610. // false if the read had to wait for the client-side timeout instead.
  15611. bool send_until_closed(const std::string &req, std::string *resp) const {
  15612. auto start = std::chrono::steady_clock::now();
  15613. if (!send_request(3, req, resp, port_)) { return false; }
  15614. auto elapsed = std::chrono::steady_clock::now() - start;
  15615. return elapsed < std::chrono::seconds(2);
  15616. }
  15617. // The final response comes without `100 Continue`, and the server closes
  15618. // the connection since the body may or may not follow.
  15619. void expect_final_without_interim(const std::string &path,
  15620. const char *status_line) const {
  15621. std::string resp;
  15622. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  15623. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  15624. EXPECT_EQ(0u, resp.find(status_line));
  15625. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  15626. }
  15627. Server svr_;
  15628. int port_ = 0;
  15629. thread thread_;
  15630. };
  15631. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  15632. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  15633. }
  15634. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  15635. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  15636. }
  15637. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  15638. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  15639. }
  15640. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  15641. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  15642. }
  15643. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  15644. // The body follows once `100 Continue` has had time to arrive.
  15645. auto req = expect_headers_only("/reader-used");
  15646. req.insert(req.size() - 2, "Connection: close\r\n");
  15647. std::string resp;
  15648. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  15649. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  15650. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  15651. EXPECT_NE(std::string::npos, resp.find("hi"));
  15652. }
  15653. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  15654. // Large enough for the client to add `Expect: 100-continue` itself.
  15655. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  15656. std::atomic<bool> body_sent{false};
  15657. Client cli(HOST, port_);
  15658. auto res = cli.Post(
  15659. "/pre-request", length,
  15660. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  15661. body_sent = true;
  15662. std::string chunk(len, 'x');
  15663. sink.write(chunk.data(), chunk.size());
  15664. return true;
  15665. },
  15666. "application/octet-stream");
  15667. ASSERT_TRUE(res);
  15668. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  15669. EXPECT_FALSE(body_sent);
  15670. }
  15671. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  15672. Server svr;
  15673. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  15674. return StatusCode::ExpectationFailed_417;
  15675. });
  15676. svr.Post("/p", [](const Request &, Response &res) {
  15677. res.set_content("ok", "text/plain");
  15678. });
  15679. auto port = svr.bind_to_any_port(HOST);
  15680. thread t = thread([&] { svr.listen_after_bind(); });
  15681. auto se = detail::scope_exit([&] {
  15682. svr.stop();
  15683. t.join();
  15684. });
  15685. svr.wait_until_ready();
  15686. std::string resp;
  15687. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  15688. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  15689. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  15690. // Exactly one response: the route handler must not run after the 417.
  15691. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  15692. }
  15693. #ifndef _WIN32
  15694. TEST(Expect100ContinueTest, ServerClosesConnection) {
  15695. static constexpr char reject[] = "Unauthorized";
  15696. static constexpr char accept[] = "Upload accepted";
  15697. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  15698. Server svr;
  15699. svr.set_expect_100_continue_handler(
  15700. [](const Request & /*req*/, Response &res) {
  15701. res.status = StatusCode::Unauthorized_401;
  15702. res.set_content(reject, "text/plain");
  15703. return res.status;
  15704. });
  15705. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  15706. res.set_content(accept, "text/plain");
  15707. });
  15708. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15709. auto se = detail::scope_exit([&] {
  15710. svr.stop();
  15711. thread.join();
  15712. ASSERT_FALSE(svr.is_running());
  15713. });
  15714. svr.wait_until_ready();
  15715. {
  15716. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  15717. curl_easy_init(), &curl_easy_cleanup};
  15718. ASSERT_NE(curl, nullptr);
  15719. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  15720. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  15721. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  15722. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  15723. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  15724. &curl_slist_free_all};
  15725. ASSERT_NE(list, nullptr);
  15726. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  15727. struct read_data {
  15728. size_t read_size;
  15729. size_t total_size;
  15730. } data = {0, total_size};
  15731. using read_callback_t =
  15732. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  15733. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  15734. void *userdata) -> size_t {
  15735. read_data *d = (read_data *)userdata;
  15736. if (!userdata || d->read_size >= d->total_size) { return 0; }
  15737. std::fill_n(ptr, size * nmemb, 'A');
  15738. d->read_size += size * nmemb;
  15739. return size * nmemb;
  15740. };
  15741. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  15742. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  15743. std::vector<char> buffer;
  15744. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  15745. using write_callback_t =
  15746. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  15747. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  15748. void *userdata) -> size_t {
  15749. std::vector<char> *buf = (std::vector<char> *)userdata;
  15750. buf->reserve(buf->size() + size * nmemb + 1);
  15751. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  15752. return size * nmemb;
  15753. };
  15754. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  15755. {
  15756. const auto res = curl_easy_perform(curl.get());
  15757. ASSERT_EQ(res, CURLE_OK);
  15758. }
  15759. {
  15760. auto response_code = long{};
  15761. const auto res =
  15762. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  15763. ASSERT_EQ(res, CURLE_OK);
  15764. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  15765. }
  15766. {
  15767. auto dl = curl_off_t{};
  15768. const auto res =
  15769. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  15770. ASSERT_EQ(res, CURLE_OK);
  15771. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  15772. }
  15773. {
  15774. buffer.push_back('\0');
  15775. ASSERT_STRCASEEQ(buffer.data(), reject);
  15776. }
  15777. }
  15778. }
  15779. #endif
  15780. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  15781. // Regression test for #2458.
  15782. //
  15783. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  15784. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  15785. // ticket can make the client socket spuriously readable during the
  15786. // 100-continue wait. If the readiness is mistaken for an incoming response,
  15787. // the client withholds the body and then blocks reading a response that never
  15788. // comes, failing with `Failed to read connection`.
  15789. //
  15790. // A correct client (like curl) sends the body once no `100 Continue` arrives
  15791. // within the timeout. This raw OpenSSL server deliberately never sends
  15792. // `100 Continue`; the client must still deliver the body and receive 200.
  15793. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  15794. signal(SIGPIPE, SIG_IGN);
  15795. const auto port = PORT + 4;
  15796. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15797. ASSERT_NE(srv, INVALID_SOCKET);
  15798. int opt = 1;
  15799. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  15800. sockaddr_in addr{};
  15801. addr.sin_family = AF_INET;
  15802. addr.sin_port = htons(static_cast<uint16_t>(port));
  15803. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15804. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  15805. ASSERT_EQ(0, ::listen(srv, 1));
  15806. std::atomic<size_t> server_body_bytes{0};
  15807. auto server_thread = std::thread([&] {
  15808. sockaddr_in cli_addr{};
  15809. socklen_t cli_len = sizeof(cli_addr);
  15810. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  15811. if (cli == INVALID_SOCKET) { return; }
  15812. // Bound the lifetime of the server side so a buggy client (which never
  15813. // sends the body) cannot make this thread block forever on join.
  15814. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  15815. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  15816. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  15817. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  15818. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  15819. SSL *ssl = SSL_new(ctx);
  15820. SSL_set_fd(ssl, static_cast<int>(cli));
  15821. if (SSL_accept(ssl) > 0) {
  15822. // Read the request headers. Reading here also flushes the TLS 1.3
  15823. // session tickets to the client. Deliberately do NOT send
  15824. // `100 Continue`.
  15825. std::string buf;
  15826. char tmp[1024];
  15827. while (buf.find("\r\n\r\n") == std::string::npos) {
  15828. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  15829. if (n <= 0) { break; }
  15830. buf.append(tmp, static_cast<size_t>(n));
  15831. }
  15832. // A correct client sends the body now; count what arrives.
  15833. auto pos = buf.find("\r\n\r\n");
  15834. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  15835. while (body < 4096) {
  15836. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  15837. if (n <= 0) { break; }
  15838. body += static_cast<size_t>(n);
  15839. }
  15840. server_body_bytes = body;
  15841. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  15842. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  15843. SSL_shutdown(ssl);
  15844. }
  15845. SSL_free(ssl);
  15846. detail::close_socket(cli);
  15847. SSL_CTX_free(ctx);
  15848. });
  15849. auto se = detail::scope_exit([&] {
  15850. server_thread.join();
  15851. detail::close_socket(srv);
  15852. });
  15853. SSLClient cli("127.0.0.1", port);
  15854. cli.enable_server_certificate_verification(false);
  15855. cli.set_connection_timeout(5, 0);
  15856. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  15857. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  15858. std::string body(4096, 'A');
  15859. auto res = cli.Put("/api/test", body, "application/json");
  15860. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  15861. EXPECT_EQ(StatusCode::OK_200, res->status);
  15862. EXPECT_EQ(body.size(), server_body_bytes.load());
  15863. }
  15864. #endif
  15865. template <typename S, typename C>
  15866. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  15867. svr.Get("/stream", [&](const Request &, Response &res) {
  15868. auto data = new std::string("01234567890123456789");
  15869. res.set_content_provider(
  15870. data->size(), "text/plain",
  15871. [&, data](size_t offset, size_t length, DataSink &sink) {
  15872. const size_t DATA_CHUNK_SIZE = 4;
  15873. const auto &d = *data;
  15874. std::this_thread::sleep_for(std::chrono::seconds(1));
  15875. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  15876. return true;
  15877. },
  15878. [data](bool success) {
  15879. EXPECT_FALSE(success);
  15880. delete data;
  15881. });
  15882. });
  15883. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  15884. auto i = new size_t(0);
  15885. res.set_content_provider(
  15886. "text/plain",
  15887. [i](size_t, DataSink &sink) {
  15888. if (*i < 5) {
  15889. std::this_thread::sleep_for(std::chrono::seconds(1));
  15890. sink.write("abcd", 4);
  15891. (*i)++;
  15892. } else {
  15893. sink.done();
  15894. }
  15895. return true;
  15896. },
  15897. [i](bool success) {
  15898. EXPECT_FALSE(success);
  15899. delete i;
  15900. });
  15901. });
  15902. svr.Get("/chunked", [&](const Request &, Response &res) {
  15903. auto i = new size_t(0);
  15904. res.set_chunked_content_provider(
  15905. "text/plain",
  15906. [i](size_t, DataSink &sink) {
  15907. if (*i < 5) {
  15908. std::this_thread::sleep_for(std::chrono::seconds(1));
  15909. sink.os << "abcd";
  15910. (*i)++;
  15911. } else {
  15912. sink.done();
  15913. }
  15914. return true;
  15915. },
  15916. [i](bool success) {
  15917. EXPECT_FALSE(success);
  15918. delete i;
  15919. });
  15920. });
  15921. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  15922. auto se = detail::scope_exit([&] {
  15923. svr.stop();
  15924. listen_thread.join();
  15925. ASSERT_FALSE(svr.is_running());
  15926. });
  15927. svr.wait_until_ready();
  15928. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  15929. {
  15930. auto start = std::chrono::steady_clock::now();
  15931. auto res = cli.Get("/stream");
  15932. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  15933. std::chrono::steady_clock::now() - start)
  15934. .count();
  15935. ASSERT_FALSE(res);
  15936. EXPECT_EQ(Error::Read, res.error());
  15937. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  15938. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  15939. }
  15940. {
  15941. auto start = std::chrono::steady_clock::now();
  15942. auto res = cli.Get("/stream_without_length");
  15943. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  15944. std::chrono::steady_clock::now() - start)
  15945. .count();
  15946. ASSERT_FALSE(res);
  15947. EXPECT_EQ(Error::Read, res.error());
  15948. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  15949. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  15950. }
  15951. {
  15952. auto start = std::chrono::steady_clock::now();
  15953. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  15954. EXPECT_EQ("abcd", string(data, data_length));
  15955. return true;
  15956. });
  15957. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  15958. std::chrono::steady_clock::now() - start)
  15959. .count();
  15960. ASSERT_FALSE(res);
  15961. EXPECT_EQ(Error::Read, res.error());
  15962. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  15963. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  15964. }
  15965. }
  15966. TEST(MaxTimeoutTest, ContentStream) {
  15967. time_t timeout = 2000;
  15968. time_t threshold = 200;
  15969. Server svr;
  15970. Client cli("localhost", PORT);
  15971. max_timeout_test(svr, cli, timeout, threshold);
  15972. }
  15973. #ifdef CPPHTTPLIB_SSL_ENABLED
  15974. TEST(MaxTimeoutTest, ContentStreamSSL) {
  15975. time_t timeout = 2000;
  15976. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  15977. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15978. SSLClient cli("localhost", PORT);
  15979. cli.enable_server_certificate_verification(false);
  15980. max_timeout_test(svr, cli, timeout, threshold);
  15981. }
  15982. #endif
  15983. class EventDispatcher {
  15984. public:
  15985. EventDispatcher() {}
  15986. bool wait_event(DataSink *sink) {
  15987. unique_lock<mutex> lk(m_);
  15988. int id = id_;
  15989. // Wait with timeout to prevent hanging if client disconnects
  15990. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  15991. [&] { return cid_ == id; })) {
  15992. return false; // Timeout occurred
  15993. }
  15994. sink->write(message_.data(), message_.size());
  15995. return true;
  15996. }
  15997. void send_event(const string &message) {
  15998. lock_guard<mutex> lk(m_);
  15999. cid_ = id_++;
  16000. message_ = message;
  16001. cv_.notify_all();
  16002. }
  16003. private:
  16004. mutex m_;
  16005. condition_variable cv_;
  16006. atomic_int id_{0};
  16007. atomic_int cid_{-1};
  16008. string message_;
  16009. };
  16010. TEST(ClientInThreadTest, Issue2068) {
  16011. EventDispatcher ed;
  16012. Server svr;
  16013. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  16014. res.set_chunked_content_provider("text/event-stream",
  16015. [&](size_t /*offset*/, DataSink &sink) {
  16016. return ed.wait_event(&sink);
  16017. });
  16018. });
  16019. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  16020. svr.wait_until_ready();
  16021. thread event_thread([&] {
  16022. int id = 0;
  16023. while (svr.is_running()) {
  16024. this_thread::sleep_for(chrono::milliseconds(500));
  16025. std::stringstream ss;
  16026. ss << "data: " << id << "\n\n";
  16027. ed.send_event(ss.str());
  16028. id++;
  16029. }
  16030. });
  16031. auto se = detail::scope_exit([&] {
  16032. svr.stop();
  16033. listen_thread.join();
  16034. event_thread.join();
  16035. ASSERT_FALSE(svr.is_running());
  16036. });
  16037. {
  16038. auto client = detail::make_unique<Client>(HOST, PORT);
  16039. client->set_read_timeout(std::chrono::minutes(10));
  16040. std::atomic<bool> stop{false};
  16041. std::thread t([&] {
  16042. client->Get("/event1",
  16043. [&](const char *, size_t) -> bool { return !stop; });
  16044. });
  16045. std::this_thread::sleep_for(std::chrono::seconds(2));
  16046. stop = true;
  16047. client->stop();
  16048. t.join();
  16049. // Reset client after thread has finished
  16050. client.reset();
  16051. }
  16052. }
  16053. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  16054. auto handled = false;
  16055. Server svr;
  16056. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  16057. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16058. auto se = detail::scope_exit([&] {
  16059. svr.stop();
  16060. t.join();
  16061. ASSERT_FALSE(svr.is_running());
  16062. ASSERT_FALSE(handled);
  16063. });
  16064. svr.wait_until_ready();
  16065. // Two Content-Length headers with different values — must be rejected
  16066. auto req = "POST /test HTTP/1.1\r\n"
  16067. "Content-Length: 5\r\n"
  16068. "Content-Length: 10\r\n"
  16069. "\r\n"
  16070. "hello";
  16071. std::string response;
  16072. ASSERT_TRUE(send_request(1, req, &response));
  16073. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  16074. response.substr(0, response.find("\r\n")));
  16075. }
  16076. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  16077. auto handled = false;
  16078. Server svr;
  16079. svr.Post("/test", [&](const Request &, Response &res) {
  16080. handled = true;
  16081. res.set_content("ok", "text/plain");
  16082. });
  16083. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16084. auto se = detail::scope_exit([&] {
  16085. svr.stop();
  16086. t.join();
  16087. ASSERT_FALSE(svr.is_running());
  16088. ASSERT_TRUE(handled);
  16089. });
  16090. svr.wait_until_ready();
  16091. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  16092. auto req = "POST /test HTTP/1.1\r\n"
  16093. "Content-Length: 5\r\n"
  16094. "Content-Length: 5\r\n"
  16095. "\r\n"
  16096. "hello";
  16097. std::string response;
  16098. ASSERT_TRUE(send_request(1, req, &response));
  16099. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  16100. }
  16101. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  16102. Server svr;
  16103. svr.Get("/", [](const Request &req, Response &res) {
  16104. EXPECT_EQ(2U, req.trailers.size());
  16105. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  16106. // Denied
  16107. EXPECT_FALSE(req.has_trailer("Content-Length"));
  16108. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  16109. // Accepted
  16110. EXPECT_TRUE(req.has_trailer("X-Hello"));
  16111. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  16112. EXPECT_TRUE(req.has_trailer("X-World"));
  16113. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  16114. res.set_content("ok", "text/plain");
  16115. });
  16116. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16117. auto se = detail::scope_exit([&] {
  16118. svr.stop();
  16119. t.join();
  16120. ASSERT_FALSE(svr.is_running());
  16121. });
  16122. svr.wait_until_ready();
  16123. const std::string req = "GET / HTTP/1.1\r\n"
  16124. "Transfer-Encoding: chunked\r\n"
  16125. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  16126. "\r\n"
  16127. "0\r\n"
  16128. "Content-Length: 10\r\n"
  16129. "Host: internal.local\r\n"
  16130. "Content-Type: malicious/content\r\n"
  16131. "Cookie: any\r\n"
  16132. "Set-Cookie: any\r\n"
  16133. "X-Forwarded-For: attacker.com\r\n"
  16134. "X-Real-Ip: 1.1.1.1\r\n"
  16135. "X-Hello: hello\r\n"
  16136. "X-World: world\r\n"
  16137. "\r\n";
  16138. std::string res;
  16139. ASSERT_TRUE(send_request(1, req, &res));
  16140. }
  16141. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  16142. // several field lines, and the combined value is what has to be parsed. A
  16143. // Trailer field split across lines therefore declares every name it lists;
  16144. // reading only the first line silently drops the trailers the later lines
  16145. // declare. The prohibited-trailer filter still applies to every line.
  16146. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  16147. Server svr;
  16148. size_t observed_trailer_count = 0;
  16149. std::string observed_hello;
  16150. std::string observed_world;
  16151. bool observed_content_length = true;
  16152. svr.Get("/", [&](const Request &req, Response &res) {
  16153. observed_trailer_count = req.trailers.size();
  16154. observed_hello = req.get_trailer_value("X-Hello");
  16155. observed_world = req.get_trailer_value("X-World");
  16156. observed_content_length = req.has_trailer("Content-Length");
  16157. res.set_content("ok", "text/plain");
  16158. });
  16159. auto port = svr.bind_to_any_port(HOST);
  16160. thread t = thread([&]() { svr.listen_after_bind(); });
  16161. auto se = detail::scope_exit([&] {
  16162. svr.stop();
  16163. t.join();
  16164. ASSERT_FALSE(svr.is_running());
  16165. });
  16166. svr.wait_until_ready();
  16167. const std::string req = "GET / HTTP/1.1\r\n"
  16168. "Transfer-Encoding: chunked\r\n"
  16169. "Trailer: X-Hello\r\n"
  16170. "Trailer: X-World, Content-Length\r\n"
  16171. "\r\n"
  16172. "0\r\n"
  16173. "X-Hello: hello\r\n"
  16174. "X-World: world\r\n"
  16175. "Content-Length: 10\r\n"
  16176. "\r\n";
  16177. std::string res;
  16178. ASSERT_TRUE(send_request(1, req, &res, port));
  16179. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  16180. // Accepted: both field lines contribute to the declared set
  16181. EXPECT_EQ(2U, observed_trailer_count);
  16182. EXPECT_EQ(observed_hello, "hello");
  16183. EXPECT_EQ(observed_world, "world");
  16184. // Denied: a prohibited name stays prohibited on a later field line
  16185. EXPECT_FALSE(observed_content_length);
  16186. }
  16187. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  16188. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  16189. // unbounded run of fields that are never declared, because the counter would
  16190. // only advance for declared fields.
  16191. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  16192. Server svr;
  16193. bool handler_called = false;
  16194. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  16195. handler_called = true;
  16196. res.set_content("ok", "text/plain");
  16197. });
  16198. auto port = svr.bind_to_any_port(HOST);
  16199. thread t = thread([&]() { svr.listen_after_bind(); });
  16200. auto se = detail::scope_exit([&] {
  16201. svr.stop();
  16202. t.join();
  16203. ASSERT_FALSE(svr.is_running());
  16204. });
  16205. svr.wait_until_ready();
  16206. // Declare nothing, then send far more undeclared trailer fields than the
  16207. // header-count limit. Parsing must stop and reject the request rather than
  16208. // read every line.
  16209. std::string req = "GET / HTTP/1.1\r\n"
  16210. "Transfer-Encoding: chunked\r\n"
  16211. "\r\n"
  16212. "0\r\n";
  16213. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  16214. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  16215. }
  16216. req += "\r\n";
  16217. std::string res;
  16218. ASSERT_TRUE(send_request(1, req, &res, port));
  16219. // The request is rejected before the handler runs.
  16220. EXPECT_FALSE(handler_called);
  16221. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  16222. }
  16223. // The set of declared trailer names is capped so a peer cannot grow it without
  16224. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  16225. // declared past the cap is not honored, even if the field is actually sent.
  16226. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  16227. Server svr;
  16228. // One name inside the cap and one past it, so the test tracks the cap rather
  16229. // than a fixed count.
  16230. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  16231. const std::string within_cap_name = "X-T-0";
  16232. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  16233. bool observed_within_cap = false;
  16234. bool observed_past_cap = false;
  16235. svr.Get("/", [&](const Request &req, Response &res) {
  16236. observed_within_cap = req.has_trailer(within_cap_name);
  16237. observed_past_cap = req.has_trailer(past_cap_name);
  16238. res.set_content("ok", "text/plain");
  16239. });
  16240. auto port = svr.bind_to_any_port(HOST);
  16241. thread t = thread([&]() { svr.listen_after_bind(); });
  16242. auto se = detail::scope_exit([&] {
  16243. svr.stop();
  16244. t.join();
  16245. ASSERT_FALSE(svr.is_running());
  16246. });
  16247. svr.wait_until_ready();
  16248. // Declare more trailer names than the cap in a single Trailer field, then
  16249. // actually send the first (within the cap) and the last (past it).
  16250. std::string trailer_decl = "Trailer: ";
  16251. for (int i = 0; i < declared_count; i++) {
  16252. if (i != 0) { trailer_decl += ", "; }
  16253. trailer_decl += "X-T-" + std::to_string(i);
  16254. }
  16255. trailer_decl += "\r\n";
  16256. const std::string req = "GET / HTTP/1.1\r\n"
  16257. "Transfer-Encoding: chunked\r\n" +
  16258. trailer_decl +
  16259. "\r\n"
  16260. "0\r\n" +
  16261. within_cap_name + ": a\r\n" + past_cap_name +
  16262. ": b\r\n"
  16263. "\r\n";
  16264. std::string res;
  16265. ASSERT_TRUE(send_request(1, req, &res, port));
  16266. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  16267. // A name within the cap is honored; one declared past the cap is dropped.
  16268. EXPECT_TRUE(observed_within_cap);
  16269. EXPECT_FALSE(observed_past_cap);
  16270. }
  16271. // A direct client that is not listed in trusted_proxies must not be able to
  16272. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  16273. // the peer address on the actual TCP connection determines whether the
  16274. // header is honored.
  16275. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  16276. Server svr;
  16277. // Deliberately does NOT include the loopback address the test client
  16278. // actually connects from, so the direct connection is not a trusted proxy.
  16279. svr.set_trusted_proxies({"203.0.113.66"});
  16280. std::string observed_remote_addr;
  16281. svr.Get("/ip", [&](const Request &req, Response &res) {
  16282. observed_remote_addr = req.remote_addr;
  16283. res.set_content("ok", "text/plain");
  16284. });
  16285. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16286. auto se = detail::scope_exit([&] {
  16287. svr.stop();
  16288. t.join();
  16289. ASSERT_FALSE(svr.is_running());
  16290. });
  16291. svr.wait_until_ready();
  16292. Client cli(HOST, PORT);
  16293. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  16294. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16295. EXPECT_EQ(StatusCode::OK_200, res->status);
  16296. // The connecting peer is not a trusted proxy, so the spoofed header must be
  16297. // ignored entirely and the real connection-level address retained.
  16298. EXPECT_TRUE(observed_remote_addr == "::1" ||
  16299. observed_remote_addr == "127.0.0.1");
  16300. }
  16301. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  16302. Server svr;
  16303. std::string observed_remote_addr;
  16304. std::string observed_xff;
  16305. svr.Get("/ip", [&](const Request &req, Response &res) {
  16306. observed_remote_addr = req.remote_addr;
  16307. observed_xff = req.get_header_value("X-Forwarded-For");
  16308. res.set_content("ok", "text/plain");
  16309. });
  16310. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16311. auto se = detail::scope_exit([&] {
  16312. svr.stop();
  16313. t.join();
  16314. ASSERT_FALSE(svr.is_running());
  16315. });
  16316. svr.wait_until_ready();
  16317. Client cli(HOST, PORT);
  16318. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  16319. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16320. EXPECT_EQ(StatusCode::OK_200, res->status);
  16321. EXPECT_EQ(observed_xff, "203.0.113.66");
  16322. EXPECT_TRUE(observed_remote_addr == "::1" ||
  16323. observed_remote_addr == "127.0.0.1");
  16324. }
  16325. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  16326. Server svr;
  16327. svr.set_trusted_proxies({"203.0.113.66"});
  16328. std::string observed_remote_addr;
  16329. std::string observed_xff;
  16330. svr.Get("/ip", [&](const Request &req, Response &res) {
  16331. observed_remote_addr = req.remote_addr;
  16332. observed_xff = req.get_header_value("X-Forwarded-For");
  16333. res.set_content("ok", "text/plain");
  16334. });
  16335. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16336. auto se = detail::scope_exit([&] {
  16337. svr.stop();
  16338. t.join();
  16339. ASSERT_FALSE(svr.is_running());
  16340. });
  16341. svr.wait_until_ready();
  16342. Client cli(HOST, PORT);
  16343. auto res = cli.Get("/ip");
  16344. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16345. EXPECT_EQ(StatusCode::OK_200, res->status);
  16346. EXPECT_EQ(observed_xff, "");
  16347. EXPECT_TRUE(observed_remote_addr == "::1" ||
  16348. observed_remote_addr == "127.0.0.1");
  16349. }
  16350. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  16351. Server svr;
  16352. // Include the loopback address the test client actually connects from, so
  16353. // the direct connection itself is recognized as the trusted proxy hop.
  16354. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  16355. std::string observed_remote_addr;
  16356. std::string observed_xff;
  16357. svr.Get("/ip", [&](const Request &req, Response &res) {
  16358. observed_remote_addr = req.remote_addr;
  16359. observed_xff = req.get_header_value("X-Forwarded-For");
  16360. res.set_content("ok", "text/plain");
  16361. });
  16362. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16363. auto se = detail::scope_exit([&] {
  16364. svr.stop();
  16365. t.join();
  16366. ASSERT_FALSE(svr.is_running());
  16367. });
  16368. svr.wait_until_ready();
  16369. Client cli(HOST, PORT);
  16370. auto res = cli.Get(
  16371. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  16372. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16373. EXPECT_EQ(StatusCode::OK_200, res->status);
  16374. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  16375. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  16376. }
  16377. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  16378. Server svr;
  16379. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  16380. std::string observed_remote_addr;
  16381. std::string observed_xff;
  16382. svr.Get("/ip", [&](const Request &req, Response &res) {
  16383. observed_remote_addr = req.remote_addr;
  16384. observed_xff = req.get_header_value("X-Forwarded-For");
  16385. res.set_content("ok", "text/plain");
  16386. });
  16387. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16388. auto se = detail::scope_exit([&] {
  16389. svr.stop();
  16390. t.join();
  16391. ASSERT_FALSE(svr.is_running());
  16392. });
  16393. svr.wait_until_ready();
  16394. Client cli(HOST, PORT);
  16395. auto res = cli.Get(
  16396. "/ip",
  16397. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  16398. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16399. EXPECT_EQ(StatusCode::OK_200, res->status);
  16400. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  16401. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  16402. }
  16403. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  16404. Server svr;
  16405. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  16406. std::string observed_remote_addr;
  16407. std::string observed_xff;
  16408. svr.Get("/ip", [&](const Request &req, Response &res) {
  16409. observed_remote_addr = req.remote_addr;
  16410. observed_xff = req.get_header_value("X-Forwarded-For");
  16411. res.set_content("ok", "text/plain");
  16412. });
  16413. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16414. auto se = detail::scope_exit([&] {
  16415. svr.stop();
  16416. t.join();
  16417. ASSERT_FALSE(svr.is_running());
  16418. });
  16419. svr.wait_until_ready();
  16420. Client cli(HOST, PORT);
  16421. auto res = cli.Get(
  16422. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  16423. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16424. EXPECT_EQ(StatusCode::OK_200, res->status);
  16425. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  16426. // by the closest hop) is used. The leftmost entry is fully client-controlled
  16427. // and must not be selected.
  16428. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  16429. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  16430. }
  16431. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  16432. Server svr;
  16433. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  16434. std::string observed_remote_addr;
  16435. svr.Get("/ip", [&](const Request &req, Response &res) {
  16436. observed_remote_addr = req.remote_addr;
  16437. res.set_content("ok", "text/plain");
  16438. });
  16439. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16440. auto se = detail::scope_exit([&] {
  16441. svr.stop();
  16442. t.join();
  16443. ASSERT_FALSE(svr.is_running());
  16444. });
  16445. svr.wait_until_ready();
  16446. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  16447. // a forged address and the trusted proxy's own address; the forged value must
  16448. // not win over the address the trusted proxy actually recorded.
  16449. Client cli(HOST, PORT);
  16450. auto res = cli.Get(
  16451. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  16452. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16453. EXPECT_EQ(StatusCode::OK_200, res->status);
  16454. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  16455. }
  16456. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  16457. Server svr;
  16458. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  16459. std::string observed_remote_addr;
  16460. std::string observed_xff;
  16461. svr.Get("/ip", [&](const Request &req, Response &res) {
  16462. observed_remote_addr = req.remote_addr;
  16463. observed_xff = req.get_header_value("X-Forwarded-For");
  16464. res.set_content("ok", "text/plain");
  16465. });
  16466. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16467. auto se = detail::scope_exit([&] {
  16468. svr.stop();
  16469. t.join();
  16470. ASSERT_FALSE(svr.is_running());
  16471. });
  16472. svr.wait_until_ready();
  16473. Client cli(HOST, PORT);
  16474. auto res = cli.Get(
  16475. "/ip",
  16476. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  16477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16478. EXPECT_EQ(StatusCode::OK_200, res->status);
  16479. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  16480. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  16481. }
  16482. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  16483. Server svr;
  16484. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  16485. std::string observed_remote_addr;
  16486. std::string observed_xff;
  16487. svr.Get("/ip", [&](const Request &req, Response &res) {
  16488. observed_remote_addr = req.remote_addr;
  16489. observed_xff = req.get_header_value("X-Forwarded-For");
  16490. res.set_content("ok", "text/plain");
  16491. });
  16492. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16493. auto se = detail::scope_exit([&] {
  16494. svr.stop();
  16495. t.join();
  16496. ASSERT_FALSE(svr.is_running());
  16497. });
  16498. svr.wait_until_ready();
  16499. std::string raw_req =
  16500. "GET /ip HTTP/1.1\r\n"
  16501. "Host: localhost\r\n"
  16502. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  16503. "Connection: close\r\n"
  16504. "\r\n";
  16505. std::string out;
  16506. ASSERT_TRUE(send_request(5, raw_req, &out));
  16507. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  16508. // Header parser trims surrounding whitespace of the header value
  16509. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  16510. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  16511. }
  16512. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  16513. // one comma-joined value, in the order received. Proxies such as HAProxy append
  16514. // their own X-Forwarded-For as a separate field line rather than extending the
  16515. // one the client sent, so every occurrence has to be taken into account.
  16516. // Reading only the first one hands back the address the client chose.
  16517. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  16518. Server svr;
  16519. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  16520. std::string observed_remote_addr;
  16521. size_t observed_xff_count = 0;
  16522. svr.Get("/ip", [&](const Request &req, Response &res) {
  16523. observed_remote_addr = req.remote_addr;
  16524. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  16525. res.set_content("ok", "text/plain");
  16526. });
  16527. auto port = svr.bind_to_any_port(HOST);
  16528. thread t = thread([&]() { svr.listen_after_bind(); });
  16529. auto se = detail::scope_exit([&] {
  16530. svr.stop();
  16531. t.join();
  16532. ASSERT_FALSE(svr.is_running());
  16533. });
  16534. svr.wait_until_ready();
  16535. // The client supplies the first field line; the trusted proxy appends the
  16536. // address it observed as a second one.
  16537. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  16538. "Host: localhost\r\n"
  16539. "X-Forwarded-For: 1.2.3.4\r\n"
  16540. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  16541. "Connection: close\r\n"
  16542. "\r\n";
  16543. std::string out;
  16544. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  16545. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  16546. EXPECT_EQ(observed_xff_count, 2U);
  16547. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  16548. // The same chain spread over one field line per hop derives the same client
  16549. // address, i.e. the split and the comma-joined representations agree.
  16550. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  16551. "Host: localhost\r\n"
  16552. "X-Forwarded-For: 1.2.3.4\r\n"
  16553. "X-Forwarded-For: 198.51.100.23\r\n"
  16554. "X-Forwarded-For: 192.0.2.45\r\n"
  16555. "Connection: close\r\n"
  16556. "\r\n";
  16557. out.clear();
  16558. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  16559. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  16560. EXPECT_EQ(observed_xff_count, 3U);
  16561. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  16562. }
  16563. // An X-Forwarded-For header whose value parses to zero IP segments must not
  16564. // crash the server (it used to call front() on an empty vector inside
  16565. // get_client_ip). The connection-level remote address must be retained instead.
  16566. static void run_malformed_xff_test(const std::string &xff_value) {
  16567. Server svr;
  16568. svr.set_trusted_proxies({"192.0.2.45"});
  16569. std::string observed_remote_addr;
  16570. svr.Get("/ip", [&](const Request &req, Response &res) {
  16571. observed_remote_addr = req.remote_addr;
  16572. res.set_content("ok", "text/plain");
  16573. });
  16574. int port = 0;
  16575. thread t = thread([&]() {
  16576. port = svr.bind_to_any_port(HOST);
  16577. svr.listen_after_bind();
  16578. });
  16579. auto se = detail::scope_exit([&] {
  16580. svr.stop();
  16581. t.join();
  16582. ASSERT_FALSE(svr.is_running());
  16583. });
  16584. svr.wait_until_ready();
  16585. Client cli(HOST, port);
  16586. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  16587. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16588. EXPECT_EQ(StatusCode::OK_200, res->status);
  16589. EXPECT_TRUE(observed_remote_addr == "::1" ||
  16590. observed_remote_addr == "127.0.0.1");
  16591. }
  16592. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  16593. run_malformed_xff_test("");
  16594. }
  16595. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  16596. run_malformed_xff_test(",");
  16597. }
  16598. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  16599. run_malformed_xff_test(", , ,");
  16600. }
  16601. // The same rule applies to Accept: a request whose acceptable types are spread
  16602. // over several field lines must be negotiated against all of them.
  16603. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  16604. // case-insensitive connection options. Comparing the whole field value against
  16605. // one option misses a client that sends several of them, and misses every
  16606. // casing but the one written in the comparison.
  16607. //
  16608. // Sends req, reads the response, then reuses the same socket for a second
  16609. // request to find out whether the server kept the connection.
  16610. static void probe_connection_reuse(int port, const std::string &req,
  16611. bool *announced_close, bool *reusable) {
  16612. auto error = Error::Success;
  16613. auto sock = detail::create_client_socket(
  16614. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  16615. /*connection_timeout_sec=*/5, 0,
  16616. /*read_timeout_sec=*/1, 0,
  16617. /*write_timeout_sec=*/5, 0, std::string(), error);
  16618. ASSERT_NE(sock, INVALID_SOCKET);
  16619. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  16620. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  16621. "Host: localhost\r\n"
  16622. "Connection: close\r\n"
  16623. "\r\n";
  16624. std::string first_response;
  16625. std::string second_response;
  16626. detail::process_client_socket(
  16627. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  16628. [&](Stream &strm) {
  16629. if (strm.write(req.data(), req.size()) !=
  16630. static_cast<ssize_t>(req.size())) {
  16631. return false;
  16632. }
  16633. char buf[512];
  16634. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  16635. // Headers plus the two-byte body of the handler below
  16636. while (reader.getline()) {
  16637. first_response += reader.ptr();
  16638. if (first_response.find("ok") != std::string::npos) { break; }
  16639. }
  16640. if (strm.write(second.data(), second.size()) !=
  16641. static_cast<ssize_t>(second.size())) {
  16642. return true;
  16643. }
  16644. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  16645. while (reader2.getline()) {
  16646. second_response += reader2.ptr();
  16647. if (second_response.find("ok") != std::string::npos) { break; }
  16648. }
  16649. return true;
  16650. });
  16651. *announced_close =
  16652. first_response.find("Connection: close") != std::string::npos;
  16653. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  16654. }
  16655. class ConnectionTokenTest : public ::testing::Test {
  16656. protected:
  16657. void SetUp() override {
  16658. svr_.Get("/keepalive", [](const Request &, Response &res) {
  16659. res.set_content("ok", "text/plain");
  16660. });
  16661. port_ = svr_.bind_to_any_port(HOST);
  16662. thread_ = thread([&]() { svr_.listen_after_bind(); });
  16663. svr_.wait_until_ready();
  16664. }
  16665. void TearDown() override {
  16666. svr_.stop();
  16667. if (thread_.joinable()) { thread_.join(); }
  16668. }
  16669. Server svr_;
  16670. int port_ = 0;
  16671. thread thread_;
  16672. };
  16673. // "close" alongside another option still closes the connection, and the
  16674. // response says so rather than leaving the peer to discover it.
  16675. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  16676. bool announced_close = false;
  16677. bool reusable = true;
  16678. probe_connection_reuse(port_,
  16679. "GET /keepalive HTTP/1.1\r\n"
  16680. "Host: localhost\r\n"
  16681. "Connection: keep-alive, close\r\n"
  16682. "\r\n",
  16683. &announced_close, &reusable);
  16684. EXPECT_TRUE(announced_close);
  16685. EXPECT_FALSE(reusable);
  16686. }
  16687. // "close" split over two field lines is the same list, so it is honored too.
  16688. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  16689. bool announced_close = false;
  16690. bool reusable = true;
  16691. probe_connection_reuse(port_,
  16692. "GET /keepalive HTTP/1.1\r\n"
  16693. "Host: localhost\r\n"
  16694. "Connection: keep-alive\r\n"
  16695. "Connection: close\r\n"
  16696. "\r\n",
  16697. &announced_close, &reusable);
  16698. EXPECT_TRUE(announced_close);
  16699. EXPECT_FALSE(reusable);
  16700. }
  16701. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  16702. // keep-alive in the spelling everyone actually sends keeps its connection.
  16703. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  16704. bool announced_close = false;
  16705. bool reusable = false;
  16706. probe_connection_reuse(port_,
  16707. "GET /keepalive HTTP/1.0\r\n"
  16708. "Host: localhost\r\n"
  16709. "Connection: keep-alive\r\n"
  16710. "\r\n",
  16711. &announced_close, &reusable);
  16712. EXPECT_FALSE(announced_close);
  16713. EXPECT_TRUE(reusable);
  16714. }
  16715. // A token the value merely contains is not the token itself.
  16716. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  16717. bool announced_close = false;
  16718. bool reusable = false;
  16719. probe_connection_reuse(port_,
  16720. "GET /keepalive HTTP/1.1\r\n"
  16721. "Host: localhost\r\n"
  16722. "Connection: notclose\r\n"
  16723. "\r\n",
  16724. &announced_close, &reusable);
  16725. EXPECT_FALSE(announced_close);
  16726. EXPECT_TRUE(reusable);
  16727. }
  16728. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  16729. Server svr;
  16730. std::vector<std::string> observed_types;
  16731. svr.Get("/", [&](const Request &req, Response &res) {
  16732. observed_types = req.accept_content_types;
  16733. res.set_content("ok", "text/plain");
  16734. });
  16735. auto port = svr.bind_to_any_port(HOST);
  16736. thread t = thread([&]() { svr.listen_after_bind(); });
  16737. auto se = detail::scope_exit([&] {
  16738. svr.stop();
  16739. t.join();
  16740. ASSERT_FALSE(svr.is_running());
  16741. });
  16742. svr.wait_until_ready();
  16743. Client cli(HOST, port);
  16744. Headers headers;
  16745. headers.emplace("Accept", "text/plain;q=0.5");
  16746. headers.emplace("Accept", "application/json");
  16747. auto res = cli.Get("/", headers);
  16748. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16749. EXPECT_EQ(StatusCode::OK_200, res->status);
  16750. // Sorted by q-value, so the second field line's type comes first
  16751. ASSERT_EQ(2U, observed_types.size());
  16752. EXPECT_EQ("application/json", observed_types[0]);
  16753. EXPECT_EQ("text/plain", observed_types[1]);
  16754. }
  16755. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  16756. // empty field line must not contribute a bare comma to the combined value.
  16757. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  16758. Server svr;
  16759. std::vector<std::string> observed_types;
  16760. svr.Get("/", [&](const Request &req, Response &res) {
  16761. observed_types = req.accept_content_types;
  16762. res.set_content("ok", "text/plain");
  16763. });
  16764. auto port = svr.bind_to_any_port(HOST);
  16765. thread t = thread([&]() { svr.listen_after_bind(); });
  16766. auto se = detail::scope_exit([&] {
  16767. svr.stop();
  16768. t.join();
  16769. ASSERT_FALSE(svr.is_running());
  16770. });
  16771. svr.wait_until_ready();
  16772. // Empty first field line, then a real one
  16773. std::string raw_req = "GET / HTTP/1.1\r\n"
  16774. "Host: localhost\r\n"
  16775. "Accept:\r\n"
  16776. "Accept: application/json\r\n"
  16777. "Connection: close\r\n"
  16778. "\r\n";
  16779. std::string out;
  16780. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  16781. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  16782. ASSERT_EQ(1U, observed_types.size());
  16783. EXPECT_EQ("application/json", observed_types[0]);
  16784. }
  16785. // The skip in get_combined_header_value() is what keeps an empty field line
  16786. // from contributing a bare comma. Only a trailing empty field line exercises
  16787. // it: a leading one is already covered by the "combined is still empty" check,
  16788. // and parse_accept_header() now ignores the empty element either way, so the
  16789. // request-level test above can no longer tell the two apart.
  16790. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  16791. Headers headers;
  16792. headers.emplace("Accept", "text/html");
  16793. headers.emplace("Accept", "");
  16794. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  16795. headers.clear();
  16796. headers.emplace("Accept", "");
  16797. headers.emplace("Accept", "application/json");
  16798. EXPECT_EQ("application/json",
  16799. detail::get_combined_header_value(headers, "Accept"));
  16800. }
  16801. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  16802. // An encoding offered on a later Accept-Encoding field line is still offered.
  16803. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  16804. Server svr;
  16805. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16806. res.set_content(std::string(1024, 'x'), "text/plain");
  16807. });
  16808. auto port = svr.bind_to_any_port(HOST);
  16809. thread t = thread([&]() { svr.listen_after_bind(); });
  16810. auto se = detail::scope_exit([&] {
  16811. svr.stop();
  16812. t.join();
  16813. ASSERT_FALSE(svr.is_running());
  16814. });
  16815. svr.wait_until_ready();
  16816. Client cli(HOST, port);
  16817. cli.set_decompress(false);
  16818. Headers headers;
  16819. headers.emplace("Accept-Encoding", "identity");
  16820. headers.emplace("Accept-Encoding", "gzip");
  16821. auto res = cli.Get("/", headers);
  16822. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16823. EXPECT_EQ(StatusCode::OK_200, res->status);
  16824. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  16825. }
  16826. #endif
  16827. #ifndef _WIN32
  16828. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  16829. Server svr;
  16830. svr.Post("/post", [&](const Request &req, Response &res) {
  16831. res.set_content(req.body, "text/plain");
  16832. });
  16833. svr.Put("/put", [&](const Request &req, Response &res) {
  16834. res.set_content(req.body, "text/plain");
  16835. });
  16836. svr.Patch("/patch", [&](const Request &req, Response &res) {
  16837. res.set_content(req.body, "text/plain");
  16838. });
  16839. svr.Delete("/delete", [&](const Request &req, Response &res) {
  16840. res.set_content(req.body, "text/plain");
  16841. });
  16842. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16843. auto se = detail::scope_exit([&] {
  16844. svr.stop();
  16845. t.join();
  16846. ASSERT_FALSE(svr.is_running());
  16847. });
  16848. svr.wait_until_ready();
  16849. std::string resp;
  16850. // POST without Content-Length
  16851. ASSERT_TRUE(send_request(5,
  16852. "POST /post HTTP/1.1\r\n"
  16853. "Host: localhost\r\n"
  16854. "Connection: close\r\n"
  16855. "\r\n",
  16856. &resp));
  16857. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  16858. // PUT without Content-Length
  16859. resp.clear();
  16860. ASSERT_TRUE(send_request(5,
  16861. "PUT /put HTTP/1.1\r\n"
  16862. "Host: localhost\r\n"
  16863. "Connection: close\r\n"
  16864. "\r\n",
  16865. &resp));
  16866. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  16867. // PATCH without Content-Length
  16868. resp.clear();
  16869. ASSERT_TRUE(send_request(5,
  16870. "PATCH /patch HTTP/1.1\r\n"
  16871. "Host: localhost\r\n"
  16872. "Connection: close\r\n"
  16873. "\r\n",
  16874. &resp));
  16875. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  16876. // DELETE without Content-Length
  16877. resp.clear();
  16878. ASSERT_TRUE(send_request(5,
  16879. "DELETE /delete HTTP/1.1\r\n"
  16880. "Host: localhost\r\n"
  16881. "Connection: close\r\n"
  16882. "\r\n",
  16883. &resp));
  16884. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  16885. }
  16886. #endif
  16887. //==============================================================================
  16888. // open_stream() Tests
  16889. //==============================================================================
  16890. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  16891. std::string result;
  16892. char buf[8192];
  16893. ssize_t n;
  16894. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  16895. result.append(buf, static_cast<size_t>(n));
  16896. }
  16897. return result;
  16898. }
  16899. // Mock stream for unit tests
  16900. class MockStream : public Stream {
  16901. public:
  16902. std::string data;
  16903. size_t pos = 0;
  16904. ssize_t error_after = -1; // -1 = no error
  16905. explicit MockStream(const std::string &d, ssize_t err = -1)
  16906. : data(d), error_after(err) {}
  16907. bool is_readable() const override { return true; }
  16908. bool wait_readable() const override { return true; }
  16909. bool wait_writable() const override { return true; }
  16910. ssize_t read(char *ptr, size_t size) override {
  16911. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  16912. if (pos >= data.size()) return 0;
  16913. size_t limit =
  16914. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  16915. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  16916. std::memcpy(ptr, data.data() + pos, to_read);
  16917. pos += to_read;
  16918. return static_cast<ssize_t>(to_read);
  16919. }
  16920. ssize_t write(const char *, size_t) override { return -1; }
  16921. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  16922. ip = "127.0.0.1";
  16923. port = 0;
  16924. }
  16925. void get_local_ip_and_port(std::string &ip, int &port) const override {
  16926. ip = "127.0.0.1";
  16927. port = 0;
  16928. }
  16929. socket_t socket() const override { return INVALID_SOCKET; }
  16930. time_t duration() const override { return 0; }
  16931. };
  16932. TEST(StreamHandleTest, Basic) {
  16933. ClientImpl::StreamHandle handle;
  16934. EXPECT_FALSE(handle.is_valid());
  16935. handle.response = detail::make_unique<Response>();
  16936. handle.error = Error::Connection;
  16937. EXPECT_FALSE(handle.is_valid());
  16938. handle.error = Error::Success;
  16939. EXPECT_TRUE(handle.is_valid());
  16940. }
  16941. TEST(BodyReaderTest, Basic) {
  16942. MockStream stream("Hello, World!");
  16943. detail::BodyReader reader;
  16944. reader.stream = &stream;
  16945. reader.content_length = 13;
  16946. char buf[32];
  16947. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  16948. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  16949. EXPECT_TRUE(reader.eof);
  16950. }
  16951. TEST(BodyReaderTest, NoStream) {
  16952. detail::BodyReader reader;
  16953. char buf[32];
  16954. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  16955. EXPECT_EQ(Error::Connection, reader.last_error);
  16956. }
  16957. TEST(BodyReaderTest, Error) {
  16958. MockStream stream("Hello, World!", 5);
  16959. detail::BodyReader reader;
  16960. reader.stream = &stream;
  16961. reader.content_length = 13;
  16962. char buf[32];
  16963. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  16964. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  16965. EXPECT_EQ(Error::Read, reader.last_error);
  16966. }
  16967. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  16968. // Mock-based StreamHandle tests relying on private internals are removed.
  16969. class OpenStreamTest : public ::testing::Test {
  16970. protected:
  16971. void SetUp() override {
  16972. svr_.Get("/hello", [](const Request &, Response &res) {
  16973. res.set_content("Hello World!", "text/plain");
  16974. });
  16975. svr_.Get("/large", [](const Request &, Response &res) {
  16976. res.set_content(std::string(10000, 'X'), "text/plain");
  16977. });
  16978. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  16979. res.set_content("Hello World!", "image/jpeg");
  16980. res.set_header("Content-Encoding", "UTF-8");
  16981. });
  16982. svr_.Get("/chunked", [](const Request &, Response &res) {
  16983. res.set_chunked_content_provider("text/plain",
  16984. [](size_t offset, DataSink &sink) {
  16985. if (offset < 15) {
  16986. sink.write("chunk", 5);
  16987. return true;
  16988. }
  16989. sink.done();
  16990. return true;
  16991. });
  16992. });
  16993. svr_.Get("/compressible", [](const Request &, Response &res) {
  16994. res.set_chunked_content_provider("text/plain", [](size_t offset,
  16995. DataSink &sink) {
  16996. if (offset < 100 * 1024) {
  16997. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  16998. sink.write(chunk.data(), chunk.size());
  16999. return true;
  17000. }
  17001. sink.done();
  17002. return true;
  17003. });
  17004. });
  17005. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  17006. [](const Request & /*req*/, Response &res) {
  17007. auto i = new int(0);
  17008. res.set_header("Trailer", "Content-Length, X-Allowed");
  17009. res.set_chunked_content_provider(
  17010. "text/plain",
  17011. [i](size_t /*offset*/, DataSink &sink) {
  17012. switch (*i) {
  17013. case 0: sink.os << "123"; break;
  17014. case 1: sink.os << "456"; break;
  17015. case 2: sink.os << "789"; break;
  17016. case 3: {
  17017. sink.done_with_trailer(
  17018. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  17019. } break;
  17020. }
  17021. (*i)++;
  17022. return true;
  17023. },
  17024. [i](bool success) {
  17025. EXPECT_TRUE(success);
  17026. delete i;
  17027. });
  17028. });
  17029. // Echo headers endpoint for header-related tests
  17030. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  17031. std::string body;
  17032. for (const auto &h : req.headers) {
  17033. body.append(h.first);
  17034. body.push_back(':');
  17035. body.append(h.second);
  17036. body.push_back('\n');
  17037. }
  17038. res.set_content(body, "text/plain");
  17039. });
  17040. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  17041. std::string body;
  17042. for (const auto &h : req.headers) {
  17043. body.append(h.first);
  17044. body.push_back(':');
  17045. body.append(h.second);
  17046. body.push_back('\n');
  17047. }
  17048. res.set_content(body, "text/plain");
  17049. });
  17050. port_ = svr_.bind_to_any_port("127.0.0.1");
  17051. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  17052. svr_.wait_until_ready();
  17053. }
  17054. void TearDown() override {
  17055. svr_.stop();
  17056. if (thread_.joinable()) thread_.join();
  17057. }
  17058. Server svr_;
  17059. std::thread thread_;
  17060. int port_ = 0;
  17061. };
  17062. TEST_F(OpenStreamTest, Basic) {
  17063. Client cli("127.0.0.1", port_);
  17064. auto handle = cli.open_stream("GET", "/hello");
  17065. EXPECT_TRUE(handle.is_valid());
  17066. EXPECT_EQ("Hello World!", read_all(handle));
  17067. }
  17068. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  17069. Client cli("127.0.0.1", port_);
  17070. auto handle = cli.open_stream("GET", "/unknown-encoding");
  17071. ASSERT_TRUE(handle.is_valid());
  17072. EXPECT_EQ("Hello World!", read_all(handle));
  17073. }
  17074. TEST_F(OpenStreamTest, SmallBuffer) {
  17075. Client cli("127.0.0.1", port_);
  17076. auto handle = cli.open_stream("GET", "/hello");
  17077. std::string result;
  17078. char buf[4];
  17079. ssize_t n;
  17080. while ((n = handle.read(buf, sizeof(buf))) > 0)
  17081. result.append(buf, static_cast<size_t>(n));
  17082. EXPECT_EQ("Hello World!", result);
  17083. }
  17084. TEST_F(OpenStreamTest, DefaultHeaders) {
  17085. Client cli("127.0.0.1", port_);
  17086. // open_stream GET should include Host, User-Agent and Accept-Encoding
  17087. {
  17088. auto handle = cli.open_stream("GET", "/echo-headers");
  17089. ASSERT_TRUE(handle.is_valid());
  17090. auto body = read_all(handle);
  17091. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  17092. std::string::npos);
  17093. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  17094. std::string::npos);
  17095. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  17096. }
  17097. // open_stream POST with body and no explicit content_type should NOT add
  17098. // text/plain Content-Type (behavior differs from non-streaming path), but
  17099. // should include Content-Length
  17100. {
  17101. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  17102. ASSERT_TRUE(handle.is_valid());
  17103. auto body = read_all(handle);
  17104. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  17105. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  17106. }
  17107. // open_stream POST with explicit Content-Type should preserve it
  17108. {
  17109. auto handle = cli.open_stream("POST", "/echo-headers", {},
  17110. {{"Content-Type", "application/custom"}},
  17111. "{}", "application/custom");
  17112. ASSERT_TRUE(handle.is_valid());
  17113. auto body = read_all(handle);
  17114. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  17115. }
  17116. // User-specified User-Agent must not be overwritten for stream API
  17117. {
  17118. auto handle = cli.open_stream("GET", "/echo-headers", {},
  17119. {{"User-Agent", "MyAgent/1.2"}});
  17120. ASSERT_TRUE(handle.is_valid());
  17121. auto body = read_all(handle);
  17122. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  17123. }
  17124. }
  17125. TEST_F(OpenStreamTest, Large) {
  17126. Client cli("127.0.0.1", port_);
  17127. auto handle = cli.open_stream("GET", "/large");
  17128. EXPECT_EQ(10000u, read_all(handle).size());
  17129. }
  17130. TEST_F(OpenStreamTest, ConnectionError) {
  17131. Client cli("127.0.0.1", 9999);
  17132. auto handle = cli.open_stream("GET", "/hello");
  17133. EXPECT_FALSE(handle.is_valid());
  17134. }
  17135. TEST_F(OpenStreamTest, Chunked) {
  17136. Client cli("127.0.0.1", port_);
  17137. auto handle = cli.open_stream("GET", "/chunked");
  17138. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  17139. "Transfer-Encoding") == "chunked");
  17140. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  17141. }
  17142. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  17143. Client cli("127.0.0.1", port_);
  17144. auto handle =
  17145. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  17146. ASSERT_TRUE(handle.is_valid());
  17147. // Consume body to allow trailers to be received/parsed
  17148. auto body = read_all(handle);
  17149. // Explicitly parse trailers (ensure trailers are available for assertion)
  17150. handle.parse_trailers_if_needed();
  17151. EXPECT_EQ(std::string("123456789"), body);
  17152. // The response should include a Trailer header declaring both names
  17153. ASSERT_TRUE(handle.response);
  17154. EXPECT_TRUE(handle.response->has_header("Trailer"));
  17155. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  17156. handle.response->get_header_value("Trailer"));
  17157. // Prohibited trailer must not be present
  17158. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  17159. // Allowed trailer should be present
  17160. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  17161. EXPECT_EQ(std::string("yes"),
  17162. handle.response->get_trailer_value("X-Allowed"));
  17163. // Verify trailers are NOT present as regular headers
  17164. EXPECT_EQ(std::string(""),
  17165. handle.response->get_header_value("Content-Length"));
  17166. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  17167. }
  17168. static std::thread serve_single_response(std::promise<int> &port_promise,
  17169. const std::string &response) {
  17170. return std::thread([&port_promise, response] {
  17171. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17172. default_socket_options(srv);
  17173. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  17174. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  17175. sockaddr_in addr{};
  17176. addr.sin_family = AF_INET;
  17177. addr.sin_port = htons(0); // Let OS assign a free port
  17178. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17179. int opt = 1;
  17180. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  17181. #ifdef _WIN32
  17182. reinterpret_cast<const char *>(&opt),
  17183. #else
  17184. &opt,
  17185. #endif
  17186. sizeof(opt));
  17187. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  17188. ::listen(srv, 1) != 0) {
  17189. port_promise.set_value(-1);
  17190. detail::close_socket(srv);
  17191. return;
  17192. }
  17193. socklen_t addr_len = sizeof(addr);
  17194. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  17195. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  17196. sockaddr_in cli_addr{};
  17197. socklen_t cli_len = sizeof(cli_addr);
  17198. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17199. if (cli != INVALID_SOCKET) {
  17200. // Read the complete HTTP request (until the blank line that terminates
  17201. // headers) before sending the response. If the server closes the socket
  17202. // while the client's request data is still unread in the kernel receive
  17203. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  17204. // connection on both sides: it discards the client's receive buffer
  17205. // (which already holds our response) and causes any in-progress write on
  17206. // the client to fail with ECONNRESET. Reading all request data first
  17207. // ensures close() emits a graceful FIN.
  17208. {
  17209. char rbuf[256];
  17210. std::string req;
  17211. while (req.find("\r\n\r\n") == std::string::npos) {
  17212. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  17213. if (n <= 0) { break; }
  17214. req.append(rbuf, static_cast<size_t>(n));
  17215. }
  17216. }
  17217. ::send(cli,
  17218. #ifdef _WIN32
  17219. static_cast<const char *>(response.c_str()),
  17220. static_cast<int>(response.size()),
  17221. #else
  17222. response.c_str(), response.size(),
  17223. #endif
  17224. 0);
  17225. detail::close_socket(cli);
  17226. }
  17227. detail::close_socket(srv);
  17228. });
  17229. }
  17230. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  17231. #ifndef _WIN32
  17232. signal(SIGPIPE, SIG_IGN);
  17233. #endif
  17234. std::promise<int> port_promise;
  17235. auto port_future = port_promise.get_future();
  17236. auto server_thread =
  17237. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  17238. "Content-Type: text/plain\r\n"
  17239. "Content-Length: not-a-number\r\n"
  17240. "Connection: close\r\n"
  17241. "\r\n"
  17242. "hello");
  17243. auto port = port_future.get();
  17244. ASSERT_GT(port, 0);
  17245. Client cli("127.0.0.1", port);
  17246. auto handle = cli.open_stream("GET", "/");
  17247. EXPECT_FALSE(handle.is_valid());
  17248. server_thread.join();
  17249. }
  17250. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  17251. #ifndef _WIN32
  17252. signal(SIGPIPE, SIG_IGN);
  17253. #endif
  17254. std::promise<int> port_promise;
  17255. auto port_future = port_promise.get_future();
  17256. auto server_thread = serve_single_response(
  17257. port_promise, "HTTP/1.1 200 OK\r\n"
  17258. "Content-Type: text/plain\r\n"
  17259. "Content-Length: 99999999999999999999999999\r\n"
  17260. "Connection: close\r\n"
  17261. "\r\n"
  17262. "hello");
  17263. auto port = port_future.get();
  17264. ASSERT_GT(port, 0);
  17265. // Historically std::stoull would throw std::out_of_range here and crash
  17266. // the process, then parsing silently clamped to a bogus framing length and
  17267. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  17268. // so the stream fails to open, matching the not-a-number case above. The
  17269. // process still must NOT terminate.
  17270. Client cli("127.0.0.1", port);
  17271. auto handle = cli.open_stream("GET", "/");
  17272. EXPECT_FALSE(handle.is_valid());
  17273. server_thread.join();
  17274. }
  17275. // Serves `response` to the single request `fn` makes with a fresh client.
  17276. template <typename Fn>
  17277. static void with_single_response(const std::string &response, Fn fn) {
  17278. #ifndef _WIN32
  17279. signal(SIGPIPE, SIG_IGN);
  17280. #endif
  17281. std::promise<int> port_promise;
  17282. auto port_future = port_promise.get_future();
  17283. auto server_thread = serve_single_response(port_promise, response);
  17284. auto se = detail::scope_exit([&] { server_thread.join(); });
  17285. auto port = port_future.get();
  17286. ASSERT_GT(port, 0);
  17287. Client cli("127.0.0.1", port);
  17288. fn(cli);
  17289. }
  17290. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  17291. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  17292. // the chunked coding and drop Content-Length, so a front-end that trusts
  17293. // Content-Length would disagree about where the body ends (response
  17294. // smuggling). The client must reject such a response.
  17295. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  17296. for (const char *te : {"chunked", "gzip, chunked"}) {
  17297. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  17298. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  17299. "\r\n" + "Connection: close\r\n" + "\r\n" +
  17300. "5\r\nhello\r\n0\r\n\r\n";
  17301. with_single_response(response, [&](Client &cli) {
  17302. auto res = cli.Get("/");
  17303. EXPECT_FALSE(static_cast<bool>(res)) << te;
  17304. EXPECT_EQ(Error::Read, res.error()) << te;
  17305. });
  17306. with_single_response(response, [&](Client &cli) {
  17307. auto handle = cli.open_stream("GET", "/");
  17308. EXPECT_FALSE(handle.is_valid()) << te;
  17309. EXPECT_EQ(Error::Read, handle.error) << te;
  17310. });
  17311. }
  17312. }
  17313. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  17314. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  17315. // closing the connection (unlike a request, which must be rejected).
  17316. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  17317. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  17318. "Transfer-Encoding: chunked\r\n"
  17319. "Connection: close\r\n"
  17320. "\r\n"
  17321. "5\r\nhello\r\n0\r\n\r\n",
  17322. "HTTP/1.1 200 OK\r\n"
  17323. "Transfer-Encoding: gzip\r\n"
  17324. "Connection: close\r\n"
  17325. "\r\n"
  17326. "hello"}) {
  17327. with_single_response(response, [&](Client &cli) {
  17328. auto res = cli.Get("/");
  17329. ASSERT_TRUE(static_cast<bool>(res)) << response;
  17330. EXPECT_EQ("hello", res->body);
  17331. });
  17332. with_single_response(response, [&](Client &cli) {
  17333. auto handle = cli.open_stream("GET", "/");
  17334. ASSERT_TRUE(handle.is_valid()) << response;
  17335. EXPECT_EQ("hello", read_all(handle));
  17336. });
  17337. }
  17338. }
  17339. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  17340. // framing headers describe nothing to read and must not be rejected.
  17341. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  17342. const std::string framing = "Content-Length: 5\r\n"
  17343. "Transfer-Encoding: chunked\r\n"
  17344. "Connection: close\r\n"
  17345. "\r\n";
  17346. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  17347. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  17348. });
  17349. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  17350. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  17351. });
  17352. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  17353. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  17354. with_single_response(response, [&](Client &cli) {
  17355. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  17356. });
  17357. with_single_response(response, [&](Client &cli) {
  17358. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  17359. });
  17360. }
  17361. }
  17362. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  17363. TEST_F(OpenStreamTest, Gzip) {
  17364. Client cli("127.0.0.1", port_);
  17365. auto handle = cli.open_stream("GET", "/compressible", {},
  17366. {{"Accept-Encoding", "gzip"}});
  17367. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  17368. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  17369. }
  17370. #endif
  17371. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  17372. TEST_F(OpenStreamTest, Brotli) {
  17373. Client cli("127.0.0.1", port_);
  17374. auto handle =
  17375. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  17376. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  17377. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  17378. }
  17379. #endif
  17380. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  17381. TEST_F(OpenStreamTest, Zstd) {
  17382. Client cli("127.0.0.1", port_);
  17383. auto handle = cli.open_stream("GET", "/compressible", {},
  17384. {{"Accept-Encoding", "zstd"}});
  17385. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  17386. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  17387. }
  17388. #endif
  17389. #ifdef CPPHTTPLIB_SSL_ENABLED
  17390. class SSLOpenStreamTest : public ::testing::Test {
  17391. protected:
  17392. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  17393. void SetUp() override {
  17394. svr_.Get("/hello", [](const Request &, Response &res) {
  17395. res.set_content("Hello SSL World!", "text/plain");
  17396. });
  17397. svr_.Get("/chunked", [](const Request &, Response &res) {
  17398. res.set_chunked_content_provider("text/plain",
  17399. [](size_t offset, DataSink &sink) {
  17400. if (offset < 15) {
  17401. sink.write("chunk", 5);
  17402. return true;
  17403. }
  17404. sink.done();
  17405. return true;
  17406. });
  17407. });
  17408. svr_.Post("/echo", [](const Request &req, Response &res) {
  17409. res.set_content(req.body, req.get_header_value("Content-Type"));
  17410. });
  17411. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  17412. std::string body = req.body;
  17413. res.set_chunked_content_provider(
  17414. "text/plain", [body](size_t offset, DataSink &sink) {
  17415. if (offset < body.size()) {
  17416. sink.write(body.data() + offset, body.size() - offset);
  17417. }
  17418. sink.done();
  17419. return true;
  17420. });
  17421. });
  17422. port_ = svr_.bind_to_any_port("127.0.0.1");
  17423. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  17424. svr_.wait_until_ready();
  17425. }
  17426. void TearDown() override {
  17427. svr_.stop();
  17428. if (thread_.joinable()) thread_.join();
  17429. }
  17430. SSLServer svr_;
  17431. std::thread thread_;
  17432. int port_ = 0;
  17433. };
  17434. TEST_F(SSLOpenStreamTest, Basic) {
  17435. SSLClient cli("127.0.0.1", port_);
  17436. cli.enable_server_certificate_verification(false);
  17437. auto handle = cli.open_stream("GET", "/hello");
  17438. ASSERT_TRUE(handle.is_valid());
  17439. EXPECT_EQ("Hello SSL World!", read_all(handle));
  17440. }
  17441. TEST_F(SSLOpenStreamTest, Chunked) {
  17442. SSLClient cli("127.0.0.1", port_);
  17443. cli.enable_server_certificate_verification(false);
  17444. auto handle = cli.open_stream("GET", "/chunked");
  17445. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  17446. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  17447. "Transfer-Encoding") == "chunked");
  17448. auto body = read_all(handle);
  17449. EXPECT_EQ("chunkchunkchunk", body);
  17450. }
  17451. TEST_F(SSLOpenStreamTest, Post) {
  17452. SSLClient cli("127.0.0.1", port_);
  17453. cli.enable_server_certificate_verification(false);
  17454. auto handle =
  17455. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  17456. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  17457. EXPECT_EQ(200, handle.response->status);
  17458. auto body = read_all(handle);
  17459. EXPECT_EQ("Hello SSL POST", body);
  17460. }
  17461. TEST_F(SSLOpenStreamTest, PostChunked) {
  17462. SSLClient cli("127.0.0.1", port_);
  17463. cli.enable_server_certificate_verification(false);
  17464. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  17465. "Chunked SSL Data", "text/plain");
  17466. ASSERT_TRUE(handle.is_valid());
  17467. EXPECT_EQ(200, handle.response->status);
  17468. auto body = read_all(handle);
  17469. EXPECT_EQ("Chunked SSL Data", body);
  17470. }
  17471. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  17472. // Content-Length is terminated by the server closing the connection. When the
  17473. // SSL peer sends a close_notify after the body, the client must treat it as a
  17474. // clean EOF and return a successful response rather than an error.
  17475. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  17476. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17477. ASSERT_TRUE(svr.is_valid());
  17478. svr.set_keep_alive_max_count(1);
  17479. const std::string expected_body = "Hello from connection-close response!";
  17480. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  17481. res.set_content_provider("text/plain",
  17482. [&](size_t offset, DataSink &sink) -> bool {
  17483. if (offset < expected_body.size()) {
  17484. sink.write(expected_body.data() + offset,
  17485. expected_body.size() - offset);
  17486. }
  17487. sink.done();
  17488. return true;
  17489. });
  17490. });
  17491. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  17492. auto se = detail::scope_exit([&] {
  17493. svr.stop();
  17494. listen_thread.join();
  17495. ASSERT_FALSE(svr.is_running());
  17496. });
  17497. svr.wait_until_ready();
  17498. SSLClient cli(HOST, PORT);
  17499. cli.enable_server_certificate_verification(false);
  17500. auto res = cli.Get("/no-content-length");
  17501. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  17502. EXPECT_EQ(StatusCode::OK_200, res->status);
  17503. EXPECT_EQ(expected_body, res->body);
  17504. }
  17505. #endif // CPPHTTPLIB_SSL_ENABLED
  17506. //==============================================================================
  17507. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  17508. // results for various scenarios.
  17509. //==============================================================================
  17510. TEST(ParityTest, GetVsOpenStream) {
  17511. Server svr;
  17512. const std::string path = "/parity";
  17513. const std::string content = "Parity test content: hello world";
  17514. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  17515. res.set_content(content, "text/plain");
  17516. });
  17517. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17518. auto se = detail::scope_exit([&] {
  17519. svr.stop();
  17520. t.join();
  17521. ASSERT_FALSE(svr.is_running());
  17522. });
  17523. svr.wait_until_ready();
  17524. Client cli(HOST, PORT);
  17525. // Non-stream path
  17526. auto r1 = cli.Get(path);
  17527. ASSERT_TRUE(r1);
  17528. EXPECT_EQ(StatusCode::OK_200, r1->status);
  17529. // Stream path
  17530. auto h = cli.open_stream("GET", path);
  17531. ASSERT_TRUE(h.is_valid());
  17532. EXPECT_EQ(r1->body, read_all(h));
  17533. }
  17534. // Helper to compress data with provided compressor type T
  17535. template <typename Compressor>
  17536. static std::string compress_payload_for_parity(const std::string &in) {
  17537. std::string out;
  17538. Compressor compressor;
  17539. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  17540. [&](const char *data, size_t n) {
  17541. out.append(data, n);
  17542. return true;
  17543. });
  17544. EXPECT_TRUE(ok);
  17545. return out;
  17546. }
  17547. // Helper function for compression parity tests
  17548. template <typename Compressor>
  17549. static void test_compression_parity(const std::string &original,
  17550. const std::string &path,
  17551. const std::string &encoding) {
  17552. const std::string compressed =
  17553. compress_payload_for_parity<Compressor>(original);
  17554. Server svr;
  17555. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  17556. res.set_content(compressed, "application/octet-stream");
  17557. res.set_header("Content-Encoding", encoding);
  17558. });
  17559. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  17560. auto se = detail::scope_exit([&] {
  17561. svr.stop();
  17562. t.join();
  17563. ASSERT_FALSE(svr.is_running());
  17564. });
  17565. svr.wait_until_ready();
  17566. Client cli(HOST, PORT);
  17567. // Non-streaming
  17568. {
  17569. auto res = cli.Get(path);
  17570. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17571. EXPECT_EQ(StatusCode::OK_200, res->status);
  17572. EXPECT_EQ(original, res->body);
  17573. }
  17574. // Streaming
  17575. {
  17576. auto h = cli.open_stream("GET", path);
  17577. ASSERT_TRUE(h.is_valid());
  17578. EXPECT_EQ(original, read_all(h));
  17579. }
  17580. }
  17581. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  17582. TEST(ParityTest, Gzip) {
  17583. test_compression_parity<detail::gzip_compressor>(
  17584. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  17585. }
  17586. #endif
  17587. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  17588. TEST(ParityTest, Brotli) {
  17589. test_compression_parity<detail::brotli_compressor>(
  17590. "Hello, brotli parity test payload", "/parity-br", "br");
  17591. }
  17592. #endif
  17593. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  17594. TEST(ParityTest, Zstd) {
  17595. test_compression_parity<detail::zstd_compressor>(
  17596. "Zstandard parity test payload", "/parity-zstd", "zstd");
  17597. }
  17598. #endif
  17599. //==============================================================================
  17600. // New Stream API Tests
  17601. //==============================================================================
  17602. inline std::string read_body(httplib::stream::Result &result) {
  17603. std::string body;
  17604. while (result.next()) {
  17605. body.append(result.data(), result.size());
  17606. }
  17607. return body;
  17608. }
  17609. TEST(ClientConnectionTest, Basic) {
  17610. httplib::ClientConnection conn;
  17611. EXPECT_FALSE(conn.is_open());
  17612. conn.sock = 1;
  17613. EXPECT_TRUE(conn.is_open());
  17614. httplib::ClientConnection conn2(std::move(conn));
  17615. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  17616. conn2.sock = INVALID_SOCKET;
  17617. }
  17618. // Unified test server for all stream::* tests
  17619. class StreamApiTest : public ::testing::Test {
  17620. protected:
  17621. void SetUp() override {
  17622. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  17623. res.set_content("Hello World!", "text/plain");
  17624. });
  17625. svr_.Get("/echo-params",
  17626. [](const httplib::Request &req, httplib::Response &res) {
  17627. std::string r;
  17628. for (const auto &p : req.params) {
  17629. if (!r.empty()) r += "&";
  17630. r += p.first + "=" + p.second;
  17631. }
  17632. res.set_content(r, "text/plain");
  17633. });
  17634. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  17635. res.set_content(req.body, req.get_header_value("Content-Type"));
  17636. });
  17637. svr_.Post("/echo-headers",
  17638. [](const httplib::Request &req, httplib::Response &res) {
  17639. std::string r;
  17640. for (const auto &h : req.headers)
  17641. r += h.first + ": " + h.second + "\n";
  17642. res.set_content(r, "text/plain");
  17643. });
  17644. svr_.Post("/echo-params",
  17645. [](const httplib::Request &req, httplib::Response &res) {
  17646. std::string r = "params:";
  17647. for (const auto &p : req.params)
  17648. r += p.first + "=" + p.second + ";";
  17649. res.set_content(r + " body:" + req.body, "text/plain");
  17650. });
  17651. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  17652. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  17653. });
  17654. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  17655. res.set_content("PUT:" + req.body, "text/plain");
  17656. });
  17657. svr_.Patch("/echo",
  17658. [](const httplib::Request &req, httplib::Response &res) {
  17659. res.set_content("PATCH:" + req.body, "text/plain");
  17660. });
  17661. svr_.Delete(
  17662. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  17663. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  17664. "text/plain");
  17665. });
  17666. svr_.Get("/head-test",
  17667. [](const httplib::Request &, httplib::Response &res) {
  17668. res.set_content("body for HEAD", "text/plain");
  17669. });
  17670. svr_.Options("/options",
  17671. [](const httplib::Request &, httplib::Response &res) {
  17672. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  17673. });
  17674. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  17675. svr_.wait_until_ready();
  17676. }
  17677. void TearDown() override {
  17678. svr_.stop();
  17679. if (thread_.joinable()) thread_.join();
  17680. }
  17681. httplib::Server svr_;
  17682. std::thread thread_;
  17683. };
  17684. // stream::Get tests
  17685. TEST_F(StreamApiTest, GetBasic) {
  17686. httplib::Client cli(HOST, PORT);
  17687. auto result = httplib::stream::Get(cli, "/hello");
  17688. ASSERT_TRUE(result.is_valid());
  17689. EXPECT_EQ(200, result.status());
  17690. EXPECT_EQ("Hello World!", read_body(result));
  17691. }
  17692. TEST_F(StreamApiTest, GetWithParams) {
  17693. httplib::Client cli(HOST, PORT);
  17694. httplib::Params params{{"foo", "bar"}};
  17695. auto result = httplib::stream::Get(cli, "/echo-params", params);
  17696. ASSERT_TRUE(result.is_valid());
  17697. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  17698. }
  17699. TEST_F(StreamApiTest, GetConnectionError) {
  17700. httplib::Client cli(HOST, 9999);
  17701. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  17702. }
  17703. TEST_F(StreamApiTest, Get404) {
  17704. httplib::Client cli(HOST, PORT);
  17705. auto result = httplib::stream::Get(cli, "/nonexistent");
  17706. EXPECT_TRUE(result.is_valid());
  17707. EXPECT_EQ(404, result.status());
  17708. }
  17709. // stream::Post tests
  17710. TEST_F(StreamApiTest, PostBasic) {
  17711. httplib::Client cli(HOST, PORT);
  17712. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  17713. "application/json");
  17714. ASSERT_TRUE(result.is_valid());
  17715. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  17716. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  17717. }
  17718. TEST_F(StreamApiTest, PostWithHeaders) {
  17719. httplib::Client cli(HOST, PORT);
  17720. httplib::Headers headers{{"X-Custom", "value"}};
  17721. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  17722. "text/plain");
  17723. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  17724. }
  17725. TEST_F(StreamApiTest, PostWithParams) {
  17726. httplib::Client cli(HOST, PORT);
  17727. httplib::Params params{{"k", "v"}};
  17728. auto result =
  17729. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  17730. auto body = read_body(result);
  17731. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  17732. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  17733. }
  17734. TEST_F(StreamApiTest, PostLarge) {
  17735. httplib::Client cli(HOST, PORT);
  17736. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  17737. size_t total = 0;
  17738. while (result.next()) {
  17739. total += result.size();
  17740. }
  17741. EXPECT_EQ(100u * 1024u, total);
  17742. }
  17743. // stream::Put/Patch tests
  17744. TEST_F(StreamApiTest, PutAndPatch) {
  17745. httplib::Client cli(HOST, PORT);
  17746. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  17747. EXPECT_EQ("PUT:test", read_body(put));
  17748. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  17749. EXPECT_EQ("PATCH:test", read_body(patch));
  17750. }
  17751. // stream::Delete tests
  17752. TEST_F(StreamApiTest, Delete) {
  17753. httplib::Client cli(HOST, PORT);
  17754. auto del1 = httplib::stream::Delete(cli, "/resource");
  17755. EXPECT_EQ("Deleted", read_body(del1));
  17756. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  17757. EXPECT_EQ("Deleted:data", read_body(del2));
  17758. }
  17759. // stream::Head/Options tests
  17760. TEST_F(StreamApiTest, HeadAndOptions) {
  17761. httplib::Client cli(HOST, PORT);
  17762. auto head = httplib::stream::Head(cli, "/head-test");
  17763. EXPECT_TRUE(head.is_valid());
  17764. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  17765. auto opts = httplib::stream::Options(cli, "/options");
  17766. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  17767. }
  17768. // SSL stream::* tests
  17769. #ifdef CPPHTTPLIB_SSL_ENABLED
  17770. class SSLStreamApiTest : public ::testing::Test {
  17771. protected:
  17772. void SetUp() override {
  17773. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  17774. res.set_content("Hello SSL!", "text/plain");
  17775. });
  17776. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  17777. res.set_content(req.body, "text/plain");
  17778. });
  17779. port_ = svr_.bind_to_any_port("127.0.0.1");
  17780. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  17781. svr_.wait_until_ready();
  17782. }
  17783. void TearDown() override {
  17784. svr_.stop();
  17785. if (thread_.joinable()) thread_.join();
  17786. }
  17787. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  17788. std::thread thread_;
  17789. int port_ = 0;
  17790. };
  17791. TEST_F(SSLStreamApiTest, GetAndPost) {
  17792. httplib::SSLClient cli("127.0.0.1", port_);
  17793. cli.enable_server_certificate_verification(false);
  17794. auto get = httplib::stream::Get(cli, "/hello");
  17795. EXPECT_EQ("Hello SSL!", read_body(get));
  17796. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  17797. EXPECT_EQ("test", read_body(post));
  17798. }
  17799. #endif
  17800. // Tests for Error::Timeout and Error::ConnectionClosed error types
  17801. // These errors are set in SocketStream/SSLSocketStream and propagated through
  17802. // BodyReader
  17803. TEST(ErrorHandlingTest, StreamReadTimeout) {
  17804. // Test that read timeout during streaming is detected
  17805. // Use a large content-length response where server delays mid-stream
  17806. Server svr;
  17807. svr.Get("/slow-stream", [](const Request &, Response &res) {
  17808. // Send a large response with delay in the middle
  17809. res.set_content_provider(
  17810. 1000, // content_length
  17811. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  17812. if (offset < 100) {
  17813. // Send first 100 bytes immediately
  17814. std::string data(100, 'A');
  17815. sink.write(data.c_str(), data.size());
  17816. return true;
  17817. }
  17818. // Then delay longer than client timeout
  17819. std::this_thread::sleep_for(std::chrono::seconds(3));
  17820. std::string data(900, 'B');
  17821. sink.write(data.c_str(), data.size());
  17822. return true;
  17823. });
  17824. });
  17825. auto port = 8091;
  17826. std::thread t([&]() { svr.listen("localhost", port); });
  17827. svr.wait_until_ready();
  17828. Client cli("localhost", port);
  17829. cli.set_read_timeout(1, 0); // 1 second timeout
  17830. auto handle = cli.open_stream("GET", "/slow-stream");
  17831. ASSERT_TRUE(handle.is_valid());
  17832. char buf[256];
  17833. ssize_t total = 0;
  17834. ssize_t n;
  17835. bool got_error = false;
  17836. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  17837. total += n;
  17838. }
  17839. if (n < 0) {
  17840. got_error = true;
  17841. // Should be timeout or read error
  17842. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  17843. handle.get_read_error() == Error::Read)
  17844. << "Actual error: " << to_string(handle.get_read_error());
  17845. }
  17846. // Either we got an error, or we got less data than expected
  17847. EXPECT_TRUE(got_error || total < 1000)
  17848. << "Expected timeout but got all " << total << " bytes";
  17849. svr.stop();
  17850. t.join();
  17851. }
  17852. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  17853. // Test connection closed detection via BodyReader
  17854. Server svr;
  17855. std::atomic<bool> close_now{false};
  17856. svr.Get("/will-close", [&](const Request &, Response &res) {
  17857. res.set_content_provider(
  17858. 10000, // Large content_length that we won't fully send
  17859. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  17860. if (offset < 100) {
  17861. std::string data(100, 'X');
  17862. sink.write(data.c_str(), data.size());
  17863. return true;
  17864. }
  17865. // Wait for signal then abort
  17866. while (!close_now) {
  17867. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  17868. }
  17869. return false; // Abort - server will close connection
  17870. });
  17871. });
  17872. auto port = 8092;
  17873. std::thread t([&]() { svr.listen("localhost", port); });
  17874. svr.wait_until_ready();
  17875. Client cli("localhost", port);
  17876. auto handle = cli.open_stream("GET", "/will-close");
  17877. ASSERT_TRUE(handle.is_valid());
  17878. char buf[256];
  17879. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  17880. EXPECT_GT(n, 0) << "First read should succeed";
  17881. // Signal server to close
  17882. close_now = true;
  17883. // Keep reading until error or EOF
  17884. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  17885. // Keep reading
  17886. }
  17887. // Should get an error since content_length wasn't satisfied
  17888. if (n < 0) {
  17889. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  17890. handle.get_read_error() == Error::Read)
  17891. << "Actual error: " << to_string(handle.get_read_error());
  17892. }
  17893. svr.stop();
  17894. t.join();
  17895. }
  17896. #ifdef CPPHTTPLIB_SSL_ENABLED
  17897. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  17898. // Test that read timeout during SSL streaming is detected
  17899. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17900. svr.Get("/slow-stream", [](const Request &, Response &res) {
  17901. res.set_content_provider(
  17902. 1000, "text/plain",
  17903. [](size_t offset, size_t /*length*/, DataSink &sink) {
  17904. if (offset < 100) {
  17905. std::string data(100, 'A');
  17906. sink.write(data.c_str(), data.size());
  17907. return true;
  17908. }
  17909. std::this_thread::sleep_for(std::chrono::seconds(3));
  17910. std::string data(900, 'B');
  17911. sink.write(data.c_str(), data.size());
  17912. return true;
  17913. });
  17914. });
  17915. auto port = 8093;
  17916. std::thread t([&]() { svr.listen("localhost", port); });
  17917. svr.wait_until_ready();
  17918. SSLClient cli("localhost", port);
  17919. cli.enable_server_certificate_verification(false);
  17920. cli.set_read_timeout(1, 0); // 1 second timeout
  17921. auto handle = cli.open_stream("GET", "/slow-stream");
  17922. ASSERT_TRUE(handle.is_valid());
  17923. char buf[256];
  17924. ssize_t total = 0;
  17925. ssize_t n;
  17926. bool got_error = false;
  17927. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  17928. total += n;
  17929. }
  17930. if (n < 0) {
  17931. got_error = true;
  17932. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  17933. handle.get_read_error() == Error::Read)
  17934. << "Actual error: " << to_string(handle.get_read_error());
  17935. }
  17936. EXPECT_TRUE(got_error || total < 1000)
  17937. << "Expected timeout but got all " << total << " bytes";
  17938. svr.stop();
  17939. t.join();
  17940. }
  17941. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  17942. // Test SSL connection closed detection
  17943. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17944. std::atomic<bool> close_now{false};
  17945. svr.Get("/will-close", [&](const Request &, Response &res) {
  17946. res.set_content_provider(
  17947. 10000, "text/plain",
  17948. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  17949. if (offset < 100) {
  17950. std::string data(100, 'X');
  17951. sink.write(data.c_str(), data.size());
  17952. return true;
  17953. }
  17954. while (!close_now) {
  17955. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  17956. }
  17957. return false;
  17958. });
  17959. });
  17960. auto port = 8094;
  17961. std::thread t([&]() { svr.listen("localhost", port); });
  17962. svr.wait_until_ready();
  17963. SSLClient cli("localhost", port);
  17964. cli.enable_server_certificate_verification(false);
  17965. auto handle = cli.open_stream("GET", "/will-close");
  17966. ASSERT_TRUE(handle.is_valid());
  17967. char buf[256];
  17968. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  17969. EXPECT_GT(n, 0);
  17970. // Signal server to close
  17971. close_now = true;
  17972. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  17973. // Keep reading
  17974. }
  17975. if (n < 0) {
  17976. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  17977. handle.get_read_error() == Error::Read)
  17978. << "Actual error: " << to_string(handle.get_read_error());
  17979. }
  17980. svr.stop();
  17981. t.join();
  17982. }
  17983. #endif
  17984. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  17985. using namespace httplib;
  17986. // Create a test file
  17987. const char *fname = "etag_testfile.txt";
  17988. const char *content = "etag-content";
  17989. {
  17990. std::ofstream ofs(fname);
  17991. ofs << content;
  17992. ASSERT_TRUE(ofs.good());
  17993. }
  17994. Server svr;
  17995. svr.set_mount_point("/static", ".");
  17996. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  17997. svr.wait_until_ready();
  17998. Client cli(HOST, PORT);
  17999. // First request: should get 200 with ETag header
  18000. auto res1 = cli.Get("/static/etag_testfile.txt");
  18001. ASSERT_TRUE(res1);
  18002. ASSERT_EQ(200, res1->status);
  18003. ASSERT_TRUE(res1->has_header("ETag"));
  18004. std::string etag = res1->get_header_value("ETag");
  18005. EXPECT_FALSE(etag.empty());
  18006. // Verify ETag format: W/"hex-hex"
  18007. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  18008. EXPECT_EQ('W', etag[0]);
  18009. EXPECT_EQ('/', etag[1]);
  18010. EXPECT_EQ('"', etag[2]);
  18011. EXPECT_EQ('"', etag.back());
  18012. // Exact match: expect 304 Not Modified
  18013. Headers h2 = {{"If-None-Match", etag}};
  18014. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  18015. ASSERT_TRUE(res2);
  18016. EXPECT_EQ(304, res2->status);
  18017. // Wildcard match: expect 304 Not Modified
  18018. Headers h3 = {{"If-None-Match", "*"}};
  18019. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  18020. ASSERT_TRUE(res3);
  18021. EXPECT_EQ(304, res3->status);
  18022. // Non-matching ETag: expect 200
  18023. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  18024. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  18025. ASSERT_TRUE(res4);
  18026. EXPECT_EQ(200, res4->status);
  18027. // Multiple ETags with one matching: expect 304
  18028. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  18029. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  18030. ASSERT_TRUE(res5);
  18031. EXPECT_EQ(304, res5->status);
  18032. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  18033. // that equivalent to the single comma-separated list above, so the match on
  18034. // the second line must still be found.
  18035. Headers h6;
  18036. h6.emplace("If-None-Match", "W/\"other\"");
  18037. h6.emplace("If-None-Match", etag);
  18038. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  18039. ASSERT_TRUE(res6);
  18040. EXPECT_EQ(304, res6->status);
  18041. svr.stop();
  18042. t.join();
  18043. std::remove(fname);
  18044. }
  18045. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  18046. using namespace httplib;
  18047. Server svr;
  18048. svr.set_mount_point("/static", ".");
  18049. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18050. svr.wait_until_ready();
  18051. Client cli(HOST, PORT);
  18052. // Send If-None-Match: * to a non-existent file
  18053. Headers h = {{"If-None-Match", "*"}};
  18054. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  18055. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18056. EXPECT_EQ(404, res->status);
  18057. svr.stop();
  18058. t.join();
  18059. }
  18060. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  18061. using namespace httplib;
  18062. // Create a test file
  18063. const char *fname = "etag_boundary_testfile.txt";
  18064. const char *content = "boundary-test";
  18065. {
  18066. std::ofstream ofs(fname);
  18067. ofs << content;
  18068. ASSERT_TRUE(ofs.good());
  18069. }
  18070. Server svr;
  18071. svr.set_mount_point("/static", ".");
  18072. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  18073. svr.wait_until_ready();
  18074. Client cli(HOST, PORT);
  18075. // Get the actual ETag
  18076. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  18077. ASSERT_TRUE(res1);
  18078. ASSERT_EQ(200, res1->status);
  18079. ASSERT_TRUE(res1->has_header("ETag"));
  18080. std::string etag = res1->get_header_value("ETag");
  18081. // Test 1: Very long ETag value (longer than actual ETag)
  18082. // Should NOT match and return 200 (not trigger out-of-bounds read)
  18083. Headers h1 = {{"If-None-Match", "W/"
  18084. "\"very-long-etag-value-that-is-much-longer-"
  18085. "than-the-actual-etag-value\""}};
  18086. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  18087. ASSERT_TRUE(res2);
  18088. EXPECT_EQ(200, res2->status); // Should not match
  18089. // Test 2: Long string followed by wildcard
  18090. // Should match on "*" and return 304 (without out-of-bounds read on the long
  18091. // string)
  18092. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  18093. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  18094. ASSERT_TRUE(res3);
  18095. EXPECT_EQ(304, res3->status); // Should match on "*"
  18096. // Test 3: Wildcard followed by long string
  18097. // Should match on "*" immediately and return 304
  18098. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  18099. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  18100. ASSERT_TRUE(res4);
  18101. EXPECT_EQ(304, res4->status); // Should match on "*"
  18102. // Test 4: Multiple long non-matching values
  18103. // Should NOT match and return 200 (test that all comparisons are safe)
  18104. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  18105. "W/\"second-long-non-matching-value\", "
  18106. "W/\"third-long-non-matching-value\""}};
  18107. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  18108. ASSERT_TRUE(res5);
  18109. EXPECT_EQ(200, res5->status); // Should not match
  18110. // Test 5: Single character that is not "*" (edge case)
  18111. Headers h5 = {{"If-None-Match", "X"}};
  18112. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  18113. ASSERT_TRUE(res6);
  18114. EXPECT_EQ(200, res6->status); // Should not match
  18115. svr.stop();
  18116. t.join();
  18117. std::remove(fname);
  18118. }
  18119. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  18120. using namespace httplib;
  18121. // Create a test file
  18122. const char *fname = "ims_testfile.txt";
  18123. const char *content = "if-modified-since-test";
  18124. {
  18125. std::ofstream ofs(fname);
  18126. ofs << content;
  18127. ASSERT_TRUE(ofs.good());
  18128. }
  18129. Server svr;
  18130. svr.set_mount_point("/static", ".");
  18131. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18132. svr.wait_until_ready();
  18133. Client cli(HOST, PORT);
  18134. // First request: should get 200 with Last-Modified header
  18135. auto res1 = cli.Get("/static/ims_testfile.txt");
  18136. ASSERT_TRUE(res1);
  18137. ASSERT_EQ(200, res1->status);
  18138. ASSERT_TRUE(res1->has_header("Last-Modified"));
  18139. std::string last_modified = res1->get_header_value("Last-Modified");
  18140. EXPECT_FALSE(last_modified.empty());
  18141. // If-Modified-Since with same time: expect 304
  18142. Headers h2 = {{"If-Modified-Since", last_modified}};
  18143. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  18144. ASSERT_TRUE(res2);
  18145. EXPECT_EQ(304, res2->status);
  18146. // If-Modified-Since with future time: expect 304
  18147. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  18148. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  18149. ASSERT_TRUE(res3);
  18150. EXPECT_EQ(304, res3->status);
  18151. // If-Modified-Since with past time: expect 200
  18152. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  18153. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  18154. ASSERT_TRUE(res4);
  18155. EXPECT_EQ(200, res4->status);
  18156. // If-None-Match takes precedence over If-Modified-Since
  18157. // (send matching ETag with old If-Modified-Since -> should still be 304)
  18158. ASSERT_TRUE(res1->has_header("ETag"));
  18159. std::string etag = res1->get_header_value("ETag");
  18160. Headers h5 = {{"If-None-Match", etag},
  18161. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  18162. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  18163. ASSERT_TRUE(res5);
  18164. EXPECT_EQ(304, res5->status);
  18165. svr.stop();
  18166. t.join();
  18167. std::remove(fname);
  18168. }
  18169. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  18170. using namespace httplib;
  18171. Server svr;
  18172. // Endpoint that returns compressible content
  18173. svr.Get("/compressible", [](const Request &, Response &res) {
  18174. // Return a large enough body to trigger compression
  18175. std::string body(1000, 'a');
  18176. res.set_content(body, "text/plain");
  18177. });
  18178. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18179. svr.wait_until_ready();
  18180. Client cli(HOST, PORT);
  18181. // Request with gzip support: should get Vary header when compressed
  18182. cli.set_compress(true);
  18183. auto res1 = cli.Get("/compressible");
  18184. ASSERT_TRUE(res1);
  18185. EXPECT_EQ(200, res1->status);
  18186. // If Content-Encoding is set, Vary should also be set
  18187. if (res1->has_header("Content-Encoding")) {
  18188. EXPECT_TRUE(res1->has_header("Vary"));
  18189. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  18190. }
  18191. // Request without Accept-Encoding header: should not have compression
  18192. Headers h_no_compress;
  18193. auto res2 = cli.Get("/compressible", h_no_compress);
  18194. ASSERT_TRUE(res2);
  18195. EXPECT_EQ(200, res2->status);
  18196. // Verify Vary header is present when compression is applied
  18197. // (the exact behavior depends on server configuration)
  18198. svr.stop();
  18199. t.join();
  18200. }
  18201. TEST(ETagTest, IfRangeWithETag) {
  18202. using namespace httplib;
  18203. // Create a test file with known content
  18204. const char *fname = "if_range_testfile.txt";
  18205. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  18206. {
  18207. std::ofstream ofs(fname);
  18208. ofs << content;
  18209. ASSERT_TRUE(ofs.good());
  18210. }
  18211. Server svr;
  18212. svr.set_mount_point("/static", ".");
  18213. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18214. svr.wait_until_ready();
  18215. Client cli(HOST, PORT);
  18216. // First request: get ETag
  18217. auto res1 = cli.Get("/static/if_range_testfile.txt");
  18218. ASSERT_TRUE(res1);
  18219. ASSERT_EQ(200, res1->status);
  18220. ASSERT_TRUE(res1->has_header("ETag"));
  18221. std::string etag = res1->get_header_value("ETag");
  18222. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  18223. // Since our server generates weak ETags (W/"..."), If-Range with our
  18224. // ETag should NOT result in partial content - it should return full content.
  18225. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  18226. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  18227. ASSERT_TRUE(res2);
  18228. // Weak ETag in If-Range -> full content (200), not partial (206)
  18229. EXPECT_EQ(200, res2->status);
  18230. EXPECT_EQ(content, res2->body);
  18231. EXPECT_FALSE(res2->has_header("Content-Range"));
  18232. // Range request with non-matching If-Range (ETag): should get 200 (full
  18233. // content)
  18234. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  18235. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  18236. ASSERT_TRUE(res3);
  18237. EXPECT_EQ(200, res3->status);
  18238. EXPECT_EQ(content, res3->body);
  18239. EXPECT_FALSE(res3->has_header("Content-Range"));
  18240. // Range request with strong ETag (hypothetical - our server doesn't generate
  18241. // strong ETags, but if client sends a strong ETag that doesn't match, it
  18242. // should return full content)
  18243. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  18244. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  18245. ASSERT_TRUE(res4);
  18246. EXPECT_EQ(200, res4->status);
  18247. EXPECT_EQ(content, res4->body);
  18248. EXPECT_FALSE(res4->has_header("Content-Range"));
  18249. svr.stop();
  18250. t.join();
  18251. std::remove(fname);
  18252. }
  18253. TEST(ETagTest, IfRangeWithDate) {
  18254. using namespace httplib;
  18255. // Create a test file
  18256. const char *fname = "if_range_date_testfile.txt";
  18257. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  18258. {
  18259. std::ofstream ofs(fname);
  18260. ofs << content;
  18261. ASSERT_TRUE(ofs.good());
  18262. }
  18263. Server svr;
  18264. svr.set_mount_point("/static", ".");
  18265. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18266. svr.wait_until_ready();
  18267. Client cli(HOST, PORT);
  18268. // First request: get Last-Modified
  18269. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  18270. ASSERT_TRUE(res1);
  18271. ASSERT_EQ(200, res1->status);
  18272. ASSERT_TRUE(res1->has_header("Last-Modified"));
  18273. std::string last_modified = res1->get_header_value("Last-Modified");
  18274. // Range request with matching If-Range (date): should get 206
  18275. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  18276. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  18277. ASSERT_TRUE(res2);
  18278. EXPECT_EQ(206, res2->status);
  18279. EXPECT_EQ("FGHIJ", res2->body);
  18280. // Range request with old If-Range date: should get 200 (full content)
  18281. Headers h3 = {{"Range", "bytes=5-9"},
  18282. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  18283. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  18284. ASSERT_TRUE(res3);
  18285. EXPECT_EQ(200, res3->status);
  18286. EXPECT_EQ(content, res3->body);
  18287. // Range request with future If-Range date: should get 206
  18288. Headers h4 = {{"Range", "bytes=0-4"},
  18289. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  18290. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  18291. ASSERT_TRUE(res4);
  18292. EXPECT_EQ(206, res4->status);
  18293. EXPECT_EQ("ABCDE", res4->body);
  18294. svr.stop();
  18295. t.join();
  18296. std::remove(fname);
  18297. }
  18298. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  18299. using namespace httplib;
  18300. const char *fname = "etag_malformed.txt";
  18301. const char *content = "malformed-etag";
  18302. {
  18303. std::ofstream ofs(fname);
  18304. ofs << content;
  18305. ASSERT_TRUE(ofs.good());
  18306. }
  18307. Server svr;
  18308. svr.set_mount_point("/static", ".");
  18309. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18310. svr.wait_until_ready();
  18311. Client cli(HOST, PORT);
  18312. // baseline: should get 200 and an ETag
  18313. auto res1 = cli.Get("/static/etag_malformed.txt");
  18314. ASSERT_TRUE(res1);
  18315. ASSERT_EQ(200, res1->status);
  18316. ASSERT_TRUE(res1->has_header("ETag"));
  18317. // Malformed ETag value (missing quotes) should be treated as non-matching
  18318. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  18319. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  18320. ASSERT_TRUE(res_bad);
  18321. EXPECT_EQ(200, res_bad->status);
  18322. // Whitespace-only header value should be considered invalid / non-matching
  18323. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  18324. "Host: localhost\r\n"
  18325. "If-None-Match: \r\n"
  18326. "Connection: close\r\n"
  18327. "\r\n";
  18328. std::string out;
  18329. ASSERT_TRUE(send_request(5, raw_req, &out));
  18330. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18331. svr.stop();
  18332. t.join();
  18333. std::remove(fname);
  18334. }
  18335. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  18336. using namespace httplib;
  18337. const char *fname = "ims_invalid_format.txt";
  18338. const char *content = "ims-bad-format";
  18339. {
  18340. std::ofstream ofs(fname);
  18341. ofs << content;
  18342. ASSERT_TRUE(ofs.good());
  18343. }
  18344. Server svr;
  18345. svr.set_mount_point("/static", ".");
  18346. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18347. svr.wait_until_ready();
  18348. Client cli(HOST, PORT);
  18349. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  18350. ASSERT_TRUE(res1);
  18351. ASSERT_EQ(200, res1->status);
  18352. ASSERT_TRUE(res1->has_header("Last-Modified"));
  18353. // If-Modified-Since with invalid format should not result in 304
  18354. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  18355. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  18356. ASSERT_TRUE(res_bad);
  18357. EXPECT_EQ(200, res_bad->status);
  18358. // If-Range with invalid date format should be treated as mismatch -> full
  18359. // content (200)
  18360. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  18361. {"If-Range", "invalid-date"}};
  18362. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  18363. ASSERT_TRUE(res_ifrange);
  18364. EXPECT_EQ(200, res_ifrange->status);
  18365. svr.stop();
  18366. t.join();
  18367. std::remove(fname);
  18368. }
  18369. TEST(ETagTest, IfRangeWithMalformedETag) {
  18370. using namespace httplib;
  18371. const char *fname = "ifrange_malformed.txt";
  18372. const std::string content = "0123456789";
  18373. {
  18374. std::ofstream ofs(fname);
  18375. ofs << content;
  18376. ASSERT_TRUE(ofs.good());
  18377. }
  18378. Server svr;
  18379. svr.set_mount_point("/static", ".");
  18380. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18381. svr.wait_until_ready();
  18382. Client cli(HOST, PORT);
  18383. // First request: get ETag
  18384. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  18385. ASSERT_TRUE(res1);
  18386. ASSERT_EQ(200, res1->status);
  18387. ASSERT_TRUE(res1->has_header("ETag"));
  18388. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  18389. // full content (200)
  18390. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  18391. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  18392. ASSERT_TRUE(res2);
  18393. EXPECT_EQ(200, res2->status);
  18394. EXPECT_EQ(content, res2->body);
  18395. svr.stop();
  18396. t.join();
  18397. std::remove(fname);
  18398. }
  18399. TEST(ETagTest, ExtremeLargeDateValues) {
  18400. using namespace httplib;
  18401. const char *fname = "ims_extreme_date.txt";
  18402. const char *content = "ims-extreme-date";
  18403. {
  18404. std::ofstream ofs(fname);
  18405. ofs << content;
  18406. ASSERT_TRUE(ofs.good());
  18407. }
  18408. Server svr;
  18409. svr.set_mount_point("/static", ".");
  18410. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18411. svr.wait_until_ready();
  18412. Client cli(HOST, PORT);
  18413. auto res1 = cli.Get(std::string("/static/") + fname);
  18414. ASSERT_TRUE(res1);
  18415. ASSERT_EQ(200, res1->status);
  18416. ASSERT_TRUE(res1->has_header("Last-Modified"));
  18417. // Extremely large year that may overflow date parsing routines.
  18418. Headers h_large_date = {
  18419. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  18420. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  18421. ASSERT_TRUE(res_bad);
  18422. // Expect server to treat this as invalid/mismatch and return full content
  18423. EXPECT_EQ(200, res_bad->status);
  18424. // If-Range with extremely large date should be treated as mismatch -> full
  18425. // content (200)
  18426. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  18427. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  18428. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  18429. ASSERT_TRUE(res_ifrange);
  18430. EXPECT_EQ(200, res_ifrange->status);
  18431. svr.stop();
  18432. t.join();
  18433. std::remove(fname);
  18434. }
  18435. TEST(ETagTest, NegativeFileModificationTime) {
  18436. using namespace httplib;
  18437. const char *fname = "ims_negative_mtime.txt";
  18438. const std::string content = "negative-mtime";
  18439. {
  18440. std::ofstream ofs(fname);
  18441. ofs << content;
  18442. ASSERT_TRUE(ofs.good());
  18443. }
  18444. // Try to set file mtime to a negative value. This may fail on some
  18445. // platforms/filesystems; if it fails, the test will still verify server
  18446. // behaves safely by performing a regular conditional request.
  18447. #if defined(__APPLE__) || defined(__linux__)
  18448. bool set_negative = false;
  18449. do {
  18450. struct timeval times[2];
  18451. // access time: now
  18452. times[0].tv_sec = time(nullptr);
  18453. times[0].tv_usec = 0;
  18454. // modification time: negative (e.g., -1)
  18455. times[1].tv_sec = -1;
  18456. times[1].tv_usec = 0;
  18457. if (utimes(fname, times) == 0) { set_negative = true; }
  18458. } while (0);
  18459. #else
  18460. bool set_negative = false;
  18461. #endif
  18462. Server svr;
  18463. svr.set_mount_point("/static", ".");
  18464. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18465. svr.wait_until_ready();
  18466. Client cli(HOST, PORT);
  18467. auto res1 = cli.Get(std::string("/static/") + fname);
  18468. ASSERT_TRUE(res1);
  18469. ASSERT_EQ(200, res1->status);
  18470. bool has_last_modified = res1->has_header("Last-Modified");
  18471. std::string last_modified;
  18472. if (has_last_modified) {
  18473. last_modified = res1->get_header_value("Last-Modified");
  18474. }
  18475. if (set_negative) {
  18476. // If we successfully set a negative mtime, ensure server returns a
  18477. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  18478. // with an old date and ensure server handles it without crash.
  18479. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  18480. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  18481. ASSERT_TRUE(res2);
  18482. // Behavior may vary; at minimum ensure server responds (200 or 304).
  18483. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  18484. } else {
  18485. // Could not set negative mtime on this platform; fall back to verifying
  18486. // that normal invalid/malformed dates are treated safely (non-304).
  18487. Headers h_bad_date = {
  18488. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  18489. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  18490. ASSERT_TRUE(res_bad);
  18491. EXPECT_EQ(200, res_bad->status);
  18492. }
  18493. svr.stop();
  18494. t.join();
  18495. std::remove(fname);
  18496. }
  18497. //==============================================================================
  18498. // SSE Parsing Tests
  18499. //==============================================================================
  18500. class SSEParsingTest : public ::testing::Test {
  18501. protected:
  18502. // Test helper that mimics SSE parsing behavior
  18503. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  18504. int &retry_ms) {
  18505. // Blank line signals end of event
  18506. if (line.empty() || line == "\r") { return true; }
  18507. // Lines starting with ':' are comments (ignored)
  18508. if (!line.empty() && line[0] == ':') { return false; }
  18509. // Find the colon separator
  18510. auto colon_pos = line.find(':');
  18511. if (colon_pos == std::string::npos) {
  18512. // Line with no colon is treated as field name with empty value
  18513. return false;
  18514. }
  18515. std::string field = line.substr(0, colon_pos);
  18516. std::string value;
  18517. // Value starts after colon, skip optional single space
  18518. if (colon_pos + 1 < line.size()) {
  18519. size_t value_start = colon_pos + 1;
  18520. if (line[value_start] == ' ') { value_start++; }
  18521. value = line.substr(value_start);
  18522. // Remove trailing \r if present
  18523. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  18524. }
  18525. // Handle known fields
  18526. if (field == "event") {
  18527. msg.event = value;
  18528. } else if (field == "data") {
  18529. // Multiple data lines are concatenated with newlines
  18530. if (!msg.data.empty()) { msg.data += "\n"; }
  18531. msg.data += value;
  18532. } else if (field == "id") {
  18533. // Empty id is valid (clears the last event ID)
  18534. msg.id = value;
  18535. } else if (field == "retry") {
  18536. // Parse retry interval in milliseconds
  18537. {
  18538. int v = 0;
  18539. auto res =
  18540. detail::from_chars(value.data(), value.data() + value.size(), v);
  18541. if (res.ec == std::errc{}) { retry_ms = v; }
  18542. }
  18543. }
  18544. // Unknown fields are ignored per SSE spec
  18545. return false;
  18546. }
  18547. };
  18548. // Test: Single-line data
  18549. TEST_F(SSEParsingTest, SingleLineData) {
  18550. sse::SSEMessage msg;
  18551. int retry_ms = 3000;
  18552. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  18553. EXPECT_EQ(msg.data, "hello");
  18554. EXPECT_EQ(msg.event, "message");
  18555. // Blank line ends event
  18556. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  18557. }
  18558. // Test: Multi-line data
  18559. TEST_F(SSEParsingTest, MultiLineData) {
  18560. sse::SSEMessage msg;
  18561. int retry_ms = 3000;
  18562. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  18563. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  18564. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  18565. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  18566. }
  18567. // Test: Custom event types
  18568. TEST_F(SSEParsingTest, CustomEventType) {
  18569. sse::SSEMessage msg;
  18570. int retry_ms = 3000;
  18571. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  18572. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  18573. EXPECT_EQ(msg.event, "update");
  18574. EXPECT_EQ(msg.data, "payload");
  18575. }
  18576. // Test: Event ID handling
  18577. TEST_F(SSEParsingTest, EventIdHandling) {
  18578. sse::SSEMessage msg;
  18579. int retry_ms = 3000;
  18580. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  18581. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  18582. EXPECT_EQ(msg.id, "12345");
  18583. }
  18584. // Test: Empty event ID (clears last event ID)
  18585. TEST_F(SSEParsingTest, EmptyEventId) {
  18586. sse::SSEMessage msg;
  18587. msg.id = "previous";
  18588. int retry_ms = 3000;
  18589. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  18590. EXPECT_EQ(msg.id, "");
  18591. }
  18592. // Test: Retry field parsing
  18593. TEST_F(SSEParsingTest, RetryFieldParsing) {
  18594. sse::SSEMessage msg;
  18595. int retry_ms = 3000;
  18596. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  18597. EXPECT_EQ(retry_ms, 5000);
  18598. }
  18599. // Test: Invalid retry value
  18600. TEST_F(SSEParsingTest, InvalidRetryValue) {
  18601. sse::SSEMessage msg;
  18602. int retry_ms = 3000;
  18603. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  18604. EXPECT_EQ(retry_ms, 3000); // Unchanged
  18605. }
  18606. // Test: Comments (lines starting with :)
  18607. TEST_F(SSEParsingTest, CommentsIgnored) {
  18608. sse::SSEMessage msg;
  18609. int retry_ms = 3000;
  18610. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  18611. EXPECT_EQ(msg.data, "");
  18612. EXPECT_EQ(msg.event, "message");
  18613. }
  18614. // Test: Colon in value
  18615. TEST_F(SSEParsingTest, ColonInValue) {
  18616. sse::SSEMessage msg;
  18617. int retry_ms = 3000;
  18618. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  18619. EXPECT_EQ(msg.data, "hello:world:test");
  18620. }
  18621. // Test: Line with no colon (field name only)
  18622. TEST_F(SSEParsingTest, FieldNameOnly) {
  18623. sse::SSEMessage msg;
  18624. int retry_ms = 3000;
  18625. // According to SSE spec, this is treated as field name with empty value
  18626. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  18627. // Since we don't recognize "data" without colon, data should be empty
  18628. EXPECT_EQ(msg.data, "");
  18629. }
  18630. // Test: Trailing \r handling
  18631. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  18632. sse::SSEMessage msg;
  18633. int retry_ms = 3000;
  18634. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  18635. EXPECT_EQ(msg.data, "hello");
  18636. }
  18637. // Test: Unknown fields ignored
  18638. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  18639. sse::SSEMessage msg;
  18640. int retry_ms = 3000;
  18641. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  18642. EXPECT_EQ(msg.data, "");
  18643. EXPECT_EQ(msg.event, "message");
  18644. }
  18645. // Test: Space after colon is optional
  18646. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  18647. sse::SSEMessage msg1, msg2;
  18648. int retry_ms = 3000;
  18649. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  18650. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  18651. EXPECT_EQ(msg1.data, "hello");
  18652. EXPECT_EQ(msg2.data, "hello");
  18653. }
  18654. // Test: SSEMessage clear
  18655. TEST_F(SSEParsingTest, MessageClear) {
  18656. sse::SSEMessage msg;
  18657. msg.event = "custom";
  18658. msg.data = "some data";
  18659. msg.id = "123";
  18660. msg.clear();
  18661. EXPECT_EQ(msg.event, "message");
  18662. EXPECT_EQ(msg.data, "");
  18663. EXPECT_EQ(msg.id, "");
  18664. }
  18665. // Test: Complete event parsing
  18666. TEST_F(SSEParsingTest, CompleteEventParsing) {
  18667. sse::SSEMessage msg;
  18668. int retry_ms = 3000;
  18669. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  18670. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  18671. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  18672. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  18673. // Blank line ends event
  18674. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  18675. EXPECT_EQ(msg.event, "notification");
  18676. EXPECT_EQ(msg.id, "evt-42");
  18677. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  18678. EXPECT_EQ(retry_ms, 1000);
  18679. }
  18680. //==============================================================================
  18681. // Integration Tests with Server
  18682. //==============================================================================
  18683. class SSEIntegrationTest : public ::testing::Test {
  18684. protected:
  18685. void SetUp() override {
  18686. stop_server_.store(false);
  18687. events_.clear();
  18688. server_ = httplib::detail::make_unique<Server>();
  18689. setup_server();
  18690. start_server();
  18691. }
  18692. void TearDown() override {
  18693. stop_server_.store(true);
  18694. event_cv_.notify_all();
  18695. server_->stop();
  18696. if (server_thread_.joinable()) { server_thread_.join(); }
  18697. }
  18698. void setup_server() {
  18699. // Simple SSE endpoint
  18700. server_->Get("/events", [this](const Request &req, Response &res) {
  18701. auto last_id = req.get_header_value("Last-Event-ID");
  18702. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  18703. res.set_chunked_content_provider(
  18704. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  18705. std::unique_lock<std::mutex> lock(event_mutex_);
  18706. if (event_cv_.wait_for(
  18707. lock, std::chrono::milliseconds(200), [this] {
  18708. return !events_.empty() || stop_server_.load();
  18709. })) {
  18710. if (stop_server_.load()) { return false; }
  18711. if (!events_.empty()) {
  18712. std::string event = events_.front();
  18713. events_.erase(events_.begin());
  18714. sink.write(event.data(), event.size());
  18715. return true;
  18716. }
  18717. }
  18718. return !stop_server_.load();
  18719. });
  18720. });
  18721. // Endpoint that returns error
  18722. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  18723. res.status = 500;
  18724. res.set_content("Internal Server Error", "text/plain");
  18725. });
  18726. // Endpoint for custom event types
  18727. server_->Get("/custom-events", [](const Request &, Response &res) {
  18728. res.set_chunked_content_provider(
  18729. "text/event-stream", [](size_t offset, DataSink &sink) {
  18730. if (offset == 0) {
  18731. std::string event = "event: update\ndata: updated\n\n"
  18732. "event: delete\ndata: deleted\n\n";
  18733. sink.write(event.data(), event.size());
  18734. }
  18735. return false; // End stream after sending
  18736. });
  18737. });
  18738. }
  18739. void start_server() {
  18740. port_ = server_->bind_to_any_port(HOST);
  18741. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  18742. // Wait for server to start
  18743. while (!server_->is_running()) {
  18744. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  18745. }
  18746. }
  18747. int get_port() const { return port_; }
  18748. void send_event(const std::string &event) {
  18749. std::lock_guard<std::mutex> lock(event_mutex_);
  18750. events_.push_back(event);
  18751. event_cv_.notify_all();
  18752. }
  18753. std::unique_ptr<Server> server_;
  18754. std::thread server_thread_;
  18755. std::mutex event_mutex_;
  18756. std::condition_variable event_cv_;
  18757. std::vector<std::string> events_;
  18758. std::atomic<bool> stop_server_{false};
  18759. std::string last_received_event_id_;
  18760. int port_ = 0;
  18761. };
  18762. // Test: Successful connection and on_open callback
  18763. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  18764. // Add a simple endpoint that sends one event and closes
  18765. server_->Get("/simple-event", [](const Request &, Response &res) {
  18766. res.set_chunked_content_provider(
  18767. "text/event-stream", [](size_t offset, DataSink &sink) {
  18768. if (offset == 0) {
  18769. std::string event = "data: hello\n\n";
  18770. sink.write(event.data(), event.size());
  18771. }
  18772. return false; // Close stream after sending
  18773. });
  18774. });
  18775. Client client("localhost", get_port());
  18776. sse::SSEClient sse(client, "/simple-event");
  18777. std::atomic<bool> open_called{false};
  18778. std::atomic<bool> message_received{false};
  18779. sse.on_open([&open_called]() { open_called.store(true); });
  18780. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  18781. if (msg.data == "hello") { message_received.store(true); }
  18782. });
  18783. sse.set_reconnect_interval(100);
  18784. sse.set_max_reconnect_attempts(1);
  18785. // Start async
  18786. sse.start_async();
  18787. // Wait for message to be processed
  18788. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  18789. sse.stop();
  18790. EXPECT_TRUE(open_called.load());
  18791. EXPECT_TRUE(message_received.load());
  18792. }
  18793. // Test: on_message callback
  18794. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  18795. // Endpoint that sends multiple events then closes
  18796. server_->Get("/multi-event", [](const Request &, Response &res) {
  18797. res.set_chunked_content_provider(
  18798. "text/event-stream", [](size_t offset, DataSink &sink) {
  18799. if (offset == 0) {
  18800. std::string events = "data: message1\n\ndata: message2\n\n";
  18801. sink.write(events.data(), events.size());
  18802. }
  18803. return false;
  18804. });
  18805. });
  18806. Client client("localhost", get_port());
  18807. sse::SSEClient sse(client, "/multi-event");
  18808. std::vector<std::string> received_messages;
  18809. std::mutex messages_mutex;
  18810. sse.on_message([&](const sse::SSEMessage &msg) {
  18811. std::lock_guard<std::mutex> lock(messages_mutex);
  18812. received_messages.push_back(msg.data);
  18813. });
  18814. sse.set_reconnect_interval(100);
  18815. sse.set_max_reconnect_attempts(1);
  18816. sse.start_async();
  18817. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  18818. sse.stop();
  18819. std::lock_guard<std::mutex> lock(messages_mutex);
  18820. EXPECT_GE(received_messages.size(), 2u);
  18821. if (received_messages.size() >= 2) {
  18822. EXPECT_EQ(received_messages[0], "message1");
  18823. EXPECT_EQ(received_messages[1], "message2");
  18824. }
  18825. }
  18826. // Test: on_event for specific types
  18827. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  18828. Client client("localhost", get_port());
  18829. sse::SSEClient sse(client, "/custom-events");
  18830. std::atomic<bool> update_received{false};
  18831. std::atomic<bool> delete_received{false};
  18832. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  18833. if (msg.data == "updated") { update_received.store(true); }
  18834. });
  18835. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  18836. if (msg.data == "deleted") { delete_received.store(true); }
  18837. });
  18838. sse.set_max_reconnect_attempts(1);
  18839. sse.start_async();
  18840. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  18841. sse.stop();
  18842. EXPECT_TRUE(update_received.load());
  18843. EXPECT_TRUE(delete_received.load());
  18844. }
  18845. // Test: on_error callback on connection failure
  18846. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  18847. // Connect to a non-existent port
  18848. Client client("localhost", 59999);
  18849. sse::SSEClient sse(client, "/events");
  18850. std::atomic<bool> error_called{false};
  18851. Error received_error = Error::Success;
  18852. sse.on_error([&](Error err) {
  18853. error_called.store(true);
  18854. received_error = err;
  18855. });
  18856. sse.set_reconnect_interval(50);
  18857. sse.set_max_reconnect_attempts(1);
  18858. sse.start_async();
  18859. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  18860. sse.stop();
  18861. EXPECT_TRUE(error_called.load());
  18862. EXPECT_NE(received_error, Error::Success);
  18863. }
  18864. // Test: Last-Event-ID header sent on reconnect
  18865. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  18866. // Endpoint that sends event with ID
  18867. server_->Get("/event-with-id", [](const Request &, Response &res) {
  18868. res.set_chunked_content_provider(
  18869. "text/event-stream", [](size_t offset, DataSink &sink) {
  18870. if (offset == 0) {
  18871. std::string event = "id: evt-123\ndata: test\n\n";
  18872. sink.write(event.data(), event.size());
  18873. }
  18874. return false;
  18875. });
  18876. });
  18877. Client client("localhost", get_port());
  18878. sse::SSEClient sse(client, "/event-with-id");
  18879. std::atomic<bool> id_received{false};
  18880. sse.on_message([&](const sse::SSEMessage &msg) {
  18881. if (!msg.id.empty()) { id_received.store(true); }
  18882. });
  18883. sse.set_reconnect_interval(100);
  18884. sse.set_max_reconnect_attempts(1);
  18885. sse.start_async();
  18886. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  18887. sse.stop();
  18888. EXPECT_TRUE(id_received.load());
  18889. EXPECT_EQ(sse.last_event_id(), "evt-123");
  18890. }
  18891. // Test: Manual stop
  18892. TEST_F(SSEIntegrationTest, ManualStop) {
  18893. // Endpoint that sends one event and stays open briefly
  18894. std::atomic<bool> handler_running{true};
  18895. server_->Get("/stay-open", [&handler_running](const Request &,
  18896. Response &res) {
  18897. res.set_chunked_content_provider(
  18898. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  18899. if (offset == 0) {
  18900. std::string event = "data: connected\n\n";
  18901. sink.write(event.data(), event.size());
  18902. }
  18903. // Keep connection open while handler_running is true
  18904. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  18905. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  18906. }
  18907. return false;
  18908. });
  18909. });
  18910. Client client("localhost", get_port());
  18911. sse::SSEClient sse(client, "/stay-open");
  18912. std::atomic<bool> connected{false};
  18913. sse.on_open([&connected]() { connected.store(true); });
  18914. sse.set_reconnect_interval(100);
  18915. sse.set_max_reconnect_attempts(1);
  18916. sse.start_async();
  18917. // Wait for connection to establish
  18918. for (int i = 0; i < 20 && !connected.load(); ++i) {
  18919. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  18920. }
  18921. EXPECT_TRUE(connected.load());
  18922. EXPECT_TRUE(sse.is_connected());
  18923. // Signal handler to stop
  18924. handler_running.store(false);
  18925. // Stop SSE client
  18926. sse.stop();
  18927. EXPECT_FALSE(sse.is_connected());
  18928. }
  18929. // Test: SSEClient with custom headers
  18930. TEST_F(SSEIntegrationTest, CustomHeaders) {
  18931. // Setup a server endpoint that checks for custom header
  18932. std::atomic<bool> header_received{false};
  18933. server_->Get("/header-check", [&](const Request &req, Response &res) {
  18934. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  18935. header_received.store(true);
  18936. }
  18937. res.set_chunked_content_provider("text/event-stream",
  18938. [](size_t, DataSink &) { return false; });
  18939. });
  18940. Client client("localhost", get_port());
  18941. Headers headers = {{"X-Custom-Header", "custom-value"}};
  18942. sse::SSEClient sse(client, "/header-check", headers);
  18943. sse.set_max_reconnect_attempts(1);
  18944. sse.start_async();
  18945. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  18946. sse.stop();
  18947. EXPECT_TRUE(header_received.load());
  18948. }
  18949. // Test: Reconnect interval configuration
  18950. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  18951. Client client("localhost", get_port());
  18952. sse::SSEClient sse(client, "/events");
  18953. auto &result = sse.set_reconnect_interval(500);
  18954. // Builder pattern should return reference to self
  18955. EXPECT_EQ(&result, &sse);
  18956. }
  18957. // Test: Max reconnect attempts
  18958. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  18959. // Connect to non-existent port to force reconnects
  18960. Client client("localhost", 59998);
  18961. sse::SSEClient sse(client, "/events");
  18962. std::atomic<int> error_count{0};
  18963. sse.on_error([&](Error) { error_count.fetch_add(1); });
  18964. sse.set_reconnect_interval(50);
  18965. sse.set_max_reconnect_attempts(2);
  18966. auto start = std::chrono::steady_clock::now();
  18967. sse.start(); // Blocking call
  18968. auto end = std::chrono::steady_clock::now();
  18969. // Should have stopped after 2 failed attempts
  18970. EXPECT_GE(error_count.load(), 2);
  18971. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  18972. auto duration =
  18973. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  18974. #ifdef _WIN32
  18975. // Windows is much slower for socket connection failures
  18976. EXPECT_LT(duration.count(), 7000);
  18977. #else
  18978. EXPECT_LT(duration.count(), 1000);
  18979. #endif
  18980. }
  18981. // Test: Multi-line data in integration
  18982. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  18983. // Endpoint with multi-line data
  18984. server_->Get("/multiline-data", [](const Request &, Response &res) {
  18985. res.set_chunked_content_provider(
  18986. "text/event-stream", [](size_t offset, DataSink &sink) {
  18987. if (offset == 0) {
  18988. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  18989. sink.write(event.data(), event.size());
  18990. }
  18991. return false;
  18992. });
  18993. });
  18994. Client client("localhost", get_port());
  18995. sse::SSEClient sse(client, "/multiline-data");
  18996. std::string received_data;
  18997. std::mutex data_mutex;
  18998. sse.on_message([&](const sse::SSEMessage &msg) {
  18999. std::lock_guard<std::mutex> lock(data_mutex);
  19000. received_data = msg.data;
  19001. });
  19002. sse.set_reconnect_interval(100);
  19003. sse.set_max_reconnect_attempts(1);
  19004. sse.start_async();
  19005. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19006. sse.stop();
  19007. std::lock_guard<std::mutex> lock(data_mutex);
  19008. EXPECT_EQ(received_data, "line1\nline2\nline3");
  19009. }
  19010. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  19011. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  19012. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  19013. DataSink &sink) {
  19014. if (offset == 0) {
  19015. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  19016. sink.write(events.data(), events.size());
  19017. }
  19018. return false;
  19019. });
  19020. });
  19021. Client client("localhost", get_port());
  19022. sse::SSEClient sse(client, "/empty-data-lines");
  19023. std::mutex mutex;
  19024. std::condition_variable cv;
  19025. std::vector<std::string> received;
  19026. sse.on_message([&](const sse::SSEMessage &msg) {
  19027. std::lock_guard<std::mutex> lock(mutex);
  19028. received.push_back(msg.data);
  19029. cv.notify_all();
  19030. });
  19031. sse.set_max_reconnect_attempts(1);
  19032. sse.start_async();
  19033. {
  19034. std::unique_lock<std::mutex> lock(mutex);
  19035. cv.wait_for(lock, std::chrono::seconds(2),
  19036. [&] { return received.size() >= 3; });
  19037. }
  19038. sse.stop();
  19039. ASSERT_GE(received.size(), 3u);
  19040. EXPECT_EQ(received[0], "");
  19041. EXPECT_EQ(received[1], "\nhello");
  19042. EXPECT_EQ(received[2], "");
  19043. }
  19044. // Test: Auto-reconnect after server disconnection
  19045. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  19046. std::atomic<int> connection_count{0};
  19047. std::atomic<int> message_count{0};
  19048. // Endpoint that sends one event and closes, forcing reconnect
  19049. server_->Get("/reconnect-test",
  19050. [&connection_count](const Request &, Response &res) {
  19051. connection_count.fetch_add(1);
  19052. res.set_chunked_content_provider(
  19053. "text/event-stream", [](size_t offset, DataSink &sink) {
  19054. if (offset == 0) {
  19055. std::string event = "data: hello\n\n";
  19056. sink.write(event.data(), event.size());
  19057. }
  19058. return false; // Close connection after sending
  19059. });
  19060. });
  19061. Client client("localhost", get_port());
  19062. sse::SSEClient sse(client, "/reconnect-test");
  19063. sse.on_message([&message_count](const sse::SSEMessage &) {
  19064. message_count.fetch_add(1);
  19065. });
  19066. sse.set_reconnect_interval(100);
  19067. sse.set_max_reconnect_attempts(3);
  19068. sse.start_async();
  19069. // Wait long enough for multiple reconnects
  19070. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  19071. sse.stop();
  19072. // Should have connected multiple times (initial + reconnects)
  19073. EXPECT_GE(connection_count.load(), 2);
  19074. // Should have received messages from multiple connections
  19075. EXPECT_GE(message_count.load(), 2);
  19076. }
  19077. // Test: A retry field that is not all ASCII digits is ignored
  19078. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  19079. std::atomic<int> connection_count{0};
  19080. server_->Get("/bad-retry",
  19081. [&connection_count](const Request &, Response &res) {
  19082. connection_count.fetch_add(1);
  19083. res.set_chunked_content_provider(
  19084. "text/event-stream", [](size_t offset, DataSink &sink) {
  19085. if (offset == 0) {
  19086. std::string event = "retry: -1\ndata: hello\n\n";
  19087. sink.write(event.data(), event.size());
  19088. }
  19089. return false;
  19090. });
  19091. });
  19092. Client client("localhost", get_port());
  19093. sse::SSEClient sse(client, "/bad-retry");
  19094. sse.set_reconnect_interval(10000);
  19095. sse.start_async();
  19096. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19097. sse.stop();
  19098. EXPECT_EQ(connection_count.load(), 1);
  19099. }
  19100. // Test: A retry field of all ASCII digits sets the reconnection time
  19101. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  19102. std::atomic<int> connection_count{0};
  19103. server_->Get("/zero-retry",
  19104. [&connection_count](const Request &, Response &res) {
  19105. connection_count.fetch_add(1);
  19106. res.set_chunked_content_provider(
  19107. "text/event-stream", [](size_t offset, DataSink &sink) {
  19108. if (offset == 0) {
  19109. std::string event = "retry: 0\ndata: hello\n\n";
  19110. sink.write(event.data(), event.size());
  19111. }
  19112. return false;
  19113. });
  19114. });
  19115. Client client("localhost", get_port());
  19116. sse::SSEClient sse(client, "/zero-retry");
  19117. sse.set_reconnect_interval(10000);
  19118. sse.start_async();
  19119. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19120. sse.stop();
  19121. // The server-supplied interval is applied, but never below 100ms, so
  19122. // "retry: 0" does not cause a busy reconnect loop
  19123. EXPECT_GE(connection_count.load(), 2);
  19124. EXPECT_LE(connection_count.load(), 10);
  19125. }
  19126. // Test: Last-Event-ID sent on reconnect
  19127. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  19128. std::atomic<int> connection_count{0};
  19129. std::vector<std::string> received_last_event_ids;
  19130. std::mutex id_mutex;
  19131. // Endpoint that checks Last-Event-ID header and sends event with ID
  19132. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  19133. int conn = connection_count.fetch_add(1);
  19134. // Capture the Last-Event-ID header from each connection
  19135. {
  19136. std::lock_guard<std::mutex> lock(id_mutex);
  19137. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  19138. }
  19139. res.set_chunked_content_provider(
  19140. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  19141. if (offset == 0) {
  19142. std::string event =
  19143. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  19144. sink.write(event.data(), event.size());
  19145. }
  19146. return false;
  19147. });
  19148. });
  19149. Client client("localhost", get_port());
  19150. sse::SSEClient sse(client, "/reconnect-with-id");
  19151. sse.set_reconnect_interval(100);
  19152. sse.set_max_reconnect_attempts(3);
  19153. sse.start_async();
  19154. // Wait for at least 2 connections
  19155. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19156. sse.stop();
  19157. // Verify behavior
  19158. std::lock_guard<std::mutex> lock(id_mutex);
  19159. EXPECT_GE(received_last_event_ids.size(), 2u);
  19160. // First connection should have no Last-Event-ID
  19161. if (!received_last_event_ids.empty()) {
  19162. EXPECT_EQ(received_last_event_ids[0], "");
  19163. }
  19164. // Second connection should have Last-Event-ID from first connection
  19165. if (received_last_event_ids.size() >= 2) {
  19166. EXPECT_EQ(received_last_event_ids[1], "event-0");
  19167. }
  19168. }
  19169. // Test: set_headers updates headers used on reconnect
  19170. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  19171. std::vector<std::string> received_tokens;
  19172. std::mutex token_mutex;
  19173. // Endpoint that captures Authorization header
  19174. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  19175. {
  19176. std::lock_guard<std::mutex> lock(token_mutex);
  19177. received_tokens.push_back(req.get_header_value("Authorization"));
  19178. }
  19179. res.set_chunked_content_provider(
  19180. "text/event-stream", [](size_t offset, DataSink &sink) {
  19181. if (offset == 0) {
  19182. std::string event = "data: hello\n\n";
  19183. sink.write(event.data(), event.size());
  19184. }
  19185. return false; // Close connection to trigger reconnect
  19186. });
  19187. });
  19188. Client client("localhost", get_port());
  19189. Headers headers = {{"Authorization", "Bearer old-token"}};
  19190. sse::SSEClient sse(client, "/auth-check", headers);
  19191. // Update headers on each successful connection
  19192. sse.on_open(
  19193. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  19194. sse.set_reconnect_interval(100);
  19195. sse.set_max_reconnect_attempts(3);
  19196. sse.start_async();
  19197. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  19198. sse.stop();
  19199. std::lock_guard<std::mutex> lock(token_mutex);
  19200. ASSERT_GE(received_tokens.size(), 2u);
  19201. // First connection uses original header
  19202. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  19203. // Second connection uses updated header from set_headers
  19204. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  19205. }
  19206. // Test: 401 allows reconnection (so on_error can refresh headers)
  19207. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  19208. std::atomic<int> connection_count{0};
  19209. // Endpoint: returns 401 on first attempt, 200 on second
  19210. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  19211. int conn = connection_count.fetch_add(1);
  19212. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  19213. res.status = StatusCode::Unauthorized_401;
  19214. res.set_content("Unauthorized", "text/plain");
  19215. return;
  19216. }
  19217. res.set_chunked_content_provider(
  19218. "text/event-stream", [](size_t offset, DataSink &sink) {
  19219. if (offset == 0) {
  19220. std::string event = "data: authenticated\n\n";
  19221. sink.write(event.data(), event.size());
  19222. }
  19223. return false;
  19224. });
  19225. });
  19226. Client client("localhost", get_port());
  19227. Headers headers = {{"Authorization", "Bearer expired"}};
  19228. sse::SSEClient sse(client, "/auth-retry", headers);
  19229. std::atomic<bool> message_received{false};
  19230. // Refresh token on error
  19231. sse.on_error(
  19232. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  19233. sse.on_message([&](const sse::SSEMessage &msg) {
  19234. if (msg.data == "authenticated") { message_received.store(true); }
  19235. });
  19236. sse.set_reconnect_interval(100);
  19237. sse.set_max_reconnect_attempts(3);
  19238. sse.start_async();
  19239. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  19240. sse.stop();
  19241. // Should have reconnected after 401 and succeeded with new token
  19242. EXPECT_GE(connection_count.load(), 2);
  19243. EXPECT_TRUE(message_received.load());
  19244. }
  19245. TEST(Issue2318Test, EmptyHostString) {
  19246. {
  19247. httplib::Client cli_empty("", PORT);
  19248. auto res = cli_empty.Get("/");
  19249. ASSERT_FALSE(res);
  19250. EXPECT_EQ(httplib::Error::Connection, res.error());
  19251. }
  19252. {
  19253. httplib::Client cli(" ", PORT);
  19254. auto res = cli.Get("/");
  19255. ASSERT_FALSE(res);
  19256. EXPECT_EQ(httplib::Error::Connection, res.error());
  19257. }
  19258. }
  19259. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19260. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  19261. Server svr;
  19262. // Set a small payload limit (1KB)
  19263. svr.set_payload_max_length(1024);
  19264. svr.Post("/test", [&](const Request &req, Response &res) {
  19265. res.set_content("Body size: " + std::to_string(req.body.size()),
  19266. "text/plain");
  19267. });
  19268. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  19269. auto se = detail::scope_exit([&] {
  19270. svr.stop();
  19271. listen_thread.join();
  19272. });
  19273. svr.wait_until_ready();
  19274. // Create data that compresses well but exceeds limit when decompressed
  19275. // 8KB of repeated null bytes compresses to a very small size
  19276. std::string original_data(8 * 1024, '\0');
  19277. // Compress the data using gzip
  19278. std::string compressed_data;
  19279. detail::gzip_compressor compressor;
  19280. compressor.compress(original_data.data(), original_data.size(), true,
  19281. [&](const char *data, size_t size) {
  19282. compressed_data.append(data, size);
  19283. return true;
  19284. });
  19285. // Verify compression worked (compressed should be much smaller)
  19286. ASSERT_LT(compressed_data.size(), original_data.size());
  19287. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  19288. // Send compressed data with Content-Encoding: gzip
  19289. Client cli(HOST, PORT);
  19290. Headers headers = {{"Content-Encoding", "gzip"}};
  19291. auto res =
  19292. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  19293. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  19294. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19295. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  19296. }
  19297. #endif
  19298. // ============================================================================
  19299. // OpenSSL-Specific Tests
  19300. // ============================================================================
  19301. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  19302. X509 *readCertificate(const std::string &strFileName) {
  19303. std::ifstream inStream(strFileName);
  19304. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  19305. std::istreambuf_iterator<char>());
  19306. if (strCertPEM.empty()) return (nullptr);
  19307. BIO *pbCert = BIO_new(BIO_s_mem());
  19308. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  19309. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  19310. BIO_free(pbCert);
  19311. return (pCert);
  19312. }
  19313. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  19314. std::ifstream inStream(strFileName);
  19315. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  19316. std::istreambuf_iterator<char>());
  19317. if (strPrivateKeyPEM.empty()) return (nullptr);
  19318. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  19319. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  19320. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  19321. BIO_free(pbPrivKey);
  19322. return (pPrivateKey);
  19323. }
  19324. TEST(BindServerTest, UpdateCerts) {
  19325. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  19326. int port = svr.bind_to_any_port("0.0.0.0");
  19327. ASSERT_TRUE(svr.is_valid());
  19328. ASSERT_TRUE(port > 0);
  19329. X509 *cert = readCertificate(SERVER_CERT_FILE);
  19330. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  19331. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  19332. ASSERT_TRUE(cert != nullptr);
  19333. ASSERT_TRUE(ca_cert != nullptr);
  19334. ASSERT_TRUE(key != nullptr);
  19335. X509_STORE *cert_store = X509_STORE_new();
  19336. X509_STORE_add_cert(cert_store, ca_cert);
  19337. // svr.update_certs(cert, key, cert_store); // deprecated
  19338. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  19339. CLIENT_CA_CERT_FILE);
  19340. ASSERT_TRUE(svr.is_valid());
  19341. svr.stop();
  19342. X509_STORE_free(cert_store);
  19343. X509_free(cert);
  19344. X509_free(ca_cert);
  19345. EVP_PKEY_free(key);
  19346. }
  19347. // Test that update_certs() updates client CA list correctly
  19348. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  19349. // Start with file-based constructor
  19350. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19351. ASSERT_TRUE(svr.is_valid());
  19352. // Initially no client CA list should be set
  19353. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  19354. ASSERT_TRUE(ssl_ctx != nullptr);
  19355. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  19356. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  19357. EXPECT_EQ(0, count_before);
  19358. // Now update with client CA (PEM string)
  19359. std::string cert_pem, key_pem, ca_pem;
  19360. read_file(SERVER_CERT_FILE, cert_pem);
  19361. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  19362. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  19363. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  19364. ASSERT_TRUE(svr.is_valid());
  19365. // Now client CA list should be set
  19366. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  19367. ASSERT_TRUE(ca_list_after != nullptr);
  19368. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  19369. }
  19370. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  19371. // Test that the file-path SSLServer constructor properly sets the client CA
  19372. // list that is sent to clients during the TLS handshake (CertificateRequest)
  19373. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  19374. ASSERT_TRUE(svr.is_valid());
  19375. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  19376. ASSERT_TRUE(ssl_ctx != nullptr);
  19377. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  19378. ASSERT_TRUE(ca_list != nullptr);
  19379. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  19380. }
  19381. #endif
  19382. // ============================================================================
  19383. // MbedTLS-Specific Tests
  19384. // ============================================================================
  19385. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  19386. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  19387. using namespace httplib::tls;
  19388. // Track if callback was invoked
  19389. bool callback_invoked = false;
  19390. // The callback receives void* ctx which is actually MbedTlsContext*
  19391. // We can access the mbedtls_ssl_config via the context
  19392. auto setup_callback = [&callback_invoked](void *ctx) {
  19393. callback_invoked = true;
  19394. // Cast to MbedTlsContext* to access the ssl config
  19395. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  19396. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  19397. // Use static variables to hold certificate data (simplified for test)
  19398. static mbedtls_x509_crt own_cert;
  19399. static mbedtls_pk_context own_key;
  19400. static mbedtls_x509_crt ca_chain;
  19401. static bool initialized = false;
  19402. if (!initialized) {
  19403. mbedtls_x509_crt_init(&own_cert);
  19404. mbedtls_pk_init(&own_key);
  19405. mbedtls_x509_crt_init(&ca_chain);
  19406. // Load server certificate
  19407. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  19408. return false;
  19409. }
  19410. // Load server private key.
  19411. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  19412. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  19413. #if MBEDTLS_VERSION_MAJOR == 3
  19414. ,
  19415. mbedtls_ctr_drbg_random, nullptr
  19416. #endif
  19417. ) != 0) {
  19418. return false;
  19419. }
  19420. // Load CA chain for client verification
  19421. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  19422. return false;
  19423. }
  19424. initialized = true;
  19425. }
  19426. // Configure the SSL config
  19427. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  19428. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  19429. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  19430. // Set minimum TLS version using mbedTLS native API
  19431. #if MBEDTLS_VERSION_MAJOR >= 3
  19432. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  19433. #else
  19434. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  19435. MBEDTLS_SSL_MINOR_VERSION_3);
  19436. #endif
  19437. return true;
  19438. };
  19439. SSLServer svr(setup_callback);
  19440. ASSERT_TRUE(svr.is_valid());
  19441. ASSERT_TRUE(callback_invoked);
  19442. svr.Get("/test", [&](const Request &req, Response &res) {
  19443. res.set_content("test", "text/plain");
  19444. auto cert = req.peer_cert();
  19445. ASSERT_TRUE(static_cast<bool>(cert));
  19446. auto common_name = cert.subject_cn();
  19447. EXPECT_EQ("Common Name", common_name);
  19448. });
  19449. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  19450. auto se = detail::scope_exit([&] {
  19451. svr.stop();
  19452. t.join();
  19453. ASSERT_FALSE(svr.is_running());
  19454. });
  19455. svr.wait_until_ready();
  19456. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  19457. cli.enable_server_certificate_verification(false);
  19458. cli.set_connection_timeout(30);
  19459. auto res = cli.Get("/test");
  19460. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19461. ASSERT_EQ(StatusCode::OK_200, res->status);
  19462. }
  19463. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  19464. // context (owning mbedtls_ssl_config) before shutting down a still-open
  19465. // keep-alive SSL session, which reads through that config in
  19466. // mbedtls_ssl_close_notify.
  19467. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  19468. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19469. ASSERT_TRUE(svr.is_valid());
  19470. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  19471. res.set_content("test", "text/plain");
  19472. });
  19473. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  19474. auto se = detail::scope_exit([&] {
  19475. svr.stop();
  19476. t.join();
  19477. ASSERT_FALSE(svr.is_running());
  19478. });
  19479. svr.wait_until_ready();
  19480. {
  19481. SSLClient cli(HOST, PORT);
  19482. cli.enable_server_certificate_verification(false);
  19483. cli.set_keep_alive(true);
  19484. auto res = cli.Get("/test");
  19485. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19486. ASSERT_EQ(StatusCode::OK_200, res->status);
  19487. // cli is destructed here with the keep-alive SSL session still open.
  19488. }
  19489. }
  19490. #endif
  19491. // WebSocket Tests
  19492. TEST(WebSocketTest, RSVBitsMustBeZero) {
  19493. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  19494. // defining the meaning of these bits has been negotiated.
  19495. auto make_frame = [](uint8_t first_byte) {
  19496. std::string frame;
  19497. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  19498. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  19499. frame += "Hello";
  19500. return frame;
  19501. };
  19502. // RSV1 set (0x40)
  19503. {
  19504. detail::BufferStream strm;
  19505. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  19506. ws::Opcode opcode;
  19507. std::string payload;
  19508. bool fin;
  19509. EXPECT_EQ(
  19510. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19511. ws::impl::FrameRead::Fail);
  19512. }
  19513. // RSV2 set (0x20)
  19514. {
  19515. detail::BufferStream strm;
  19516. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  19517. ws::Opcode opcode;
  19518. std::string payload;
  19519. bool fin;
  19520. EXPECT_EQ(
  19521. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19522. ws::impl::FrameRead::Fail);
  19523. }
  19524. // RSV3 set (0x10)
  19525. {
  19526. detail::BufferStream strm;
  19527. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  19528. ws::Opcode opcode;
  19529. std::string payload;
  19530. bool fin;
  19531. EXPECT_EQ(
  19532. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19533. ws::impl::FrameRead::Fail);
  19534. }
  19535. // No RSV bits set - should succeed
  19536. {
  19537. detail::BufferStream strm;
  19538. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  19539. ws::Opcode opcode;
  19540. std::string payload;
  19541. bool fin;
  19542. EXPECT_EQ(
  19543. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19544. ws::impl::FrameRead::Ok);
  19545. EXPECT_EQ(ws::Opcode::Text, opcode);
  19546. EXPECT_EQ("Hello", payload);
  19547. EXPECT_TRUE(fin);
  19548. }
  19549. }
  19550. TEST(WebSocketTest, ControlFrameValidation) {
  19551. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  19552. // payload length <= 125.
  19553. // Ping with FIN=0 - must be rejected
  19554. {
  19555. detail::BufferStream strm;
  19556. std::string frame;
  19557. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  19558. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  19559. strm.write(frame.data(), frame.size());
  19560. ws::Opcode opcode;
  19561. std::string payload;
  19562. bool fin;
  19563. EXPECT_EQ(
  19564. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19565. ws::impl::FrameRead::Fail);
  19566. }
  19567. // Close with FIN=0 - must be rejected
  19568. {
  19569. detail::BufferStream strm;
  19570. std::string frame;
  19571. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  19572. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  19573. strm.write(frame.data(), frame.size());
  19574. ws::Opcode opcode;
  19575. std::string payload;
  19576. bool fin;
  19577. EXPECT_EQ(
  19578. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19579. ws::impl::FrameRead::Fail);
  19580. }
  19581. // Ping with payload_len=126 (extended length) - must be rejected
  19582. {
  19583. detail::BufferStream strm;
  19584. std::string frame;
  19585. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  19586. frame += static_cast<char>(126); // payload_len=126 (>125)
  19587. frame += static_cast<char>(0x00); // extended length high byte
  19588. frame += static_cast<char>(126); // extended length low byte
  19589. frame += std::string(126, 'x');
  19590. strm.write(frame.data(), frame.size());
  19591. ws::Opcode opcode;
  19592. std::string payload;
  19593. bool fin;
  19594. EXPECT_EQ(
  19595. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19596. ws::impl::FrameRead::Fail);
  19597. }
  19598. // Ping with FIN=1 and payload_len=125 - should succeed
  19599. {
  19600. detail::BufferStream strm;
  19601. std::string frame;
  19602. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  19603. frame += static_cast<char>(125); // payload_len=125
  19604. frame += std::string(125, 'x');
  19605. strm.write(frame.data(), frame.size());
  19606. ws::Opcode opcode;
  19607. std::string payload;
  19608. bool fin;
  19609. EXPECT_EQ(
  19610. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19611. ws::impl::FrameRead::Ok);
  19612. EXPECT_EQ(ws::Opcode::Ping, opcode);
  19613. EXPECT_EQ(125u, payload.size());
  19614. EXPECT_TRUE(fin);
  19615. }
  19616. }
  19617. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  19618. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  19619. // length MUST be 0.
  19620. // MSB set - must be rejected
  19621. {
  19622. detail::BufferStream strm;
  19623. std::string frame;
  19624. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  19625. frame += static_cast<char>(127); // 64-bit extended length
  19626. frame += static_cast<char>(0x80); // MSB set (invalid)
  19627. frame += std::string(7, '\0'); // remaining 7 bytes of length
  19628. strm.write(frame.data(), frame.size());
  19629. ws::Opcode opcode;
  19630. std::string payload;
  19631. bool fin;
  19632. EXPECT_EQ(
  19633. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19634. ws::impl::FrameRead::Fail);
  19635. }
  19636. // MSB clear - should pass length parsing (will be rejected by max_len,
  19637. // but that's a different check; use a small length to verify)
  19638. {
  19639. detail::BufferStream strm;
  19640. std::string frame;
  19641. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  19642. frame += static_cast<char>(127); // 64-bit extended length
  19643. frame += std::string(7, '\0'); // high bytes = 0
  19644. frame += static_cast<char>(0x03); // length = 3
  19645. frame += "abc";
  19646. strm.write(frame.data(), frame.size());
  19647. ws::Opcode opcode;
  19648. std::string payload;
  19649. bool fin;
  19650. EXPECT_EQ(
  19651. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19652. ws::impl::FrameRead::Ok);
  19653. EXPECT_EQ(ws::Opcode::Text, opcode);
  19654. EXPECT_EQ("abc", payload);
  19655. }
  19656. }
  19657. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  19658. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  19659. // Valid UTF-8
  19660. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  19661. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  19662. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  19663. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  19664. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  19665. // Invalid UTF-8
  19666. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  19667. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  19668. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  19669. EXPECT_FALSE(
  19670. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  19671. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  19672. }
  19673. TEST(WebSocketTest, ConnectAndDisconnect) {
  19674. Server svr;
  19675. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  19676. std::string msg;
  19677. while (ws.read(msg)) {}
  19678. });
  19679. auto port = svr.bind_to_any_port(HOST);
  19680. std::thread t([&]() { svr.listen_after_bind(); });
  19681. svr.wait_until_ready();
  19682. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  19683. auto res = client.connect();
  19684. ASSERT_TRUE(res);
  19685. EXPECT_EQ(Error::Success, res.error());
  19686. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  19687. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  19688. EXPECT_TRUE(client.is_open());
  19689. client.close();
  19690. EXPECT_FALSE(client.is_open());
  19691. svr.stop();
  19692. t.join();
  19693. }
  19694. TEST(WebSocketTest, ValidURL) {
  19695. ws::WebSocketClient ws1("ws://localhost:8080/path");
  19696. EXPECT_TRUE(ws1.is_valid());
  19697. ws::WebSocketClient ws2("ws://example.com/path");
  19698. EXPECT_TRUE(ws2.is_valid());
  19699. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  19700. EXPECT_TRUE(ws3.is_valid());
  19701. #ifdef CPPHTTPLIB_SSL_ENABLED
  19702. ws::WebSocketClient wss1("wss://example.com/path");
  19703. EXPECT_TRUE(wss1.is_valid());
  19704. ws::WebSocketClient wss2("wss://example.com:443/path");
  19705. EXPECT_TRUE(wss2.is_valid());
  19706. #endif
  19707. }
  19708. TEST(WebSocketTest, InvalidURL) {
  19709. // No scheme
  19710. ws::WebSocketClient ws1("localhost:8080/path");
  19711. EXPECT_FALSE(ws1.is_valid());
  19712. // No path
  19713. ws::WebSocketClient ws2("ws://localhost:8080");
  19714. EXPECT_FALSE(ws2.is_valid());
  19715. // Empty string
  19716. ws::WebSocketClient ws3("");
  19717. EXPECT_FALSE(ws3.is_valid());
  19718. // Missing host
  19719. ws::WebSocketClient ws4("ws://:8080/path");
  19720. EXPECT_FALSE(ws4.is_valid());
  19721. // Port number overflow — should not crash
  19722. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  19723. EXPECT_FALSE(ws5.is_valid());
  19724. // Port out of range
  19725. ws::WebSocketClient ws6("ws://localhost:99999/path");
  19726. EXPECT_FALSE(ws6.is_valid());
  19727. }
  19728. TEST(WebSocketTest, UnsupportedScheme) {
  19729. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  19730. ws::WebSocketClient ws1("http://localhost:8080/path");
  19731. EXPECT_FALSE(ws1.is_valid());
  19732. ws::WebSocketClient ws2("https://localhost:8080/path");
  19733. EXPECT_FALSE(ws2.is_valid());
  19734. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  19735. EXPECT_FALSE(ws3.is_valid());
  19736. #else
  19737. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  19738. std::invalid_argument);
  19739. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  19740. std::invalid_argument);
  19741. #endif
  19742. }
  19743. TEST(WebSocketTest, ConnectWhenInvalid) {
  19744. ws::WebSocketClient ws("not a valid url");
  19745. EXPECT_FALSE(ws.is_valid());
  19746. auto res = ws.connect();
  19747. EXPECT_FALSE(res);
  19748. EXPECT_EQ(Error::Connection, res.error());
  19749. EXPECT_EQ(-1, res.status());
  19750. }
  19751. TEST(WebSocketTest, ConnectRefusedReportsError) {
  19752. // Grab a port that is free, then close it again so nothing listens there
  19753. Server svr;
  19754. auto port = svr.bind_to_any_port(HOST);
  19755. svr.stop();
  19756. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  19757. auto res = client.connect();
  19758. ASSERT_FALSE(res);
  19759. EXPECT_EQ(Error::Connection, res.error());
  19760. EXPECT_EQ(-1, res.status());
  19761. }
  19762. TEST(WebSocketTest, DefaultPort) {
  19763. ws::WebSocketClient ws1("ws://example.com/path");
  19764. EXPECT_TRUE(ws1.is_valid());
  19765. // ws:// defaults to port 80 (verified by successful parse)
  19766. #ifdef CPPHTTPLIB_SSL_ENABLED
  19767. ws::WebSocketClient ws2("wss://example.com/path");
  19768. EXPECT_TRUE(ws2.is_valid());
  19769. // wss:// defaults to port 443 (verified by successful parse)
  19770. #endif
  19771. }
  19772. TEST(WebSocketTest, IPv6LiteralAddress) {
  19773. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  19774. EXPECT_TRUE(ws1.is_valid());
  19775. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  19776. EXPECT_TRUE(ws2.is_valid());
  19777. }
  19778. TEST(WebSocketTest, ComplexPath) {
  19779. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  19780. EXPECT_TRUE(ws1.is_valid());
  19781. ws::WebSocketClient ws2("ws://localhost:8080/");
  19782. EXPECT_TRUE(ws2.is_valid());
  19783. }
  19784. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  19785. Server svr;
  19786. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  19787. std::string msg;
  19788. while (ws.read(msg)) {}
  19789. });
  19790. auto port = svr.bind_to_any_port(HOST);
  19791. std::thread t([&]() { svr.listen_after_bind(); });
  19792. svr.wait_until_ready();
  19793. auto another_host = "example.com";
  19794. auto wrong_ip = "192.0.2.1";
  19795. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  19796. client.set_hostname_addr_map({{another_host, wrong_ip}});
  19797. ASSERT_TRUE(client.connect());
  19798. EXPECT_TRUE(client.is_open());
  19799. client.close();
  19800. svr.stop();
  19801. t.join();
  19802. }
  19803. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  19804. Server svr;
  19805. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  19806. std::string msg;
  19807. while (ws.read(msg)) {}
  19808. });
  19809. auto port = svr.bind_to_any_port(HOST);
  19810. std::thread t([&]() { svr.listen_after_bind(); });
  19811. svr.wait_until_ready();
  19812. auto wrong_ip = "192.0.2.1";
  19813. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  19814. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  19815. client.set_connection_timeout(1);
  19816. client.set_read_timeout(1);
  19817. client.set_write_timeout(1);
  19818. EXPECT_FALSE(client.connect());
  19819. EXPECT_FALSE(client.is_open());
  19820. svr.stop();
  19821. t.join();
  19822. }
  19823. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  19824. // A mapped value that is not an IP literal must be resolved. HOST resolves
  19825. // from the hosts file, so this test needs no external DNS. "target.invalid"
  19826. // (RFC 6761) is only a map key and the Host header value.
  19827. auto host = "target.invalid";
  19828. Server svr;
  19829. std::string received_host;
  19830. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  19831. received_host = req.get_header_value("Host");
  19832. std::string msg;
  19833. while (ws.read(msg)) {}
  19834. });
  19835. auto port = svr.bind_to_any_port(HOST);
  19836. std::thread t([&]() { svr.listen_after_bind(); });
  19837. // ASSERT_* below returns from the test body, which would leave t joinable
  19838. // and make ~thread call std::terminate.
  19839. auto se = detail::scope_exit([&] {
  19840. svr.stop();
  19841. if (t.joinable()) { t.join(); }
  19842. });
  19843. svr.wait_until_ready();
  19844. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  19845. std::to_string(port) + "/ws");
  19846. client.set_hostname_addr_map({{host, HOST}});
  19847. ASSERT_TRUE(client.connect());
  19848. EXPECT_TRUE(client.is_open());
  19849. client.close();
  19850. svr.stop();
  19851. t.join();
  19852. // The mapping only redirects the connection; the identity stays host_.
  19853. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  19854. }
  19855. class WebSocketIntegrationTest : public ::testing::Test {
  19856. protected:
  19857. void SetUp() override {
  19858. server_ = httplib::detail::make_unique<Server>();
  19859. setup_server();
  19860. start_server();
  19861. }
  19862. void TearDown() override {
  19863. server_->stop();
  19864. if (server_thread_.joinable()) { server_thread_.join(); }
  19865. }
  19866. void setup_server() {
  19867. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  19868. std::string msg;
  19869. ws::ReadResult ret;
  19870. while ((ret = ws.read(msg))) {
  19871. if (ret == ws::Binary) {
  19872. ws.send(msg.data(), msg.size());
  19873. } else {
  19874. ws.send(msg);
  19875. }
  19876. }
  19877. });
  19878. server_->WebSocket("/ws-echo-string",
  19879. [](const Request &, ws::WebSocket &ws) {
  19880. std::string msg;
  19881. while (ws.read(msg)) {
  19882. ws.send("echo: " + msg);
  19883. }
  19884. });
  19885. server_->WebSocket(
  19886. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  19887. // Echo back request metadata
  19888. ws.send("path:" + req.path);
  19889. ws.send("header:" + req.get_header_value("X-Test-Header"));
  19890. std::string msg;
  19891. while (ws.read(msg)) {}
  19892. });
  19893. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  19894. std::string msg;
  19895. ws.read(msg); // wait for a message
  19896. ws.close();
  19897. });
  19898. server_->WebSocket("/ws-close-status",
  19899. [](const Request &, ws::WebSocket &ws) {
  19900. std::string msg;
  19901. ws.read(msg); // wait for a message
  19902. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  19903. });
  19904. server_->WebSocket(
  19905. "/ws-subprotocol",
  19906. [](const Request &, ws::WebSocket &ws) {
  19907. std::string msg;
  19908. while (ws.read(msg)) {
  19909. ws.send(msg);
  19910. }
  19911. },
  19912. [](const std::vector<std::string> &protocols) -> std::string {
  19913. for (const auto &p : protocols) {
  19914. if (p == "graphql-ws") { return p; }
  19915. }
  19916. return "";
  19917. });
  19918. }
  19919. void start_server() {
  19920. port_ = server_->bind_to_any_port(HOST);
  19921. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  19922. server_->wait_until_ready();
  19923. }
  19924. std::unique_ptr<Server> server_;
  19925. std::thread server_thread_;
  19926. int port_ = 0;
  19927. };
  19928. TEST_F(WebSocketIntegrationTest, TextEcho) {
  19929. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19930. "/ws-echo");
  19931. ASSERT_TRUE(client.connect());
  19932. ASSERT_TRUE(client.is_open());
  19933. ASSERT_TRUE(client.send("Hello WebSocket"));
  19934. std::string msg;
  19935. EXPECT_EQ(ws::Text, client.read(msg));
  19936. EXPECT_EQ("Hello WebSocket", msg);
  19937. client.close();
  19938. }
  19939. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  19940. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19941. "/ws-echo");
  19942. ASSERT_TRUE(client.connect());
  19943. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  19944. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  19945. std::string msg;
  19946. EXPECT_EQ(ws::Binary, client.read(msg));
  19947. EXPECT_EQ(binary_data, msg);
  19948. client.close();
  19949. }
  19950. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  19951. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19952. "/ws-echo");
  19953. ASSERT_TRUE(client.connect());
  19954. for (int i = 0; i < 10; i++) {
  19955. auto text = "message " + std::to_string(i);
  19956. ASSERT_TRUE(client.send(text));
  19957. std::string msg;
  19958. ASSERT_TRUE(client.read(msg));
  19959. EXPECT_EQ(text, msg);
  19960. }
  19961. client.close();
  19962. }
  19963. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  19964. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19965. "/ws-close");
  19966. ASSERT_TRUE(client.connect());
  19967. // Send a message to trigger the server to close
  19968. ASSERT_TRUE(client.send("trigger close"));
  19969. // The server will close, so read should return false
  19970. std::string msg;
  19971. EXPECT_FALSE(client.read(msg));
  19972. EXPECT_FALSE(client.is_open());
  19973. }
  19974. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  19975. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19976. "/ws-echo");
  19977. ASSERT_TRUE(client.connect());
  19978. // 128KB message
  19979. std::string large_data(128 * 1024, 'X');
  19980. ASSERT_TRUE(client.send(large_data));
  19981. std::string msg;
  19982. ASSERT_TRUE(client.read(msg));
  19983. EXPECT_EQ(large_data, msg);
  19984. client.close();
  19985. }
  19986. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  19987. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19988. "/ws-echo");
  19989. ASSERT_TRUE(client.connect());
  19990. const int num_threads = 4;
  19991. std::vector<std::thread> threads;
  19992. std::atomic<int> send_count{0};
  19993. for (int t = 0; t < num_threads; t++) {
  19994. threads.emplace_back([&client, &send_count, t]() {
  19995. for (int i = 0; i < 5; i++) {
  19996. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  19997. if (client.send(text)) { send_count++; }
  19998. }
  19999. });
  20000. }
  20001. for (auto &th : threads) {
  20002. th.join();
  20003. }
  20004. int received = 0;
  20005. std::string msg;
  20006. while (received < send_count.load()) {
  20007. if (!client.read(msg)) { break; }
  20008. received++;
  20009. }
  20010. EXPECT_EQ(send_count.load(), received);
  20011. client.close();
  20012. }
  20013. TEST_F(WebSocketIntegrationTest, ReadString) {
  20014. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20015. "/ws-echo-string");
  20016. ASSERT_TRUE(client.connect());
  20017. ASSERT_TRUE(client.send("hello"));
  20018. std::string msg;
  20019. ASSERT_TRUE(client.read(msg));
  20020. EXPECT_EQ("echo: hello", msg);
  20021. ASSERT_TRUE(client.send("world"));
  20022. ASSERT_TRUE(client.read(msg));
  20023. EXPECT_EQ("echo: world", msg);
  20024. client.close();
  20025. }
  20026. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  20027. Headers headers = {{"X-Test-Header", "test-value"}};
  20028. ws::WebSocketClient client(
  20029. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  20030. ASSERT_TRUE(client.connect());
  20031. std::string msg;
  20032. ASSERT_TRUE(client.read(msg));
  20033. EXPECT_EQ("path:/ws-request-info", msg);
  20034. ASSERT_TRUE(client.read(msg));
  20035. EXPECT_EQ("header:test-value", msg);
  20036. client.close();
  20037. }
  20038. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  20039. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20040. "/ws-echo");
  20041. client.set_read_timeout(1, 0); // 1 second
  20042. ASSERT_TRUE(client.connect());
  20043. // Don't send anything — server echo handler waits for a message, so read()
  20044. // should time out. The connection survives it: nothing was consumed.
  20045. std::string msg;
  20046. EXPECT_EQ(client.read(msg), ws::Timeout);
  20047. EXPECT_TRUE(client.is_open());
  20048. // And it is still usable afterwards.
  20049. EXPECT_TRUE(client.send("after timeout"));
  20050. EXPECT_EQ(client.read(msg), ws::Text);
  20051. EXPECT_EQ(msg, "after timeout");
  20052. }
  20053. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  20054. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20055. "/ws-echo");
  20056. client.set_read_timeout(1, 0);
  20057. ASSERT_TRUE(client.connect());
  20058. ASSERT_TRUE(client.send("first"));
  20059. std::string msg;
  20060. ASSERT_EQ(client.read(msg), ws::Text);
  20061. ASSERT_EQ(msg, "first");
  20062. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  20063. // not be used with a read timeout: it would reprocess the previous message.
  20064. EXPECT_EQ(client.read(msg), ws::Timeout);
  20065. EXPECT_EQ(msg, "first");
  20066. }
  20067. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  20068. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20069. "/ws-echo");
  20070. ASSERT_TRUE(client.connect());
  20071. // Setting it once the connection is open reaches the live stream, not just
  20072. // the seed for the next connect().
  20073. client.set_read_timeout(1, 0);
  20074. std::string msg;
  20075. EXPECT_EQ(client.read(msg), ws::Timeout);
  20076. EXPECT_TRUE(client.is_open());
  20077. }
  20078. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  20079. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20080. "/ws-echo");
  20081. client.set_read_timeout(5, 0);
  20082. ASSERT_TRUE(client.connect());
  20083. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  20084. // The server should reject it and close the connection.
  20085. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  20086. client.send(oversized);
  20087. // The server's read() should have failed due to payload limit,
  20088. // so our read() should return false (connection closed).
  20089. std::string msg;
  20090. EXPECT_FALSE(client.read(msg));
  20091. }
  20092. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  20093. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20094. "/ws-echo");
  20095. client.set_read_timeout(10, 0);
  20096. ASSERT_TRUE(client.connect());
  20097. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  20098. // This should succeed.
  20099. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  20100. ASSERT_TRUE(client.send(at_limit));
  20101. std::string msg;
  20102. ASSERT_TRUE(client.read(msg));
  20103. EXPECT_EQ(at_limit.size(), msg.size());
  20104. client.close();
  20105. }
  20106. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  20107. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20108. "/nonexistent");
  20109. auto res = client.connect();
  20110. EXPECT_FALSE(res);
  20111. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  20112. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  20113. EXPECT_FALSE(client.is_open());
  20114. }
  20115. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  20116. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20117. "/ws-echo");
  20118. ASSERT_TRUE(client.connect());
  20119. ASSERT_TRUE(client.send(""));
  20120. std::string msg;
  20121. EXPECT_EQ(ws::Text, client.read(msg));
  20122. EXPECT_EQ("", msg);
  20123. client.close();
  20124. }
  20125. TEST_F(WebSocketIntegrationTest, Reconnect) {
  20126. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20127. "/ws-echo");
  20128. // First connection
  20129. ASSERT_TRUE(client.connect());
  20130. ASSERT_TRUE(client.send("first"));
  20131. std::string msg;
  20132. ASSERT_TRUE(client.read(msg));
  20133. EXPECT_EQ("first", msg);
  20134. client.close();
  20135. EXPECT_FALSE(client.is_open());
  20136. // Reconnect using the same client object
  20137. ASSERT_TRUE(client.connect());
  20138. ASSERT_TRUE(client.is_open());
  20139. ASSERT_TRUE(client.send("second"));
  20140. ASSERT_TRUE(client.read(msg));
  20141. EXPECT_EQ("second", msg);
  20142. client.close();
  20143. }
  20144. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  20145. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20146. "/ws-close-status");
  20147. ASSERT_TRUE(client.connect());
  20148. // Trigger the server to close with GoingAway status
  20149. ASSERT_TRUE(client.send("trigger"));
  20150. // read() should return false after receiving the close frame
  20151. std::string msg;
  20152. EXPECT_FALSE(client.read(msg));
  20153. EXPECT_FALSE(client.is_open());
  20154. }
  20155. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  20156. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20157. "/ws-echo");
  20158. ASSERT_TRUE(client.connect());
  20159. client.close(ws::CloseStatus::GoingAway, "client leaving");
  20160. EXPECT_FALSE(client.is_open());
  20161. }
  20162. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  20163. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  20164. ws::WebSocketClient client(
  20165. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  20166. ASSERT_TRUE(client.connect());
  20167. // Server should have selected graphql-ws
  20168. EXPECT_EQ("graphql-ws", client.subprotocol());
  20169. client.close();
  20170. }
  20171. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  20172. Headers headers;
  20173. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  20174. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  20175. ws::WebSocketClient client(
  20176. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  20177. ASSERT_TRUE(client.connect());
  20178. // The offer on the second field line counts too, so graphql-ws is selected
  20179. EXPECT_EQ("graphql-ws", client.subprotocol());
  20180. client.close();
  20181. }
  20182. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  20183. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  20184. ws::WebSocketClient client(
  20185. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  20186. ASSERT_TRUE(client.connect());
  20187. // Server should not have selected any subprotocol
  20188. EXPECT_TRUE(client.subprotocol().empty());
  20189. client.close();
  20190. }
  20191. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  20192. // Connect without requesting any subprotocol
  20193. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20194. "/ws-subprotocol");
  20195. ASSERT_TRUE(client.connect());
  20196. EXPECT_TRUE(client.subprotocol().empty());
  20197. client.close();
  20198. }
  20199. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  20200. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20201. "/ws-echo");
  20202. client.set_tcp_nodelay(true);
  20203. client.set_connection_timeout(3, 0);
  20204. bool socket_options_called = false;
  20205. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  20206. ASSERT_TRUE(client.connect());
  20207. ASSERT_TRUE(client.is_open());
  20208. EXPECT_TRUE(socket_options_called);
  20209. ASSERT_TRUE(client.send("hello"));
  20210. std::string msg;
  20211. auto result = client.read(msg);
  20212. EXPECT_EQ(result, ws::ReadResult::Text);
  20213. EXPECT_EQ(msg, "hello");
  20214. client.close();
  20215. }
  20216. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  20217. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20218. "/ws-echo");
  20219. client.set_connection_timeout(std::chrono::seconds(3));
  20220. client.set_write_timeout(std::chrono::seconds(3));
  20221. // A sub-second remainder exercises the seconds/microseconds split.
  20222. client.set_read_timeout(std::chrono::milliseconds(1500));
  20223. ASSERT_TRUE(client.connect());
  20224. auto start = std::chrono::steady_clock::now();
  20225. std::string msg;
  20226. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  20227. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  20228. std::chrono::steady_clock::now() - start)
  20229. .count();
  20230. // Above 1s so that dropping the microseconds half of the split fails here.
  20231. // Ignoring the setter altogether would not reach this line at all: a client
  20232. // waits forever by default.
  20233. EXPECT_GE(elapsed, 1400);
  20234. EXPECT_LT(elapsed, 30000);
  20235. }
  20236. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  20237. Server svr;
  20238. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  20239. if (!req.has_header("Authorization")) {
  20240. res.status = StatusCode::Unauthorized_401;
  20241. res.set_content("Unauthorized", "text/plain");
  20242. return Server::HandlerResponse::Handled;
  20243. }
  20244. return Server::HandlerResponse::Unhandled;
  20245. });
  20246. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20247. std::string msg;
  20248. while (ws.read(msg)) {
  20249. ws.send(msg);
  20250. }
  20251. });
  20252. auto port = svr.bind_to_any_port("localhost");
  20253. std::thread t([&]() { svr.listen_after_bind(); });
  20254. svr.wait_until_ready();
  20255. // Without Authorization header - should be rejected before upgrade
  20256. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  20257. EXPECT_FALSE(client1.connect());
  20258. // The rejection is framed like any other HTTP response
  20259. {
  20260. Client cli("localhost", port);
  20261. Headers headers = {{"Upgrade", "websocket"},
  20262. {"Connection", "Upgrade"},
  20263. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  20264. {"Sec-WebSocket-Version", "13"}};
  20265. auto res = cli.Get("/ws", headers);
  20266. ASSERT_TRUE(res);
  20267. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  20268. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  20269. EXPECT_EQ("Unauthorized", res->body);
  20270. }
  20271. // With Authorization header - should succeed
  20272. Headers headers = {{"Authorization", "Bearer token123"}};
  20273. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  20274. headers);
  20275. ASSERT_TRUE(client2.connect());
  20276. ASSERT_TRUE(client2.send("hello"));
  20277. std::string msg;
  20278. ASSERT_TRUE(client2.read(msg));
  20279. EXPECT_EQ("hello", msg);
  20280. client2.close();
  20281. svr.stop();
  20282. t.join();
  20283. }
  20284. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  20285. Server svr;
  20286. std::atomic<int> pre_request_calls{0};
  20287. std::atomic<bool> route_matched{false};
  20288. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  20289. pre_request_calls++;
  20290. if (req.matched_route == "/ws/:id") { route_matched = true; }
  20291. if (req.get_header_value("Authorization") != "Bearer token123") {
  20292. res.status = StatusCode::Unauthorized_401;
  20293. res.set_content("Unauthorized", "text/plain");
  20294. return Server::HandlerResponse::Handled;
  20295. }
  20296. return Server::HandlerResponse::Unhandled;
  20297. });
  20298. std::atomic<bool> handler_called{false};
  20299. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  20300. handler_called = true;
  20301. ws.send(req.matched_route + " " + req.path_params.at("id"));
  20302. });
  20303. auto port = svr.bind_to_any_port("localhost");
  20304. std::thread t([&]() { svr.listen_after_bind(); });
  20305. svr.wait_until_ready();
  20306. // Without Authorization header - should be rejected before upgrade
  20307. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  20308. "/ws/1");
  20309. EXPECT_FALSE(client1.connect());
  20310. EXPECT_FALSE(handler_called);
  20311. EXPECT_EQ(1, pre_request_calls);
  20312. EXPECT_TRUE(route_matched);
  20313. // The rejection is an ordinary HTTP response, not a protocol switch
  20314. {
  20315. Client cli("localhost", port);
  20316. Headers headers = {{"Upgrade", "websocket"},
  20317. {"Connection", "Upgrade"},
  20318. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  20319. {"Sec-WebSocket-Version", "13"}};
  20320. auto res = cli.Get("/ws/1", headers);
  20321. ASSERT_TRUE(res);
  20322. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  20323. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  20324. EXPECT_EQ("Unauthorized", res->body);
  20325. }
  20326. EXPECT_FALSE(handler_called);
  20327. // With Authorization header - should succeed
  20328. Headers headers = {{"Authorization", "Bearer token123"}};
  20329. ws::WebSocketClient client2(
  20330. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  20331. ASSERT_TRUE(client2.connect());
  20332. std::string msg;
  20333. ASSERT_TRUE(client2.read(msg));
  20334. EXPECT_EQ("/ws/:id 2", msg);
  20335. EXPECT_TRUE(handler_called);
  20336. client2.close();
  20337. svr.stop();
  20338. t.join();
  20339. }
  20340. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  20341. Server svr;
  20342. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20343. // A read timeout is how a handler gets control back. Without it, a handler
  20344. // parked in read() can never write on the connection it is reading.
  20345. ws.set_read_timeout(std::chrono::milliseconds(100));
  20346. std::string msg;
  20347. while (ws.is_open()) {
  20348. auto r = ws.read(msg);
  20349. if (r == httplib::ws::Timeout) {
  20350. ws.send("tick");
  20351. continue;
  20352. }
  20353. if (r == httplib::ws::Fail) { break; }
  20354. ws.send(msg);
  20355. }
  20356. });
  20357. auto port = svr.bind_to_any_port("localhost");
  20358. std::thread t([&]() { svr.listen_after_bind(); });
  20359. svr.wait_until_ready();
  20360. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20361. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  20362. ASSERT_TRUE(client.connect());
  20363. // The client sends nothing, so anything it receives came out of the
  20364. // handler's timeout path.
  20365. std::string msg;
  20366. ASSERT_EQ(client.read(msg), ws::Text);
  20367. EXPECT_EQ("tick", msg);
  20368. client.close();
  20369. svr.stop();
  20370. t.join();
  20371. }
  20372. // Stream::read may return fewer bytes than asked for. This is that contract at
  20373. // its worst -- one byte per call -- which is what a frame header straddling a
  20374. // read buffer's boundary looks like to the frame parser.
  20375. class WsByteAtATimeStream : public Stream {
  20376. public:
  20377. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  20378. bool is_readable() const override { return true; }
  20379. bool wait_readable() const override { return true; }
  20380. bool wait_writable() const override { return true; }
  20381. ssize_t read(char *ptr, size_t size) override {
  20382. if (size == 0 || pos_ >= data_.size()) { return 0; }
  20383. *ptr = data_[pos_++];
  20384. return 1;
  20385. }
  20386. ssize_t write(const char *, size_t size) override {
  20387. return static_cast<ssize_t>(size);
  20388. }
  20389. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  20390. ip = "127.0.0.1";
  20391. port = 0;
  20392. }
  20393. void get_local_ip_and_port(std::string &ip, int &port) const override {
  20394. ip = "127.0.0.1";
  20395. port = 0;
  20396. }
  20397. socket_t socket() const override { return INVALID_SOCKET; }
  20398. time_t duration() const override { return 0; }
  20399. private:
  20400. std::string data_;
  20401. size_t pos_ = 0;
  20402. };
  20403. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  20404. // A 200-byte payload uses the 16-bit extended length, so the header, the
  20405. // length and the mask key are all multi-byte fields here. Each used to be
  20406. // read with a single read() call, which fails as soon as one is split.
  20407. std::string body(200, 'x');
  20408. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  20409. std::string frame;
  20410. frame += static_cast<char>(0x81); // FIN + Text
  20411. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  20412. frame += static_cast<char>(body.size() >> 8);
  20413. frame += static_cast<char>(body.size() & 0xff);
  20414. for (size_t i = 0; i < 4; i++) {
  20415. frame += static_cast<char>(mask[i]);
  20416. }
  20417. for (size_t i = 0; i < body.size(); i++) {
  20418. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  20419. }
  20420. WsByteAtATimeStream strm(frame);
  20421. ws::Opcode opcode;
  20422. std::string payload;
  20423. bool fin = false;
  20424. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  20425. /*expect_masked=*/true, 1024),
  20426. ws::impl::FrameRead::Ok);
  20427. EXPECT_TRUE(fin);
  20428. EXPECT_EQ(opcode, ws::Opcode::Text);
  20429. EXPECT_EQ(payload, body);
  20430. }
  20431. TEST(WebSocketTest, QueryStringInHandshake) {
  20432. Server svr;
  20433. std::mutex mtx;
  20434. std::string received_target;
  20435. std::string received_token;
  20436. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  20437. {
  20438. std::lock_guard<std::mutex> lock(mtx);
  20439. received_target = req.target;
  20440. if (req.has_param("token")) {
  20441. received_token = req.get_param_value("token");
  20442. }
  20443. }
  20444. std::string msg;
  20445. while (ws.read(msg)) {
  20446. ws.send(msg);
  20447. }
  20448. });
  20449. auto port = svr.bind_to_any_port("localhost");
  20450. std::thread t([&]() { svr.listen_after_bind(); });
  20451. svr.wait_until_ready();
  20452. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  20453. "/ws?token=ABC&session=123");
  20454. ASSERT_TRUE(client.connect());
  20455. // Round-trip ensures the handler has run and captured the request.
  20456. ASSERT_TRUE(client.send("hello"));
  20457. std::string msg;
  20458. ASSERT_TRUE(client.read(msg));
  20459. EXPECT_EQ("hello", msg);
  20460. client.close();
  20461. {
  20462. std::lock_guard<std::mutex> lock(mtx);
  20463. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  20464. EXPECT_EQ("ABC", received_token);
  20465. }
  20466. svr.stop();
  20467. t.join();
  20468. }
  20469. // Run a handshake against a throwaway server and hand the request the server
  20470. // received back to the caller, so tests can assert on the headers the client
  20471. // actually put on the wire.
  20472. static void capture_websocket_handshake_request(
  20473. const Headers &client_headers,
  20474. std::function<void(const Request &, int port)> verify) {
  20475. Server svr;
  20476. std::mutex mtx;
  20477. Request received;
  20478. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  20479. {
  20480. std::lock_guard<std::mutex> lock(mtx);
  20481. received = req;
  20482. }
  20483. std::string msg;
  20484. while (ws.read(msg)) {
  20485. ws.send(msg);
  20486. }
  20487. });
  20488. auto port = svr.bind_to_any_port("localhost");
  20489. std::thread t([&]() { svr.listen_after_bind(); });
  20490. auto se = detail::scope_exit([&] {
  20491. svr.stop();
  20492. t.join();
  20493. });
  20494. svr.wait_until_ready();
  20495. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  20496. client_headers);
  20497. ASSERT_TRUE(client.connect());
  20498. ASSERT_TRUE(client.send("hello"));
  20499. std::string msg;
  20500. ASSERT_TRUE(client.read(msg));
  20501. client.close();
  20502. {
  20503. std::lock_guard<std::mutex> lock(mtx);
  20504. verify(received, port);
  20505. }
  20506. }
  20507. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  20508. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  20509. // Non-default port must be present in the Host header. Default ports
  20510. // (80/443) are omitted; that logic is covered by
  20511. // MakeHostAndPortStringTest.
  20512. EXPECT_EQ("localhost:" + std::to_string(port),
  20513. req.get_header_value("Host"));
  20514. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  20515. req.get_header_value("User-Agent"));
  20516. EXPECT_FALSE(req.has_header("Accept"));
  20517. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  20518. EXPECT_FALSE(req.has_header("Content-Length"));
  20519. });
  20520. }
  20521. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  20522. capture_websocket_handshake_request(
  20523. {{"Host", "example.com"},
  20524. {"User-Agent", "custom-agent"},
  20525. {"X-Custom", "value"}},
  20526. [](const Request &req, int) {
  20527. EXPECT_EQ("example.com", req.get_header_value("Host"));
  20528. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  20529. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  20530. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  20531. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  20532. });
  20533. }
  20534. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  20535. capture_websocket_handshake_request(
  20536. {{"Upgrade", "bogus"},
  20537. {"Connection", "close"},
  20538. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  20539. {"Sec-WebSocket-Version", "8"}},
  20540. [](const Request &req, int) {
  20541. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  20542. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  20543. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  20544. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  20545. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  20546. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  20547. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  20548. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  20549. req.get_header_value("Sec-WebSocket-Key"));
  20550. });
  20551. }
  20552. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  20553. // A header the client refuses to send must abort the handshake before any
  20554. // part of it reaches the wire; a lone request line would otherwise sit in
  20555. // the peer's buffer as a truncated request.
  20556. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  20557. ASSERT_NE(INVALID_SOCKET, srv);
  20558. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  20559. sockaddr_in addr{};
  20560. addr.sin_family = AF_INET;
  20561. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  20562. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  20563. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  20564. ASSERT_EQ(0, ::listen(srv, 1));
  20565. sockaddr_in bound{};
  20566. socklen_t bound_len = sizeof(bound);
  20567. ASSERT_EQ(
  20568. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  20569. auto port = ntohs(bound.sin_port);
  20570. ssize_t received = -1;
  20571. std::thread t([&] {
  20572. // Bound every blocking call so a regression fails the test with a bad
  20573. // value instead of hanging the suite.
  20574. fd_set rfds;
  20575. FD_ZERO(&rfds);
  20576. FD_SET(srv, &rfds);
  20577. timeval tv{5, 0};
  20578. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  20579. 0) {
  20580. return;
  20581. }
  20582. sockaddr_in cli_addr{};
  20583. socklen_t cli_len = sizeof(cli_addr);
  20584. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  20585. if (cli == INVALID_SOCKET) { return; }
  20586. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  20587. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  20588. char buf[4096];
  20589. received = ::recv(cli, buf, sizeof(buf), 0);
  20590. });
  20591. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  20592. // connect() has already shut the socket down by the time it returns false,
  20593. // so the peer sees EOF without waiting for the client to be destroyed.
  20594. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  20595. {{"X-Bad", "a\r\nInjected: 1"}});
  20596. EXPECT_FALSE(client.connect());
  20597. t.join();
  20598. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  20599. EXPECT_EQ(0, received);
  20600. }
  20601. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  20602. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  20603. // contains "upgrade" as a substring is a different token and must not
  20604. // start a WebSocket handshake.
  20605. auto make_request = [](const std::vector<std::string> &connection_values) {
  20606. Request req;
  20607. req.method = "GET";
  20608. req.headers.emplace("Upgrade", "websocket");
  20609. for (const auto &value : connection_values) {
  20610. req.headers.emplace("Connection", value);
  20611. }
  20612. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  20613. req.headers.emplace("Sec-WebSocket-Version", "13");
  20614. return req;
  20615. };
  20616. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  20617. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  20618. EXPECT_TRUE(
  20619. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  20620. EXPECT_TRUE(
  20621. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  20622. EXPECT_TRUE(
  20623. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  20624. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  20625. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  20626. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  20627. EXPECT_FALSE(
  20628. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  20629. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  20630. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  20631. }
  20632. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  20633. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  20634. // asks recipients to match each protocol-name case-insensitively, and RFC
  20635. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  20636. // client naming websocket alongside another protocol, or on a second field
  20637. // line, is offering websocket; a value that merely contains "websocket" as a
  20638. // substring is a different protocol name and is not.
  20639. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  20640. Request req;
  20641. req.method = "GET";
  20642. for (const auto &value : upgrade_values) {
  20643. req.headers.emplace("Upgrade", value);
  20644. }
  20645. req.headers.emplace("Connection", "Upgrade");
  20646. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  20647. req.headers.emplace("Sec-WebSocket-Version", "13");
  20648. return req;
  20649. };
  20650. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  20651. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  20652. EXPECT_TRUE(
  20653. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  20654. EXPECT_TRUE(
  20655. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  20656. EXPECT_TRUE(
  20657. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  20658. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  20659. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  20660. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  20661. EXPECT_FALSE(
  20662. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  20663. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  20664. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  20665. }
  20666. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  20667. Server svr;
  20668. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  20669. auto port = svr.bind_to_any_port("localhost");
  20670. std::thread t([&]() { svr.listen_after_bind(); });
  20671. auto se = detail::scope_exit([&] {
  20672. svr.stop();
  20673. t.join();
  20674. });
  20675. svr.wait_until_ready();
  20676. Headers headers = {{"Upgrade", "websocket"},
  20677. {"Connection", "notupgrade"},
  20678. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  20679. {"Sec-WebSocket-Version", "13"}};
  20680. Client cli("localhost", port);
  20681. auto res = cli.Get("/ws", headers);
  20682. // The route exists only as a WebSocket route, so a request that fails the
  20683. // handshake check falls through to ordinary routing.
  20684. ASSERT_TRUE(res);
  20685. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  20686. }
  20687. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  20688. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  20689. // Connection value is the only thing left for the client to reject.
  20690. Server svr;
  20691. svr.Get("/ws", [](const Request &req, Response &res) {
  20692. res.status = StatusCode::SwitchingProtocol_101;
  20693. res.set_header("Upgrade", "websocket");
  20694. res.set_header("Connection", "notupgrade");
  20695. res.set_header("Sec-WebSocket-Accept",
  20696. detail::websocket_accept_key(
  20697. req.get_header_value("Sec-WebSocket-Key")));
  20698. });
  20699. auto port = svr.bind_to_any_port("localhost");
  20700. std::thread t([&]() { svr.listen_after_bind(); });
  20701. auto se = detail::scope_exit([&] {
  20702. svr.stop();
  20703. t.join();
  20704. });
  20705. svr.wait_until_ready();
  20706. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20707. auto res = client.connect();
  20708. EXPECT_FALSE(res);
  20709. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  20710. EXPECT_FALSE(client.is_open());
  20711. }
  20712. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  20713. // The socket path doubles as the URL host, so it must not contain '/'.
  20714. const char *shard = getenv("GTEST_SHARD_INDEX");
  20715. const std::string sock_path =
  20716. shard ? std::string("httplib-ws-") + shard + ".sock"
  20717. : std::string("httplib-ws.sock");
  20718. std::remove(sock_path.c_str());
  20719. Server svr;
  20720. std::mutex mtx;
  20721. std::string received_host;
  20722. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  20723. {
  20724. std::lock_guard<std::mutex> lock(mtx);
  20725. received_host = req.get_header_value("Host");
  20726. }
  20727. std::string msg;
  20728. while (ws.read(msg)) {
  20729. ws.send(msg);
  20730. }
  20731. });
  20732. svr.set_address_family(AF_UNIX);
  20733. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  20734. auto se = detail::scope_exit([&] {
  20735. svr.stop();
  20736. t.join();
  20737. std::remove(sock_path.c_str());
  20738. });
  20739. svr.wait_until_ready();
  20740. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  20741. client.set_address_family(AF_UNIX);
  20742. ASSERT_TRUE(client.connect());
  20743. ASSERT_TRUE(client.send("hello"));
  20744. std::string msg;
  20745. ASSERT_TRUE(client.read(msg));
  20746. client.close();
  20747. {
  20748. std::lock_guard<std::mutex> lock(mtx);
  20749. // There is no host:port for a Unix socket, so the same "localhost"
  20750. // placeholder the HTTP client uses is expected.
  20751. EXPECT_EQ("localhost", received_host);
  20752. }
  20753. }
  20754. // Two threads must never parse WebSocket frames from the same stream.
  20755. // close() used to read the peer's Close reply with its own frame read, so it
  20756. // raced a reader thread that was in the middle of a payload: the payload loop
  20757. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  20758. // so bytes taken by close() were replaced with bytes from further along the
  20759. // stream. The message kept its length and silently changed content.
  20760. //
  20761. // The raw peer below sends a frame header plus part of the payload, waits for
  20762. // the handler to call close(), and only then sends the rest. Whichever thread
  20763. // would win the race for those bytes, the message must arrive intact, because
  20764. // close() must not touch the stream while read() owns it.
  20765. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  20766. #ifndef _WIN32
  20767. signal(SIGPIPE, SIG_IGN);
  20768. #endif
  20769. const size_t payload_len = 120; // fits the 7-bit length field
  20770. const size_t prefix_len = 8;
  20771. const int attempts = 8;
  20772. std::string expected(payload_len, '\0');
  20773. for (size_t i = 0; i < payload_len; i++) {
  20774. expected[i] = static_cast<char>('a' + i % 26);
  20775. }
  20776. std::atomic<bool> peer_stalled{false};
  20777. std::atomic<bool> handler_done{false};
  20778. std::mutex received_mutex;
  20779. std::vector<std::string> received;
  20780. // Bound every wait, so a regression fails the test instead of hanging the
  20781. // suite.
  20782. auto wait_for = [](const std::atomic<bool> &flag) {
  20783. for (int i = 0; i < 500 && !flag; i++) {
  20784. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20785. }
  20786. };
  20787. Server svr;
  20788. svr.set_websocket_ping_interval(0);
  20789. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  20790. std::thread reader([&]() {
  20791. std::string msg;
  20792. while (ws.read(msg)) {
  20793. std::lock_guard<std::mutex> guard(received_mutex);
  20794. received.push_back(msg);
  20795. }
  20796. });
  20797. // Wait until the peer stalls mid-payload, so the reader thread is parked
  20798. // inside read_websocket_frame() when close() runs.
  20799. wait_for(peer_stalled);
  20800. ws.close();
  20801. reader.join();
  20802. handler_done = true;
  20803. });
  20804. auto port = svr.bind_to_any_port("127.0.0.1");
  20805. std::thread t([&]() { svr.listen_after_bind(); });
  20806. auto se = detail::scope_exit([&] {
  20807. svr.stop();
  20808. t.join();
  20809. });
  20810. svr.wait_until_ready();
  20811. auto send_bytes = [](socket_t s, const std::string &data) {
  20812. #ifdef _WIN32
  20813. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  20814. #else
  20815. auto n = ::send(s, data.data(), data.size(), 0);
  20816. #endif
  20817. return n == static_cast<decltype(n)>(data.size());
  20818. };
  20819. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  20820. // Every length used here fits the 7-bit length field.
  20821. auto masked_header = [](uint8_t first_byte, size_t len) {
  20822. std::string h;
  20823. h += static_cast<char>(first_byte);
  20824. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  20825. h.append(4, '\0'); // mask key
  20826. return h;
  20827. };
  20828. for (int attempt = 0; attempt < attempts; attempt++) {
  20829. peer_stalled = false;
  20830. handler_done = false;
  20831. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  20832. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  20833. auto se_sock = detail::scope_exit([&] {
  20834. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  20835. });
  20836. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  20837. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  20838. sockaddr_in addr{};
  20839. addr.sin_family = AF_INET;
  20840. addr.sin_port = htons(static_cast<uint16_t>(port));
  20841. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  20842. ASSERT_EQ(
  20843. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  20844. << "attempt " << attempt;
  20845. ASSERT_TRUE(send_bytes(sock,
  20846. "GET /ws HTTP/1.1\r\n"
  20847. "Host: 127.0.0.1\r\n"
  20848. "Upgrade: websocket\r\n"
  20849. "Connection: Upgrade\r\n"
  20850. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  20851. "Sec-WebSocket-Version: 13\r\n"
  20852. "\r\n"))
  20853. << "attempt " << attempt;
  20854. std::string response;
  20855. while (response.find("\r\n\r\n") == std::string::npos) {
  20856. char buf[512];
  20857. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  20858. if (n <= 0) { break; }
  20859. response.append(buf, static_cast<size_t>(n));
  20860. }
  20861. ASSERT_NE(std::string::npos, response.find(" 101 "))
  20862. << "attempt " << attempt;
  20863. // Send the header of a Binary message but only the first prefix_len bytes
  20864. // of its payload, leaving the reader thread stalled inside the payload.
  20865. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  20866. expected.substr(0, prefix_len)))
  20867. << "attempt " << attempt;
  20868. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20869. peer_stalled = true;
  20870. // Let close() send its Close frame and park in its own read before the
  20871. // rest of the payload arrives, so both threads are waiting for it.
  20872. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20873. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  20874. close_frame += static_cast<char>(0x03); // status 1000
  20875. close_frame += static_cast<char>(0xE8);
  20876. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  20877. << "attempt " << attempt;
  20878. // Closing the peer releases the reader thread even on the buggy path,
  20879. // where it waits for bytes another thread already consumed.
  20880. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20881. detail::close_socket(sock);
  20882. sock = INVALID_SOCKET;
  20883. wait_for(handler_done);
  20884. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  20885. }
  20886. std::lock_guard<std::mutex> guard(received_mutex);
  20887. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  20888. << "a message in flight when close() ran was dropped";
  20889. for (size_t i = 0; i < received.size(); i++) {
  20890. EXPECT_EQ(expected, received[i]) << "message " << i;
  20891. }
  20892. }
  20893. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  20894. class WebSocketSSLIntegrationTest : public ::testing::Test {
  20895. protected:
  20896. void SetUp() override {
  20897. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  20898. SERVER_PRIVATE_KEY_FILE);
  20899. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  20900. std::string msg;
  20901. ws::ReadResult ret;
  20902. while ((ret = ws.read(msg))) {
  20903. if (ret == ws::Binary) {
  20904. ws.send(msg.data(), msg.size());
  20905. } else {
  20906. ws.send(msg);
  20907. }
  20908. }
  20909. });
  20910. port_ = server_->bind_to_any_port(HOST);
  20911. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  20912. server_->wait_until_ready();
  20913. }
  20914. void TearDown() override {
  20915. server_->stop();
  20916. if (server_thread_.joinable()) { server_thread_.join(); }
  20917. }
  20918. std::unique_ptr<SSLServer> server_;
  20919. std::thread server_thread_;
  20920. int port_ = 0;
  20921. };
  20922. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  20923. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  20924. "/ws-echo");
  20925. client.enable_server_certificate_verification(false);
  20926. ASSERT_TRUE(client.connect());
  20927. ASSERT_TRUE(client.is_open());
  20928. ASSERT_TRUE(client.send("Hello WSS"));
  20929. std::string msg;
  20930. EXPECT_EQ(ws::Text, client.read(msg));
  20931. EXPECT_EQ("Hello WSS", msg);
  20932. client.close();
  20933. }
  20934. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  20935. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  20936. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  20937. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  20938. // client (without calling close() first) is the only path that runs
  20939. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  20940. // bug exactly.
  20941. //
  20942. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  20943. // when linked against an instrumented libssl; run under Valgrind to catch it
  20944. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  20945. // suite (the freed session otherwise stalls on the close handshake) — this test
  20946. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  20947. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  20948. {
  20949. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  20950. "/ws-echo");
  20951. client.enable_server_certificate_verification(false);
  20952. client.set_read_timeout(2, 0);
  20953. client.set_write_timeout(2, 0);
  20954. ASSERT_TRUE(client.connect());
  20955. ASSERT_TRUE(client.is_open());
  20956. ASSERT_TRUE(client.send("still open"));
  20957. // Intentionally do NOT call client.close(): leaving scope runs
  20958. // shutdown_and_close() with the WebSocket still open, which must send the
  20959. // close frame while the TLS session is still alive.
  20960. }
  20961. }
  20962. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  20963. // shutdown_and_close() at the start of connect(), reproducing the same
  20964. // use-after-free within the test body rather than at scope exit. The second
  20965. // connect must succeed and echo, proving the close handshake ran over a live
  20966. // session. See the note above about memory-tool requirements.
  20967. TEST_F(WebSocketSSLIntegrationTest,
  20968. ReconnectWhileOpenSendsCloseOverLiveSession) {
  20969. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  20970. "/ws-echo");
  20971. client.enable_server_certificate_verification(false);
  20972. client.set_read_timeout(2, 0);
  20973. client.set_write_timeout(2, 0);
  20974. ASSERT_TRUE(client.connect());
  20975. ASSERT_TRUE(client.is_open());
  20976. ASSERT_TRUE(client.send("still open"));
  20977. // Reconnect without closing first: connect() calls shutdown_and_close() on
  20978. // the still-open connection, which must not touch a freed TLS session.
  20979. ASSERT_TRUE(client.connect());
  20980. ASSERT_TRUE(client.is_open());
  20981. ASSERT_TRUE(client.send("after reconnect"));
  20982. std::string msg;
  20983. EXPECT_EQ(ws::Text, client.read(msg));
  20984. EXPECT_EQ("after reconnect", msg);
  20985. client.close();
  20986. }
  20987. #endif
  20988. #ifdef CPPHTTPLIB_SSL_ENABLED
  20989. class WebSocketSSLCATest : public ::testing::Test {
  20990. protected:
  20991. void SetUp() override {
  20992. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  20993. SERVER_PRIVATE_KEY_FILE);
  20994. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  20995. std::string msg;
  20996. while (ws.read(msg)) {
  20997. ws.send(msg);
  20998. }
  20999. });
  21000. port_ = server_->bind_to_any_port("127.0.0.1");
  21001. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21002. server_->wait_until_ready();
  21003. }
  21004. void TearDown() override {
  21005. server_->stop();
  21006. if (server_thread_.joinable()) { server_thread_.join(); }
  21007. }
  21008. std::string url() const {
  21009. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  21010. }
  21011. std::unique_ptr<SSLServer> server_;
  21012. std::thread server_thread_;
  21013. int port_ = 0;
  21014. };
  21015. // A custom CA loaded as PEM verifies the server with full certificate
  21016. // verification enabled
  21017. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  21018. ws::WebSocketClient client(url());
  21019. std::string cert;
  21020. read_file(SERVER_CERT2_FILE, cert);
  21021. client.load_ca_cert_store(cert.c_str(), cert.size());
  21022. ASSERT_TRUE(client.connect());
  21023. ASSERT_TRUE(client.send("hello"));
  21024. std::string msg;
  21025. EXPECT_EQ(ws::Text, client.read(msg));
  21026. EXPECT_EQ("hello", msg);
  21027. client.close();
  21028. }
  21029. // A custom CA that does not cover the server must fail verification (the
  21030. // custom CA is exclusive; system certs are not loaded alongside it)
  21031. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  21032. ws::WebSocketClient client(url());
  21033. std::string cert;
  21034. read_file(CLIENT_CA_CERT_FILE, cert);
  21035. client.load_ca_cert_store(cert.c_str(), cert.size());
  21036. auto res = client.connect();
  21037. ASSERT_FALSE(res);
  21038. EXPECT_EQ(Error::SSLServerVerification, res.error());
  21039. EXPECT_EQ(-1, res.status());
  21040. EXPECT_NE(0u, res.ssl_backend_error());
  21041. }
  21042. // The same CA as a file path rather than PEM in memory
  21043. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  21044. ws::WebSocketClient client(url());
  21045. client.set_ca_cert_path(SERVER_CERT2_FILE);
  21046. ASSERT_TRUE(client.connect());
  21047. ASSERT_TRUE(client.send("hello"));
  21048. std::string msg;
  21049. EXPECT_EQ(ws::Text, client.read(msg));
  21050. EXPECT_EQ("hello", msg);
  21051. client.close();
  21052. }
  21053. // ...and a CA file that does not cover the server still fails, so it is the
  21054. // path above that decides the outcome
  21055. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  21056. ws::WebSocketClient client(url());
  21057. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  21058. ASSERT_FALSE(client.connect());
  21059. }
  21060. // Regression test: reconnecting with a native custom CA store used to reuse
  21061. // a store handle the previous TLS context had already freed (use-after-free
  21062. // under the OpenSSL backend). The context now lives as long as the client.
  21063. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  21064. ws::WebSocketClient client(url());
  21065. std::string cert;
  21066. read_file(SERVER_CERT2_FILE, cert);
  21067. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  21068. ASSERT_TRUE(client.connect());
  21069. client.close();
  21070. ASSERT_TRUE(client.connect());
  21071. ASSERT_TRUE(client.send("again"));
  21072. std::string msg;
  21073. EXPECT_EQ(ws::Text, client.read(msg));
  21074. EXPECT_EQ("again", msg);
  21075. client.close();
  21076. }
  21077. // Regression test: a certificate with a trusted chain but no identity match
  21078. // for the server IP must be rejected. The Mbed TLS backend used to skip
  21079. // verification entirely for IP hosts, so this connection succeeded there.
  21080. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  21081. // chain verification while the identity check must still fail.
  21082. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  21083. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21084. ASSERT_TRUE(svr.is_valid());
  21085. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  21086. std::string msg;
  21087. while (ws.read(msg)) {
  21088. ws.send(msg);
  21089. }
  21090. });
  21091. auto port = svr.bind_to_any_port("127.0.0.1");
  21092. auto t = std::thread([&]() { svr.listen_after_bind(); });
  21093. auto se = detail::scope_exit([&] {
  21094. svr.stop();
  21095. t.join();
  21096. });
  21097. svr.wait_until_ready();
  21098. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  21099. "/echo");
  21100. std::string cert;
  21101. read_file(SERVER_CERT_FILE, cert);
  21102. client.load_ca_cert_store(cert.c_str(), cert.size());
  21103. ASSERT_FALSE(client.connect());
  21104. }
  21105. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  21106. // SNI, so nothing binds the host name to the TLS session. These bind the
  21107. // server to "localhost" instead, the only shape that exercises the SNI and
  21108. // hostname-verification path with certificate verification left enabled.
  21109. class WebSocketSSLDnsHostTest : public ::testing::Test {
  21110. protected:
  21111. void Start(const char *cert_file) {
  21112. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  21113. SERVER_PRIVATE_KEY_FILE);
  21114. ASSERT_TRUE(server_->is_valid());
  21115. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  21116. std::string msg;
  21117. while (ws.read(msg)) {
  21118. ws.send(msg);
  21119. }
  21120. });
  21121. port_ = server_->bind_to_any_port("localhost");
  21122. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21123. server_->wait_until_ready();
  21124. }
  21125. void TearDown() override {
  21126. if (server_) { server_->stop(); }
  21127. if (server_thread_.joinable()) { server_thread_.join(); }
  21128. }
  21129. std::string url() const {
  21130. return "wss://localhost:" + std::to_string(port_) + "/echo";
  21131. }
  21132. std::unique_ptr<SSLServer> server_;
  21133. std::thread server_thread_;
  21134. int port_ = 0;
  21135. };
  21136. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  21137. // out and the connection is usable
  21138. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  21139. Start(SERVER_CERT2_FILE);
  21140. ws::WebSocketClient client(url());
  21141. client.set_ca_cert_path(SERVER_CERT2_FILE);
  21142. ASSERT_TRUE(client.connect());
  21143. ASSERT_TRUE(client.send("hello"));
  21144. std::string msg;
  21145. EXPECT_EQ(ws::Text, client.read(msg));
  21146. EXPECT_EQ("hello", msg);
  21147. client.close();
  21148. }
  21149. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  21150. // while the identity check must still reject "localhost"
  21151. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  21152. Start(SERVER_CERT_FILE);
  21153. ws::WebSocketClient client(url());
  21154. client.set_ca_cert_path(SERVER_CERT_FILE);
  21155. auto res = client.connect();
  21156. ASSERT_FALSE(res);
  21157. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  21158. EXPECT_EQ(-1, res.status());
  21159. }
  21160. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  21161. // disabled: the chain is still checked, only the identity check is skipped
  21162. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  21163. Start(SERVER_CERT_FILE);
  21164. ws::WebSocketClient client(url());
  21165. client.set_ca_cert_path(SERVER_CERT_FILE);
  21166. client.enable_server_hostname_verification(false);
  21167. ASSERT_TRUE(client.connect());
  21168. ASSERT_TRUE(client.send("hello"));
  21169. std::string msg;
  21170. EXPECT_EQ(ws::Text, client.read(msg));
  21171. EXPECT_EQ("hello", msg);
  21172. client.close();
  21173. }
  21174. // A CA that did not sign the server certificate fails the chain, even though
  21175. // the name would match
  21176. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  21177. Start(SERVER_CERT2_FILE);
  21178. ws::WebSocketClient client(url());
  21179. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  21180. ASSERT_FALSE(client.connect());
  21181. }
  21182. // With verification disabled, neither the chain nor the name is checked
  21183. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  21184. Start(SERVER_CERT_FILE);
  21185. ws::WebSocketClient client(url());
  21186. client.enable_server_certificate_verification(false);
  21187. ASSERT_TRUE(client.connect());
  21188. ASSERT_TRUE(client.send("hello"));
  21189. std::string msg;
  21190. EXPECT_EQ(ws::Text, client.read(msg));
  21191. EXPECT_EQ("hello", msg);
  21192. client.close();
  21193. }
  21194. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  21195. protected:
  21196. void SetUp() override {
  21197. server_ = httplib::detail::make_unique<SSLServer>(
  21198. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  21199. ASSERT_TRUE(server_->is_valid());
  21200. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  21201. std::string msg;
  21202. while (ws.read(msg)) {
  21203. ws.send(msg);
  21204. }
  21205. });
  21206. port_ = server_->bind_to_any_port("localhost");
  21207. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21208. server_->wait_until_ready();
  21209. }
  21210. void TearDown() override {
  21211. server_->stop();
  21212. if (server_thread_.joinable()) { server_thread_.join(); }
  21213. }
  21214. std::string url() const {
  21215. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  21216. }
  21217. void ConnectWithClientCert(const std::string &client_cert_file,
  21218. const std::string &client_private_key_file,
  21219. const char *private_key_password) {
  21220. std::string cert_pem, key_pem;
  21221. read_file(client_cert_file, cert_pem);
  21222. read_file(client_private_key_file, key_pem);
  21223. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  21224. key_pem.c_str(), key_pem.size(),
  21225. private_key_password};
  21226. ws::WebSocketClient client(url(), pem);
  21227. ASSERT_TRUE(client.is_valid());
  21228. client.enable_server_certificate_verification(false);
  21229. ASSERT_TRUE(client.connect());
  21230. ASSERT_TRUE(client.send("hello"));
  21231. std::string msg;
  21232. EXPECT_EQ(ws::Text, client.read(msg));
  21233. EXPECT_EQ("hello", msg);
  21234. client.close();
  21235. }
  21236. std::unique_ptr<SSLServer> server_;
  21237. std::thread server_thread_;
  21238. int port_ = 0;
  21239. };
  21240. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  21241. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  21242. }
  21243. // Control for the tests above: the fixture's server really does require a
  21244. // client certificate, so it is the PEM the constructor installed that decides
  21245. // the outcome.
  21246. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  21247. ws::WebSocketClient client(url());
  21248. ASSERT_TRUE(client.is_valid());
  21249. client.enable_server_certificate_verification(false);
  21250. EXPECT_FALSE(client.connect());
  21251. }
  21252. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  21253. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  21254. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  21255. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  21256. }
  21257. #endif
  21258. #if !defined(_WIN32)
  21259. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  21260. auto secret_dir = std::string("./symlink_test_secret");
  21261. auto served_dir = std::string("./symlink_test_served");
  21262. auto secret_file = secret_dir + "/secret.txt";
  21263. auto symlink_path = served_dir + "/escape";
  21264. // Setup: create directories and files
  21265. mkdir(secret_dir.c_str(), 0755);
  21266. mkdir(served_dir.c_str(), 0755);
  21267. {
  21268. std::ofstream ofs(secret_file);
  21269. ofs << "SECRET_DATA";
  21270. }
  21271. // Create symlink using absolute path so it resolves correctly
  21272. #ifdef PATH_MAX
  21273. char abs_secret[PATH_MAX];
  21274. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  21275. #else
  21276. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  21277. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  21278. ASSERT_NE(nullptr, abs_secret);
  21279. #endif
  21280. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  21281. auto se = detail::scope_exit([&] {
  21282. unlink(symlink_path.c_str());
  21283. unlink(secret_file.c_str());
  21284. rmdir(served_dir.c_str());
  21285. rmdir(secret_dir.c_str());
  21286. });
  21287. Server svr;
  21288. svr.set_mount_point("/", served_dir);
  21289. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  21290. auto se2 = detail::scope_exit([&] {
  21291. svr.stop();
  21292. listen_thread.join();
  21293. });
  21294. svr.wait_until_ready();
  21295. Client cli("localhost", PORT);
  21296. // Symlink pointing outside base dir should be blocked
  21297. auto res = cli.Get("/escape/secret.txt");
  21298. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21299. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  21300. }
  21301. #endif
  21302. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  21303. // "GET /smuggled" request), reads the first response, and only then sends the
  21304. // embedded request as the body. Returns how many times /smuggled ran.
  21305. //
  21306. // The body is sent AFTER receiving the first response (as in the original
  21307. // PoC) so that the stream_line_reader cannot buffer it together with the
  21308. // headers of the first request.
  21309. static int count_smuggled_requests(const std::string &outer_head,
  21310. std::string &first_response) {
  21311. Server svr;
  21312. svr.set_mount_point("/", "./www");
  21313. std::atomic<int> smuggled_count(0);
  21314. svr.Get("/smuggled", [&](const Request &, Response &res) {
  21315. smuggled_count++;
  21316. res.set_content("oops", "text/plain");
  21317. });
  21318. svr.Post("/post", [&](const Request &req, Response &res) {
  21319. res.set_content(req.body, "text/plain");
  21320. });
  21321. auto port = svr.bind_to_any_port("localhost");
  21322. thread t = thread([&] { svr.listen_after_bind(); });
  21323. auto se = detail::scope_exit([&] {
  21324. svr.stop();
  21325. t.join();
  21326. });
  21327. svr.wait_until_ready();
  21328. auto error = Error::Success;
  21329. auto sock = detail::create_client_socket(
  21330. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  21331. /*connection_timeout_sec=*/2, 0,
  21332. /*read_timeout_sec=*/2, 0,
  21333. /*write_timeout_sec=*/2, 0, std::string(), error);
  21334. EXPECT_NE(INVALID_SOCKET, sock);
  21335. if (sock == INVALID_SOCKET) { return -1; }
  21336. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  21337. // The "smuggled" request will be sent as the body of the outer request
  21338. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  21339. "Host: localhost\r\n"
  21340. "Connection: close\r\n"
  21341. "\r\n";
  21342. auto head = outer_head;
  21343. auto len = std::to_string(smuggled.size());
  21344. for (auto pos = head.find("{len}"); pos != std::string::npos;
  21345. pos = head.find("{len}", pos + len.size())) {
  21346. head.replace(pos, 5, len);
  21347. }
  21348. // Step 1: Send only the outer request headers (no body yet)
  21349. auto sent = send(sock, head.data(), head.size(), 0);
  21350. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  21351. // Step 2: Read the first response
  21352. char buf[4096];
  21353. for (;;) {
  21354. auto n = recv(sock, buf, sizeof(buf), 0);
  21355. if (n <= 0) break;
  21356. first_response.append(buf, static_cast<size_t>(n));
  21357. // Stop once we have a complete response (headers + body)
  21358. auto hdr_end = first_response.find("\r\n\r\n");
  21359. if (hdr_end != std::string::npos) {
  21360. // Check for Content-Length to know when the body is complete
  21361. auto cl_pos = first_response.find("Content-Length:");
  21362. if (cl_pos != std::string::npos) {
  21363. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  21364. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  21365. auto cl = std::stoul(
  21366. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  21367. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  21368. } else {
  21369. break; // No Content-Length, assume headers-only response
  21370. }
  21371. }
  21372. }
  21373. // Step 3: Now send the body, which looks like a new HTTP request. On a
  21374. // vulnerable server the keep-alive loop reads this as a second request. The
  21375. // server may already have closed the connection, so the result is ignored.
  21376. send(sock, smuggled.data(), smuggled.size(), 0);
  21377. // Half-close so that a server which drained the body sees EOF and closes,
  21378. // instead of the read below waiting for the read timeout.
  21379. #ifdef _WIN32
  21380. ::shutdown(sock, SD_SEND);
  21381. #else
  21382. ::shutdown(sock, SHUT_WR);
  21383. #endif
  21384. // Step 4: Read until the server closes the connection
  21385. for (;;) {
  21386. auto n = recv(sock, buf, sizeof(buf), 0);
  21387. if (n <= 0) break;
  21388. }
  21389. return smuggled_count.load();
  21390. }
  21391. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  21392. // A GET request with Content-Length to a static file handler must have its
  21393. // body drained before the keep-alive connection is reused. Otherwise the
  21394. // unread body bytes are interpreted as the next HTTP request.
  21395. std::string first_response;
  21396. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  21397. "Host: localhost\r\n"
  21398. "Content-Length: {len}\r\n"
  21399. "\r\n",
  21400. first_response));
  21401. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  21402. }
  21403. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  21404. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  21405. // be answered with 400 and the connection closed. Treating it as "no body"
  21406. // leaves the body to be parsed as the next request.
  21407. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  21408. const char *targets[] = {
  21409. "GET /file", // handler that never reads the body
  21410. "GET /not-found", // no handler matches (404)
  21411. "POST /post", // handler that reads the body
  21412. };
  21413. for (auto target : targets) {
  21414. for (auto value : values) {
  21415. std::string first_response;
  21416. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  21417. " HTTP/1.1\r\n"
  21418. "Host: localhost\r\n"
  21419. "Content-Length: " +
  21420. value + "\r\n\r\n",
  21421. first_response))
  21422. << target << " with Content-Length: " << value;
  21423. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  21424. << target << " with Content-Length: " << value;
  21425. }
  21426. }
  21427. }
  21428. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  21429. // A 400 for an unparseable request line leaves the rest of the message
  21430. // unread, so the connection must be closed rather than reused.
  21431. std::string first_response;
  21432. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  21433. "Host: localhost\r\n"
  21434. "Content-Length: {len}\r\n"
  21435. "\r\n",
  21436. first_response));
  21437. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  21438. }
  21439. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  21440. // Same as above for a header block that fails to parse.
  21441. std::string first_response;
  21442. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  21443. "Host: localhost\r\n"
  21444. "Bad Header\r\n"
  21445. "Content-Length: {len}\r\n"
  21446. "\r\n",
  21447. first_response));
  21448. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  21449. }
  21450. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  21451. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  21452. // server must not read another request on that connection, even when the
  21453. // request had no body to drain.
  21454. std::string first_response;
  21455. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  21456. "Host: localhost\r\n"
  21457. "\r\n",
  21458. first_response));
  21459. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  21460. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  21461. }
  21462. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  21463. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  21464. // must be rejected with 400 Bad Request.
  21465. Server svr;
  21466. svr.Post("/test", [&](const Request &, Response &res) {
  21467. res.set_content("ok", "text/plain");
  21468. });
  21469. thread t = thread([&] { svr.listen(HOST, PORT); });
  21470. auto se = detail::scope_exit([&] {
  21471. svr.stop();
  21472. t.join();
  21473. ASSERT_FALSE(svr.is_running());
  21474. });
  21475. svr.wait_until_ready();
  21476. // Exact "chunked"
  21477. {
  21478. auto req = "POST /test HTTP/1.1\r\n"
  21479. "Host: localhost\r\n"
  21480. "Content-Length: 5\r\n"
  21481. "Transfer-Encoding: chunked\r\n"
  21482. "Connection: close\r\n"
  21483. "\r\n"
  21484. "hello";
  21485. std::string response;
  21486. ASSERT_TRUE(send_request(1, req, &response));
  21487. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  21488. response.substr(0, response.find("\r\n")));
  21489. }
  21490. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  21491. {
  21492. auto req = "POST /test HTTP/1.1\r\n"
  21493. "Host: localhost\r\n"
  21494. "Content-Length: 5\r\n"
  21495. "Transfer-Encoding: gzip, chunked\r\n"
  21496. "Connection: close\r\n"
  21497. "\r\n"
  21498. "hello";
  21499. std::string response;
  21500. ASSERT_TRUE(send_request(1, req, &response));
  21501. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  21502. response.substr(0, response.find("\r\n")));
  21503. }
  21504. }
  21505. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  21506. Server svr;
  21507. svr.Post("/test", [&](const Request &, Response &res) {
  21508. res.set_content("ok", "text/plain");
  21509. });
  21510. thread t = thread([&] { svr.listen(HOST, PORT); });
  21511. auto se = detail::scope_exit([&] {
  21512. svr.stop();
  21513. t.join();
  21514. ASSERT_FALSE(svr.is_running());
  21515. });
  21516. svr.wait_until_ready();
  21517. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  21518. // length cannot be determined, so the server must answer 400 and close
  21519. // rather than treat the request as bodyless and leave the body in the
  21520. // socket for the next request to pick up.
  21521. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  21522. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  21523. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  21524. std::string response;
  21525. ASSERT_TRUE(send_request(1, req, &response));
  21526. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  21527. response.substr(0, response.find("\r\n")))
  21528. << transfer_encoding;
  21529. }
  21530. // RFC 9110 5.3: the codings may also be split across several
  21531. // Transfer-Encoding lines, which combine in the order they were received.
  21532. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  21533. // just like the single-line "chunked, gzip" above.
  21534. {
  21535. auto req = "POST /test HTTP/1.1\r\n"
  21536. "Host: localhost\r\n"
  21537. "Transfer-Encoding: chunked\r\n"
  21538. "Transfer-Encoding: gzip\r\n"
  21539. "\r\n"
  21540. "0\r\n\r\n";
  21541. std::string response;
  21542. ASSERT_TRUE(send_request(1, req, &response));
  21543. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  21544. response.substr(0, response.find("\r\n")));
  21545. }
  21546. // A sequence ending in chunked stays valid.
  21547. auto req = "POST /test HTTP/1.1\r\n"
  21548. "Host: localhost\r\n"
  21549. "Transfer-Encoding: gzip, chunked\r\n"
  21550. "Connection: close\r\n"
  21551. "\r\n"
  21552. "0\r\n\r\n";
  21553. std::string response;
  21554. ASSERT_TRUE(send_request(1, req, &response));
  21555. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  21556. // ...including when it is spread over several lines.
  21557. auto split_req = "POST /test HTTP/1.1\r\n"
  21558. "Host: localhost\r\n"
  21559. "Transfer-Encoding: gzip\r\n"
  21560. "Transfer-Encoding: chunked\r\n"
  21561. "Connection: close\r\n"
  21562. "\r\n"
  21563. "0\r\n\r\n";
  21564. std::string split_response;
  21565. ASSERT_TRUE(send_request(1, split_req, &split_response));
  21566. EXPECT_EQ("HTTP/1.1 200 OK",
  21567. split_response.substr(0, split_response.find("\r\n")));
  21568. }
  21569. // Regression for issue #2450: a DELETE without Content-Length on a
  21570. // keep-alive connection must not let the post-response drain consume the
  21571. // next request's bytes.
  21572. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  21573. Server svr;
  21574. std::atomic<int> delete_count(0);
  21575. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  21576. delete_count++;
  21577. res.status = StatusCode::NoContent_204;
  21578. });
  21579. auto port = svr.bind_to_any_port(HOST);
  21580. thread t = thread([&] { svr.listen_after_bind(); });
  21581. auto se = detail::scope_exit([&] {
  21582. svr.stop();
  21583. t.join();
  21584. });
  21585. svr.wait_until_ready();
  21586. auto error = Error::Success;
  21587. auto sock = detail::create_client_socket(
  21588. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  21589. /*connection_timeout_sec=*/2, 0,
  21590. /*read_timeout_sec=*/2, 0,
  21591. /*write_timeout_sec=*/2, 0, std::string(), error);
  21592. ASSERT_NE(INVALID_SOCKET, sock);
  21593. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  21594. auto send_request_and_read_response = [&](const std::string &req,
  21595. std::string &out) -> bool {
  21596. auto sent = send(sock, req.data(), req.size(), 0);
  21597. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  21598. char buf[4096];
  21599. for (;;) {
  21600. auto n = recv(sock, buf, sizeof(buf), 0);
  21601. if (n <= 0) { return !out.empty(); }
  21602. out.append(buf, static_cast<size_t>(n));
  21603. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  21604. }
  21605. };
  21606. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  21607. "Host: localhost\r\n"
  21608. "\r\n";
  21609. std::string resp1;
  21610. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  21611. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  21612. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  21613. "Host: localhost\r\n"
  21614. "Connection: close\r\n"
  21615. "\r\n";
  21616. std::string resp2;
  21617. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  21618. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  21619. EXPECT_EQ(2, delete_count.load());
  21620. }
  21621. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  21622. Server svr;
  21623. svr.Post("/ingest", [&](const Request &, Response &res,
  21624. const ContentReader &content_reader) {
  21625. auto consumed = content_reader([](const char *, size_t) { return false; });
  21626. EXPECT_FALSE(consumed);
  21627. res.status = StatusCode::Conflict_409;
  21628. res.set_header("Connection", "close");
  21629. });
  21630. auto port = svr.bind_to_any_port(HOST);
  21631. thread t = thread([&] { svr.listen_after_bind(); });
  21632. auto se = detail::scope_exit([&] {
  21633. svr.stop();
  21634. t.join();
  21635. });
  21636. svr.wait_until_ready();
  21637. auto error = Error::Success;
  21638. auto sock = detail::create_client_socket(
  21639. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  21640. /*connection_timeout_sec=*/2, 0,
  21641. /*read_timeout_sec=*/1, 0,
  21642. /*write_timeout_sec=*/2, 0, std::string(), error);
  21643. ASSERT_NE(INVALID_SOCKET, sock);
  21644. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  21645. std::string request = "POST /ingest HTTP/1.1\r\n"
  21646. "Host: localhost\r\n"
  21647. "Transfer-Encoding: chunked\r\n"
  21648. "\r\n"
  21649. "4\r\n"
  21650. "data\r\n";
  21651. auto sent = send(sock, request.data(), request.size(), 0);
  21652. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  21653. std::string response;
  21654. ssize_t received = 0;
  21655. do {
  21656. char buf[4096];
  21657. received = recv(sock, buf, sizeof(buf), 0);
  21658. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  21659. } while (received > 0);
  21660. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  21661. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  21662. EXPECT_EQ(0, received);
  21663. }
  21664. namespace no_proxy_test {
  21665. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  21666. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  21667. // calling listen().
  21668. class ScopedServer {
  21669. public:
  21670. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  21671. ~ScopedServer() {
  21672. svr_.stop();
  21673. if (th_.joinable()) { th_.join(); }
  21674. }
  21675. Server &svr() { return svr_; }
  21676. int port() const { return port_; }
  21677. void listen() {
  21678. th_ = std::thread([this] { svr_.listen_after_bind(); });
  21679. svr_.wait_until_ready();
  21680. }
  21681. private:
  21682. Server svr_;
  21683. std::thread th_;
  21684. int port_ = 0;
  21685. };
  21686. class ProxyAndTargetServers {
  21687. public:
  21688. ProxyAndTargetServers() {
  21689. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  21690. proxy_hits_++;
  21691. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  21692. res.set_content("via-proxy", "text/plain");
  21693. });
  21694. target_.Get(".*", [this](const Request &req, Response &res) {
  21695. target_hits_++;
  21696. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  21697. res.set_content("direct", "text/plain");
  21698. });
  21699. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  21700. target_port_ = target_.bind_to_any_port("127.0.0.1");
  21701. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  21702. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  21703. proxy_mock_.wait_until_ready();
  21704. target_.wait_until_ready();
  21705. }
  21706. ~ProxyAndTargetServers() {
  21707. proxy_mock_.stop();
  21708. target_.stop();
  21709. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  21710. if (target_thread_.joinable()) { target_thread_.join(); }
  21711. }
  21712. Server &proxy_mock() { return proxy_mock_; }
  21713. Server &target() { return target_; }
  21714. int proxy_port() const { return proxy_port_; }
  21715. int target_port() const { return target_port_; }
  21716. int proxy_hits() const { return proxy_hits_.load(); }
  21717. int target_hits() const { return target_hits_.load(); }
  21718. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  21719. void reset_counters() {
  21720. proxy_hits_ = 0;
  21721. target_hits_ = 0;
  21722. last_had_proxy_authz_ = false;
  21723. }
  21724. private:
  21725. Server proxy_mock_;
  21726. Server target_;
  21727. std::thread proxy_thread_;
  21728. std::thread target_thread_;
  21729. int proxy_port_ = 0;
  21730. int target_port_ = 0;
  21731. std::atomic<int> proxy_hits_{0};
  21732. std::atomic<int> target_hits_{0};
  21733. std::atomic<bool> last_had_proxy_authz_{false};
  21734. };
  21735. inline std::unique_ptr<Client> make_client(const std::string &host,
  21736. ProxyAndTargetServers &s) {
  21737. auto cli = detail::make_unique<Client>(host, s.target_port());
  21738. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  21739. cli->set_proxy("127.0.0.1", s.proxy_port());
  21740. return cli;
  21741. }
  21742. } // namespace no_proxy_test
  21743. using no_proxy_test::make_client;
  21744. using no_proxy_test::ProxyAndTargetServers;
  21745. TEST(NoProxyTest, ExactHostnameBypasses) {
  21746. ProxyAndTargetServers s;
  21747. auto cli = make_client("example.com", s);
  21748. cli->set_no_proxy({"example.com"});
  21749. auto res = cli->Get("/");
  21750. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21751. EXPECT_EQ(0, s.proxy_hits());
  21752. EXPECT_EQ(1, s.target_hits());
  21753. }
  21754. TEST(NoProxyTest, SubdomainBypasses) {
  21755. ProxyAndTargetServers s;
  21756. auto cli = make_client("foo.example.com", s);
  21757. cli->set_no_proxy({"example.com"});
  21758. auto res = cli->Get("/");
  21759. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21760. EXPECT_EQ(0, s.proxy_hits());
  21761. EXPECT_EQ(1, s.target_hits());
  21762. }
  21763. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  21764. // Regression guard: "evilexample.com" must not be considered a subdomain
  21765. // of "example.com". Without the dot-boundary rule, a naive endsWith
  21766. // check would let traffic bypass the proxy and leak credentials direct
  21767. // to the attacker host.
  21768. ProxyAndTargetServers s;
  21769. auto cli = make_client("evilexample.com", s);
  21770. cli->set_no_proxy({"example.com"});
  21771. auto res = cli->Get("/");
  21772. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21773. EXPECT_GE(s.proxy_hits(), 1);
  21774. EXPECT_EQ(0, s.target_hits());
  21775. }
  21776. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  21777. ProxyAndTargetServers s;
  21778. auto cli = make_client("example.com.evil.com", s);
  21779. cli->set_no_proxy({"example.com"});
  21780. auto res = cli->Get("/");
  21781. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21782. EXPECT_GE(s.proxy_hits(), 1);
  21783. EXPECT_EQ(0, s.target_hits());
  21784. }
  21785. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  21786. ProxyAndTargetServers s;
  21787. auto cli = make_client("example.com", s);
  21788. cli->set_no_proxy({".example.com"});
  21789. auto res = cli->Get("/");
  21790. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21791. EXPECT_EQ(0, s.proxy_hits());
  21792. EXPECT_EQ(1, s.target_hits());
  21793. }
  21794. TEST(NoProxyTest, CaseInsensitiveHostname) {
  21795. ProxyAndTargetServers s;
  21796. auto cli = make_client("Example.COM", s);
  21797. cli->set_no_proxy({"EXAMPLE.com"});
  21798. auto res = cli->Get("/");
  21799. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21800. EXPECT_EQ(0, s.proxy_hits());
  21801. EXPECT_EQ(1, s.target_hits());
  21802. }
  21803. TEST(NoProxyTest, TrailingDotIsNormalized) {
  21804. ProxyAndTargetServers s;
  21805. auto cli = make_client("example.com.", s);
  21806. cli->set_no_proxy({"example.com"});
  21807. auto res = cli->Get("/");
  21808. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21809. EXPECT_EQ(0, s.proxy_hits());
  21810. EXPECT_EQ(1, s.target_hits());
  21811. }
  21812. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  21813. // Trailing dots must be normalized on BOTH sides — host and entry.
  21814. // An implementation that only strips the host-side trailing dot would
  21815. // fail to match host "example.com" against entry "example.com." because
  21816. // a literal substring search would compare 11 chars against 12.
  21817. ProxyAndTargetServers s;
  21818. auto cli = make_client("example.com", s);
  21819. cli->set_no_proxy({"example.com."});
  21820. auto res = cli->Get("/");
  21821. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21822. EXPECT_EQ(0, s.proxy_hits());
  21823. EXPECT_EQ(1, s.target_hits());
  21824. }
  21825. TEST(NoProxyTest, WildcardBypassesEverything) {
  21826. ProxyAndTargetServers s;
  21827. auto cli = make_client("anything.invalid.test", s);
  21828. cli->set_no_proxy({"*"});
  21829. auto res = cli->Get("/");
  21830. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21831. EXPECT_EQ(0, s.proxy_hits());
  21832. EXPECT_EQ(1, s.target_hits());
  21833. }
  21834. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  21835. ProxyAndTargetServers s;
  21836. Client cli("127.0.0.1", s.target_port());
  21837. cli.set_proxy("127.0.0.1", s.proxy_port());
  21838. cli.set_no_proxy({"127.0.0.1"});
  21839. auto res = cli.Get("/");
  21840. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21841. EXPECT_EQ(0, s.proxy_hits());
  21842. EXPECT_EQ(1, s.target_hits());
  21843. }
  21844. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  21845. ProxyAndTargetServers s;
  21846. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  21847. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  21848. cli.set_proxy("127.0.0.1", s.proxy_port());
  21849. cli.set_no_proxy({"::1"});
  21850. auto res = cli.Get("/");
  21851. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21852. EXPECT_EQ(0, s.proxy_hits());
  21853. EXPECT_EQ(1, s.target_hits());
  21854. }
  21855. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  21856. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  21857. // must still be recognized as IPv6 for CIDR matching. Implementations
  21858. // that detect IPv6 only when the host begins with '[' would parse the
  21859. // host as a hostname and miss the match.
  21860. ProxyAndTargetServers s;
  21861. Client cli("fe80::1", s.target_port());
  21862. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  21863. cli.set_proxy("127.0.0.1", s.proxy_port());
  21864. cli.set_no_proxy({"fe80::/10"});
  21865. auto res = cli.Get("/");
  21866. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21867. EXPECT_EQ(0, s.proxy_hits());
  21868. EXPECT_EQ(1, s.target_hits());
  21869. }
  21870. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  21871. ProxyAndTargetServers s;
  21872. Client cli("::1", s.target_port());
  21873. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  21874. cli.set_proxy("127.0.0.1", s.proxy_port());
  21875. cli.set_no_proxy({"[::1]"});
  21876. auto res = cli.Get("/");
  21877. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21878. EXPECT_EQ(0, s.proxy_hits());
  21879. EXPECT_EQ(1, s.target_hits());
  21880. }
  21881. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  21882. ProxyAndTargetServers s;
  21883. Client cli("fe80::1", s.target_port());
  21884. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  21885. cli.set_proxy("127.0.0.1", s.proxy_port());
  21886. cli.set_no_proxy({"[fe80::]/10"});
  21887. auto res = cli.Get("/");
  21888. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21889. EXPECT_EQ(0, s.proxy_hits());
  21890. EXPECT_EQ(1, s.target_hits());
  21891. }
  21892. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  21893. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  21894. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  21895. // tricks via address-family conversion.
  21896. ProxyAndTargetServers s;
  21897. Client cli("::ffff:127.0.0.1", s.target_port());
  21898. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  21899. cli.set_proxy("127.0.0.1", s.proxy_port());
  21900. cli.set_no_proxy({"127.0.0.1"});
  21901. auto res = cli.Get("/");
  21902. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21903. EXPECT_GE(s.proxy_hits(), 1);
  21904. EXPECT_EQ(0, s.target_hits());
  21905. }
  21906. TEST(NoProxyTest, IPv4CidrMatch) {
  21907. ProxyAndTargetServers s;
  21908. Client cli("127.0.0.1", s.target_port());
  21909. cli.set_proxy("127.0.0.1", s.proxy_port());
  21910. cli.set_no_proxy({"127.0.0.0/8"});
  21911. auto res = cli.Get("/");
  21912. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21913. EXPECT_EQ(0, s.proxy_hits());
  21914. EXPECT_EQ(1, s.target_hits());
  21915. }
  21916. TEST(NoProxyTest, IPv4CidrNonMatch) {
  21917. ProxyAndTargetServers s;
  21918. Client cli("127.0.0.1", s.target_port());
  21919. cli.set_proxy("127.0.0.1", s.proxy_port());
  21920. cli.set_no_proxy({"10.0.0.0/8"});
  21921. auto res = cli.Get("/");
  21922. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21923. EXPECT_GE(s.proxy_hits(), 1);
  21924. EXPECT_EQ(0, s.target_hits());
  21925. }
  21926. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  21927. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  21928. // IPv4 target matches.
  21929. ProxyAndTargetServers s;
  21930. Client cli("127.0.0.1", s.target_port());
  21931. cli.set_proxy("127.0.0.1", s.proxy_port());
  21932. cli.set_no_proxy({"0.0.0.0/0"});
  21933. auto res = cli.Get("/");
  21934. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21935. EXPECT_EQ(0, s.proxy_hits());
  21936. EXPECT_EQ(1, s.target_hits());
  21937. }
  21938. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  21939. ProxyAndTargetServers s;
  21940. Client cli("127.0.0.1", s.target_port());
  21941. cli.set_proxy("127.0.0.1", s.proxy_port());
  21942. cli.set_no_proxy({"127.0.0.1"});
  21943. auto res = cli.Get("/");
  21944. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21945. EXPECT_EQ(0, s.proxy_hits());
  21946. EXPECT_EQ(1, s.target_hits());
  21947. }
  21948. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  21949. ProxyAndTargetServers s;
  21950. Client cli("127.0.0.1", s.target_port());
  21951. cli.set_proxy("127.0.0.1", s.proxy_port());
  21952. cli.set_no_proxy({"127.0.0.0/33"});
  21953. auto res = cli.Get("/");
  21954. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21955. EXPECT_GE(s.proxy_hits(), 1);
  21956. EXPECT_EQ(0, s.target_hits());
  21957. }
  21958. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  21959. // Empty prefix after the slash must be rejected, not silently treated as /32.
  21960. ProxyAndTargetServers s;
  21961. Client cli("127.0.0.1", s.target_port());
  21962. cli.set_proxy("127.0.0.1", s.proxy_port());
  21963. cli.set_no_proxy({"127.0.0.1/"});
  21964. auto res = cli.Get("/");
  21965. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21966. EXPECT_GE(s.proxy_hits(), 1);
  21967. EXPECT_EQ(0, s.target_hits());
  21968. }
  21969. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  21970. ProxyAndTargetServers s;
  21971. auto cli = make_client("internal.corp", s);
  21972. cli->set_proxy_basic_auth("u", "p");
  21973. cli->set_no_proxy({"internal.corp"});
  21974. auto res = cli->Get("/");
  21975. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21976. EXPECT_EQ(1, s.target_hits());
  21977. EXPECT_EQ(0, s.proxy_hits());
  21978. EXPECT_FALSE(s.last_had_proxy_authz())
  21979. << "Proxy-Authorization must not be sent direct to the target";
  21980. }
  21981. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  21982. ProxyAndTargetServers s;
  21983. auto cli = make_client("public.example", s);
  21984. cli->set_proxy_basic_auth("u", "p");
  21985. cli->set_no_proxy({"internal.corp"}); // does not match
  21986. auto res = cli->Get("/");
  21987. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21988. EXPECT_GE(s.proxy_hits(), 1);
  21989. EXPECT_TRUE(s.last_had_proxy_authz());
  21990. }
  21991. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  21992. ProxyAndTargetServers s;
  21993. auto cli = make_client("anything.test", s);
  21994. auto res = cli->Get("/");
  21995. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21996. EXPECT_GE(s.proxy_hits(), 1);
  21997. EXPECT_EQ(0, s.target_hits());
  21998. }
  21999. TEST(NoProxyTest, PortSpecificEntryRejected) {
  22000. ProxyAndTargetServers s;
  22001. auto cli = make_client("example.com", s);
  22002. cli->set_no_proxy({"example.com:8080"});
  22003. auto res = cli->Get("/");
  22004. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22005. EXPECT_GE(s.proxy_hits(), 1);
  22006. EXPECT_EQ(0, s.target_hits());
  22007. }
  22008. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  22009. ProxyAndTargetServers s;
  22010. auto cli = make_client("anything.test", s);
  22011. cli->set_no_proxy({"", " ", "\t"});
  22012. auto res = cli->Get("/");
  22013. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22014. EXPECT_GE(s.proxy_hits(), 1);
  22015. EXPECT_EQ(0, s.target_hits());
  22016. }
  22017. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  22018. // An entry with leading/trailing whitespace must still match — env-style
  22019. // values are commonly pasted with stray spaces and an implementation
  22020. // that feeds the raw token directly to inet_pton would fail to match
  22021. // valid CIDRs because of the spaces.
  22022. ProxyAndTargetServers s;
  22023. Client cli("127.0.0.1", s.target_port());
  22024. cli.set_proxy("127.0.0.1", s.proxy_port());
  22025. cli.set_no_proxy({" 127.0.0.0/8 "});
  22026. auto res = cli.Get("/");
  22027. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22028. EXPECT_EQ(0, s.proxy_hits());
  22029. EXPECT_EQ(1, s.target_hits());
  22030. }
  22031. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  22032. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  22033. // go direct and must NOT carry Proxy-Authorization.
  22034. std::atomic<int> proxy_hits{0};
  22035. std::atomic<int> target_hits{0};
  22036. std::atomic<bool> target_saw_authz{false};
  22037. no_proxy_test::ScopedServer proxy_mock, target;
  22038. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  22039. proxy_hits++;
  22040. res.status = 302;
  22041. res.set_header("Location", "http://127.0.0.1:" +
  22042. std::to_string(target.port()) + "/landed");
  22043. });
  22044. target.svr().Get(".*", [&](const Request &req, Response &res) {
  22045. target_hits++;
  22046. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  22047. res.set_content("direct", "text/plain");
  22048. });
  22049. proxy_mock.listen();
  22050. target.listen();
  22051. Client cli("public.example", target.port());
  22052. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  22053. cli.set_proxy("127.0.0.1", proxy_mock.port());
  22054. cli.set_proxy_basic_auth("u", "p");
  22055. cli.set_no_proxy({"127.0.0.1"});
  22056. cli.set_follow_location(true);
  22057. auto res = cli.Get("/redir");
  22058. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22059. EXPECT_GE(proxy_hits.load(), 1);
  22060. EXPECT_GE(target_hits.load(), 1);
  22061. EXPECT_FALSE(target_saw_authz.load());
  22062. }
  22063. #ifdef CPPHTTPLIB_SSL_ENABLED
  22064. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  22065. // Direct origin replying 407 must not trigger the digest retry; otherwise
  22066. // proxy creds would be sent to the (possibly hostile) origin.
  22067. std::atomic<int> target_hits{0};
  22068. std::atomic<bool> target_saw_proxy_authz{false};
  22069. no_proxy_test::ScopedServer target;
  22070. target.svr().Get(".*", [&](const Request &req, Response &res) {
  22071. target_hits++;
  22072. if (req.has_header("Proxy-Authorization")) {
  22073. target_saw_proxy_authz = true;
  22074. }
  22075. res.status = StatusCode::ProxyAuthenticationRequired_407;
  22076. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  22077. "nonce=\"abc\", algorithm=MD5");
  22078. });
  22079. target.listen();
  22080. // The proxy address is set to the target's port: the bypass MUST kick in;
  22081. // if it doesn't, the test still routes "via proxy" to the same server and
  22082. // the Proxy-Authorization assertion below catches the leak.
  22083. Client cli("evil.example", target.port());
  22084. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  22085. cli.set_proxy("127.0.0.1", target.port());
  22086. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  22087. cli.set_no_proxy({"evil.example"});
  22088. auto res = cli.Get("/x");
  22089. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22090. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  22091. EXPECT_EQ(1, target_hits.load());
  22092. EXPECT_FALSE(target_saw_proxy_authz.load());
  22093. }
  22094. #endif
  22095. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  22096. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  22097. std::atomic<int> proxy_hits{0};
  22098. std::atomic<int> bypass_hits{0};
  22099. std::atomic<bool> proxy_saw_c_url{false};
  22100. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  22101. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  22102. proxy_hits++;
  22103. if (req.path.find("/start") != std::string::npos) {
  22104. res.status = 302;
  22105. res.set_header("Location", "http://127.0.0.1:" +
  22106. std::to_string(bypass_server.port()) +
  22107. "/middle");
  22108. return;
  22109. }
  22110. if (req.path.find("/end") != std::string::npos) {
  22111. proxy_saw_c_url = true;
  22112. res.set_content("c-via-proxy", "text/plain");
  22113. return;
  22114. }
  22115. res.set_content("unexpected", "text/plain");
  22116. });
  22117. // public.example's "advertised" port is arbitrary (the request never lands
  22118. // there — it goes through the proxy), but use a dynamic value to stay
  22119. // friendly with sharded parallel runs.
  22120. int public_port = bypass_server.port();
  22121. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  22122. bypass_hits++;
  22123. res.status = 302;
  22124. res.set_header("Location", "http://public.example:" +
  22125. std::to_string(public_port) + "/end");
  22126. });
  22127. proxy_mock.listen();
  22128. bypass_server.listen();
  22129. Client cli("public.example", public_port);
  22130. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  22131. cli.set_proxy("127.0.0.1", proxy_mock.port());
  22132. cli.set_no_proxy({"127.0.0.1"});
  22133. cli.set_follow_location(true);
  22134. auto res = cli.Get("/start");
  22135. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22136. EXPECT_EQ(StatusCode::OK_200, res->status);
  22137. EXPECT_EQ("c-via-proxy", res->body);
  22138. EXPECT_GE(proxy_hits.load(), 2);
  22139. EXPECT_GE(bypass_hits.load(), 1);
  22140. EXPECT_TRUE(proxy_saw_c_url.load());
  22141. }
  22142. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  22143. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  22144. // request reconnects to the correct endpoint.
  22145. std::atomic<int> proxy_hits{0};
  22146. std::atomic<int> target_hits{0};
  22147. no_proxy_test::ScopedServer proxy_mock, target;
  22148. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  22149. proxy_hits++;
  22150. res.set_content("via-proxy", "text/plain");
  22151. });
  22152. target.svr().Get(".*", [&](const Request &, Response &res) {
  22153. target_hits++;
  22154. res.set_content("direct", "text/plain");
  22155. });
  22156. proxy_mock.listen();
  22157. target.listen();
  22158. Client cli("public.example", target.port());
  22159. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  22160. cli.set_proxy("127.0.0.1", proxy_mock.port());
  22161. cli.set_keep_alive(true);
  22162. auto res1 = cli.Get("/a");
  22163. ASSERT_TRUE(res1);
  22164. EXPECT_EQ("via-proxy", res1->body);
  22165. EXPECT_EQ(1, proxy_hits.load());
  22166. EXPECT_EQ(0, target_hits.load());
  22167. cli.set_no_proxy({"public.example"});
  22168. auto res2 = cli.Get("/b");
  22169. ASSERT_TRUE(res2);
  22170. EXPECT_EQ("direct", res2->body);
  22171. EXPECT_EQ(1, proxy_hits.load());
  22172. EXPECT_EQ(1, target_hits.load());
  22173. }
  22174. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  22175. namespace proxy_tunnel_test {
  22176. // SSLServer counterpart to no_proxy_test::ScopedServer.
  22177. class ScopedSSLServer {
  22178. public:
  22179. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  22180. port_ = svr_.bind_to_any_port("127.0.0.1");
  22181. }
  22182. ~ScopedSSLServer() {
  22183. svr_.stop();
  22184. if (th_.joinable()) { th_.join(); }
  22185. }
  22186. SSLServer &svr() { return svr_; }
  22187. int port() const { return port_; }
  22188. void listen() {
  22189. th_ = std::thread([this] { svr_.listen_after_bind(); });
  22190. svr_.wait_until_ready();
  22191. }
  22192. private:
  22193. SSLServer svr_;
  22194. std::thread th_;
  22195. int port_ = 0;
  22196. };
  22197. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  22198. class ScopedConnectProxy {
  22199. public:
  22200. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  22201. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  22202. if (listen_fd_ < 0) { return; }
  22203. int yes = 1;
  22204. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  22205. sockaddr_in a{};
  22206. a.sin_family = AF_INET;
  22207. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  22208. a.sin_port = 0;
  22209. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  22210. return;
  22211. }
  22212. socklen_t alen = sizeof(a);
  22213. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  22214. 0) {
  22215. return;
  22216. }
  22217. port_ = ntohs(a.sin_port);
  22218. if (::listen(listen_fd_, 1) != 0) { return; }
  22219. th_ = std::thread([this] { run(); });
  22220. }
  22221. ~ScopedConnectProxy() {
  22222. stop_ = true;
  22223. if (listen_fd_ >= 0) {
  22224. ::shutdown(listen_fd_, SHUT_RDWR);
  22225. ::close(listen_fd_);
  22226. }
  22227. if (th_.joinable()) { th_.join(); }
  22228. }
  22229. int port() const { return port_; }
  22230. int connect_hits() const { return connect_hits_.load(); }
  22231. // Head of the last CONNECT request, as the proxy saw it on the wire.
  22232. std::string connect_request() const {
  22233. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  22234. return connect_request_;
  22235. }
  22236. private:
  22237. void run() {
  22238. while (!stop_.load()) {
  22239. fd_set rfds;
  22240. FD_ZERO(&rfds);
  22241. FD_SET(listen_fd_, &rfds);
  22242. timeval tv{0, 100 * 1000};
  22243. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  22244. if (sel <= 0) { continue; }
  22245. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  22246. if (client_fd < 0) { continue; }
  22247. std::string req;
  22248. char buf[2048];
  22249. while (req.find("\r\n\r\n") == std::string::npos) {
  22250. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  22251. if (n <= 0) { break; }
  22252. req.append(buf, static_cast<size_t>(n));
  22253. }
  22254. if (req.compare(0, 7, "CONNECT") != 0) {
  22255. ::close(client_fd);
  22256. continue;
  22257. }
  22258. connect_hits_++;
  22259. {
  22260. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  22261. connect_request_ = req;
  22262. }
  22263. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  22264. ::send(client_fd, ok, std::strlen(ok), 0);
  22265. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  22266. sockaddr_in o{};
  22267. o.sin_family = AF_INET;
  22268. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  22269. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  22270. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  22271. 0) {
  22272. ::close(client_fd);
  22273. ::close(origin_fd);
  22274. continue;
  22275. }
  22276. auto forward = [](int from, int to) {
  22277. char b[8192];
  22278. for (;;) {
  22279. ssize_t n = ::recv(from, b, sizeof(b), 0);
  22280. if (n <= 0) { break; }
  22281. ssize_t off = 0;
  22282. while (off < n) {
  22283. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  22284. if (s <= 0) {
  22285. off = n;
  22286. break;
  22287. }
  22288. off += s;
  22289. }
  22290. }
  22291. ::shutdown(to, SHUT_WR);
  22292. };
  22293. std::thread t1([&] { forward(client_fd, origin_fd); });
  22294. std::thread t2([&] { forward(origin_fd, client_fd); });
  22295. t1.join();
  22296. t2.join();
  22297. ::close(client_fd);
  22298. ::close(origin_fd);
  22299. }
  22300. }
  22301. int forward_port_ = -1;
  22302. int listen_fd_ = -1;
  22303. int port_ = 0;
  22304. std::thread th_;
  22305. std::atomic<bool> stop_{false};
  22306. std::atomic<int> connect_hits_{0};
  22307. mutable std::mutex connect_request_mutex_;
  22308. std::string connect_request_;
  22309. };
  22310. // Sends one request through the CONNECT proxy to the TLS origin with a
  22311. // credential configured for each hop, and checks that each credential reaches
  22312. // only the hop it was configured for: the proxy's on the CONNECT request, the
  22313. // origin's (every header in origin_headers) on the tunnelled request.
  22314. void CredentialsStayWithTheirHop(
  22315. const std::function<void(SSLClient &)> &set_credentials,
  22316. const std::string &scheme,
  22317. const std::vector<std::string> &origin_headers = {"Authorization"}) {
  22318. std::atomic<int> origin_hits{0};
  22319. std::atomic<bool> origin_saw_proxy_authz{false};
  22320. std::atomic<bool> origin_saw_headers{false};
  22321. ScopedSSLServer origin;
  22322. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  22323. origin_hits++;
  22324. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  22325. origin_saw_headers =
  22326. std::all_of(origin_headers.begin(), origin_headers.end(),
  22327. [&](const std::string &h) { return req.has_header(h); });
  22328. res.set_content("ok", "text/plain");
  22329. });
  22330. origin.listen();
  22331. ScopedConnectProxy proxy(origin.port());
  22332. ASSERT_NE(0, proxy.port());
  22333. // Pinned to 127.0.0.1 for the same reason as the test below.
  22334. SSLClient cli("127.0.0.1", origin.port());
  22335. cli.enable_server_certificate_verification(false);
  22336. cli.set_proxy("127.0.0.1", proxy.port());
  22337. set_credentials(cli);
  22338. auto res = cli.Get("/x");
  22339. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22340. EXPECT_EQ(StatusCode::OK_200, res->status);
  22341. EXPECT_EQ(1, origin_hits.load());
  22342. EXPECT_EQ(1, proxy.connect_hits());
  22343. EXPECT_TRUE(origin_saw_headers.load());
  22344. EXPECT_FALSE(origin_saw_proxy_authz.load())
  22345. << "Proxy-Authorization must not be sent inside the tunnel";
  22346. auto connect_req = proxy.connect_request();
  22347. EXPECT_NE(std::string::npos,
  22348. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  22349. for (const auto &h : origin_headers) {
  22350. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  22351. << h << " must not be sent to the proxy on CONNECT";
  22352. }
  22353. }
  22354. } // namespace proxy_tunnel_test
  22355. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  22356. proxy_tunnel_test::CredentialsStayWithTheirHop(
  22357. [](SSLClient &cli) {
  22358. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  22359. cli.set_basic_auth("origin-user", "origin-pass");
  22360. },
  22361. "Basic");
  22362. }
  22363. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  22364. proxy_tunnel_test::CredentialsStayWithTheirHop(
  22365. [](SSLClient &cli) {
  22366. cli.set_proxy_bearer_token_auth("proxy-token");
  22367. cli.set_bearer_token_auth("origin-token");
  22368. },
  22369. "Bearer");
  22370. }
  22371. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  22372. proxy_tunnel_test::CredentialsStayWithTheirHop(
  22373. [](SSLClient &cli) {
  22374. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  22375. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  22376. {"Cookie", "sid=origin-session"},
  22377. {"X-Api-Key", "origin-key"}});
  22378. },
  22379. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  22380. }
  22381. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  22382. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  22383. // retry; otherwise proxy creds would be sent to the origin.
  22384. std::atomic<int> origin_hits{0};
  22385. std::atomic<bool> origin_saw_proxy_authz{false};
  22386. proxy_tunnel_test::ScopedSSLServer origin;
  22387. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  22388. origin_hits++;
  22389. if (req.has_header("Proxy-Authorization")) {
  22390. origin_saw_proxy_authz = true;
  22391. }
  22392. res.status = StatusCode::ProxyAuthenticationRequired_407;
  22393. res.set_header("Proxy-Authenticate",
  22394. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  22395. "algorithm=MD5");
  22396. });
  22397. origin.listen();
  22398. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  22399. ASSERT_NE(0, proxy.port());
  22400. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  22401. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  22402. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  22403. // and answer with its own status, making this test flaky.
  22404. SSLClient cli("127.0.0.1", origin.port());
  22405. cli.enable_server_certificate_verification(false);
  22406. cli.set_proxy("127.0.0.1", proxy.port());
  22407. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  22408. auto res = cli.Get("/x");
  22409. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22410. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  22411. EXPECT_EQ(1, origin_hits.load());
  22412. EXPECT_FALSE(origin_saw_proxy_authz.load());
  22413. EXPECT_EQ(1, proxy.connect_hits());
  22414. }
  22415. #endif