test.cc 816 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324
  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. // Empty quality value
  892. EXPECT_FALSE(
  893. detail::parse_accept_header("text/html;q=,application/json", result));
  894. // Invalid media type format (no slash and not wildcard)
  895. EXPECT_FALSE(
  896. detail::parse_accept_header("invalidtype,application/json", result));
  897. // Valid cases should still work
  898. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  899. EXPECT_EQ(result.size(), 1U);
  900. EXPECT_EQ(result[0], "*/*");
  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("text/*", result));
  905. EXPECT_EQ(result.size(), 1U);
  906. EXPECT_EQ(result[0], "text/*");
  907. }
  908. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  909. // elements, so a leading, trailing or doubled comma is a legal Accept value
  910. // and must not be answered with 400 Bad Request.
  911. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  912. struct {
  913. const char *value;
  914. std::vector<std::string> expected;
  915. } cases[] = {
  916. {",application/json", {"application/json"}},
  917. {"text/html,", {"text/html"}},
  918. {"text/html,,*/*", {"text/html", "*/*"}},
  919. // An empty element may be spelled with whitespace in it
  920. {"text/html, , application/json", {"text/html", "application/json"}},
  921. // Nothing but empty elements is an empty list, which means the same
  922. // thing as no Accept header at all
  923. {",,,", {}},
  924. // Quality values still apply across ignored empty elements
  925. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  926. };
  927. for (const auto &c : cases) {
  928. std::vector<std::string> result;
  929. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  930. << "value: " << c.value;
  931. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  932. }
  933. // An invalid entry is still rejected when empty elements surround it
  934. std::vector<std::string> result;
  935. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  936. }
  937. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  938. Server svr;
  939. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  940. EXPECT_EQ(req.accept_content_types.size(), 3U);
  941. EXPECT_EQ(req.accept_content_types[0], "application/json");
  942. EXPECT_EQ(req.accept_content_types[1], "text/html");
  943. EXPECT_EQ(req.accept_content_types[2], "*/*");
  944. res.set_content("ok", "text/plain");
  945. });
  946. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  947. EXPECT_TRUE(false);
  948. res.set_content("bad request", "text/plain");
  949. });
  950. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  951. auto se = detail::scope_exit([&] {
  952. svr.stop();
  953. listen_thread.join();
  954. ASSERT_FALSE(svr.is_running());
  955. });
  956. svr.wait_until_ready();
  957. Client cli("localhost", PORT);
  958. {
  959. auto res = cli.Get(
  960. "/accept_ok",
  961. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  962. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  963. EXPECT_EQ(StatusCode::OK_200, res->status);
  964. }
  965. {
  966. auto res = cli.Get("/accept_bad_request",
  967. Headers{{"Accept", "text/html;q=abc,application/json"}});
  968. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  969. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  970. }
  971. }
  972. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  973. Server svr;
  974. svr.Get("/", [](const Request & /*req*/, Response &res) {
  975. res.set_content("ok", "text/plain");
  976. });
  977. std::atomic<int> start_count{0};
  978. std::atomic<bool> running_when_called{false};
  979. svr.set_start_handler([&]() {
  980. running_when_called = svr.is_running();
  981. start_count++;
  982. });
  983. auto port = svr.bind_to_any_port(HOST);
  984. std::thread t([&]() { svr.listen_after_bind(); });
  985. auto se = detail::scope_exit([&] {
  986. svr.stop();
  987. t.join();
  988. ASSERT_FALSE(svr.is_running());
  989. });
  990. svr.wait_until_ready();
  991. // A successful request proves the accept loop is running, which the start
  992. // handler precedes; so by now the handler must have run exactly once.
  993. Client cli(HOST, port);
  994. cli.set_connection_timeout(std::chrono::seconds(5));
  995. auto res = cli.Get("/");
  996. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  997. EXPECT_EQ(StatusCode::OK_200, res->status);
  998. EXPECT_EQ(1, start_count.load());
  999. EXPECT_TRUE(running_when_called.load());
  1000. }
  1001. TEST(DivideTest, DivideStringTests) {
  1002. auto divide = [](const std::string &str, char d) {
  1003. std::string lhs;
  1004. std::string rhs;
  1005. detail::divide(str, d,
  1006. [&](const char *lhs_data, std::size_t lhs_size,
  1007. const char *rhs_data, std::size_t rhs_size) {
  1008. lhs.assign(lhs_data, lhs_size);
  1009. rhs.assign(rhs_data, rhs_size);
  1010. });
  1011. return std::make_pair(std::move(lhs), std::move(rhs));
  1012. };
  1013. {
  1014. const auto res = divide("", '=');
  1015. EXPECT_EQ(res.first, "");
  1016. EXPECT_EQ(res.second, "");
  1017. }
  1018. {
  1019. const auto res = divide("=", '=');
  1020. EXPECT_EQ(res.first, "");
  1021. EXPECT_EQ(res.second, "");
  1022. }
  1023. {
  1024. const auto res = divide(" ", '=');
  1025. EXPECT_EQ(res.first, " ");
  1026. EXPECT_EQ(res.second, "");
  1027. }
  1028. {
  1029. const auto res = divide("a", '=');
  1030. EXPECT_EQ(res.first, "a");
  1031. EXPECT_EQ(res.second, "");
  1032. }
  1033. {
  1034. const auto res = divide("a=", '=');
  1035. EXPECT_EQ(res.first, "a");
  1036. EXPECT_EQ(res.second, "");
  1037. }
  1038. {
  1039. const auto res = divide("=b", '=');
  1040. EXPECT_EQ(res.first, "");
  1041. EXPECT_EQ(res.second, "b");
  1042. }
  1043. {
  1044. const auto res = divide("a=b", '=');
  1045. EXPECT_EQ(res.first, "a");
  1046. EXPECT_EQ(res.second, "b");
  1047. }
  1048. {
  1049. const auto res = divide("a=b=", '=');
  1050. EXPECT_EQ(res.first, "a");
  1051. EXPECT_EQ(res.second, "b=");
  1052. }
  1053. {
  1054. const auto res = divide("a=b=c", '=');
  1055. EXPECT_EQ(res.first, "a");
  1056. EXPECT_EQ(res.second, "b=c");
  1057. }
  1058. }
  1059. TEST(SplitTest, ParseQueryString) {
  1060. string s = "key1=val1&key2=val2&key3=val3";
  1061. Params dic;
  1062. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1063. [&](const char *b, const char *e) {
  1064. string key, val;
  1065. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1066. if (key.empty()) {
  1067. key.assign(b2, e2);
  1068. } else {
  1069. val.assign(b2, e2);
  1070. }
  1071. });
  1072. dic.emplace(key, val);
  1073. });
  1074. EXPECT_EQ("val1", dic.find("key1")->second);
  1075. EXPECT_EQ("val2", dic.find("key2")->second);
  1076. EXPECT_EQ("val3", dic.find("key3")->second);
  1077. }
  1078. TEST(SplitTest, ParseInvalidQueryTests) {
  1079. {
  1080. string s = " ";
  1081. Params dict;
  1082. detail::parse_query_text(s, dict);
  1083. EXPECT_TRUE(dict.empty());
  1084. }
  1085. {
  1086. string s = " = =";
  1087. Params dict;
  1088. detail::parse_query_text(s, dict);
  1089. EXPECT_TRUE(dict.empty());
  1090. }
  1091. }
  1092. TEST(ParseQueryTest, ParseQueryString) {
  1093. {
  1094. std::string s = "key1=val1&key2=val2&key3=val3";
  1095. Params dic;
  1096. detail::parse_query_text(s, dic);
  1097. EXPECT_EQ("val1", dic.find("key1")->second);
  1098. EXPECT_EQ("val2", dic.find("key2")->second);
  1099. EXPECT_EQ("val3", dic.find("key3")->second);
  1100. }
  1101. {
  1102. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1103. Params dic;
  1104. detail::parse_query_text(s, dic);
  1105. EXPECT_EQ("", dic.find("key1")->second);
  1106. EXPECT_EQ("val1", dic.find("key2")->second);
  1107. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1108. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1109. }
  1110. }
  1111. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1112. Params dic;
  1113. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1114. dic.emplace("key1", "val1");
  1115. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1116. dic.emplace("key2", "val2");
  1117. dic.emplace("key3", "val3");
  1118. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1119. }
  1120. // Joins every entry of a Headers or Params into "key=value " so a whole
  1121. // traversal can be compared in one assertion. Both are instantiations of the
  1122. // same insertion-ordered container, so one helper serves both.
  1123. template <typename Map> static std::string entries_to_string(const Map &m) {
  1124. std::string s;
  1125. for (const auto &entry : m) {
  1126. s += entry.first + "=" + entry.second + " ";
  1127. }
  1128. return s;
  1129. }
  1130. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1131. // Params used to be a std::multimap, which sorted by name and handed the
  1132. // caller's query back alphabetised. A client signing its query string could
  1133. // not reproduce the order it asked for.
  1134. Params dic;
  1135. dic.emplace("zulu", "1");
  1136. dic.emplace("alpha", "2");
  1137. dic.emplace("mike", "3");
  1138. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1139. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1140. }
  1141. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1142. Params dic;
  1143. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1144. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1145. }
  1146. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1147. Request req;
  1148. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1149. req.params);
  1150. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1151. EXPECT_EQ("first", req.get_param_value("tag"));
  1152. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1153. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1154. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1155. EXPECT_EQ("", req.get_param_value("tag", 3));
  1156. }
  1157. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1158. // Params shares its container with Headers, which matches field names
  1159. // case-insensitively. Parameter names must not pick that up.
  1160. Params dic;
  1161. dic.emplace("Key", "upper");
  1162. dic.emplace("key", "lower");
  1163. EXPECT_EQ(2U, dic.size());
  1164. EXPECT_EQ(1U, dic.count("Key"));
  1165. EXPECT_EQ(1U, dic.count("key"));
  1166. EXPECT_EQ("upper", dic.find("Key")->second);
  1167. EXPECT_EQ("lower", dic.find("key")->second);
  1168. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1169. }
  1170. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1171. Server svr;
  1172. std::string order;
  1173. svr.Get("/order", [&](const Request &req, Response &res) {
  1174. order = entries_to_string(req.params);
  1175. res.set_content("ok", "text/plain");
  1176. });
  1177. auto port = svr.bind_to_any_port(HOST);
  1178. thread t = thread([&] { svr.listen_after_bind(); });
  1179. auto se = detail::scope_exit([&] {
  1180. svr.stop();
  1181. t.join();
  1182. ASSERT_FALSE(svr.is_running());
  1183. });
  1184. svr.wait_until_ready();
  1185. Client cli(HOST, port);
  1186. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1187. ASSERT_TRUE(res);
  1188. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1189. }
  1190. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1191. Server svr;
  1192. std::string field_order, file_order;
  1193. svr.Post("/order", [&](const Request &req, Response &res) {
  1194. for (const auto &field : req.form.fields) {
  1195. field_order += field.first + "=" + field.second.content + " ";
  1196. }
  1197. for (const auto &file : req.form.files) {
  1198. file_order += file.first + "=" + file.second.filename + " ";
  1199. }
  1200. res.set_content("ok", "text/plain");
  1201. });
  1202. auto port = svr.bind_to_any_port(HOST);
  1203. thread t = thread([&] { svr.listen_after_bind(); });
  1204. auto se = detail::scope_exit([&] {
  1205. svr.stop();
  1206. t.join();
  1207. ASSERT_FALSE(svr.is_running());
  1208. });
  1209. svr.wait_until_ready();
  1210. UploadFormDataItems items = {
  1211. {"zulu", "1", "", ""},
  1212. {"alpha", "2", "", ""},
  1213. {"mike", "3", "", ""},
  1214. {"zebra", "z", "z.txt", "text/plain"},
  1215. {"apple", "a", "a.txt", "text/plain"},
  1216. };
  1217. Client cli(HOST, port);
  1218. auto res = cli.Post("/order", items);
  1219. ASSERT_TRUE(res);
  1220. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1221. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1222. }
  1223. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1224. Server svr;
  1225. std::vector<std::string> values;
  1226. std::string first, second, out_of_range, order;
  1227. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1228. values = req.form.get_fields("tag");
  1229. first = req.form.get_field("tag", 0);
  1230. second = req.form.get_field("tag", 1);
  1231. out_of_range = req.form.get_field("tag", 2);
  1232. for (const auto &field : req.form.fields) {
  1233. order += field.first + "=" + field.second.content + " ";
  1234. }
  1235. res.set_content("ok", "text/plain");
  1236. });
  1237. auto port = svr.bind_to_any_port(HOST);
  1238. thread t = thread([&] { svr.listen_after_bind(); });
  1239. auto se = detail::scope_exit([&] {
  1240. svr.stop();
  1241. t.join();
  1242. ASSERT_FALSE(svr.is_running());
  1243. });
  1244. svr.wait_until_ready();
  1245. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1246. // not adjacent in the container.
  1247. UploadFormDataItems items = {
  1248. {"tag", "first", "", ""},
  1249. {"other", "x", "", ""},
  1250. {"tag", "second", "", ""},
  1251. };
  1252. Client cli(HOST, port);
  1253. auto res = cli.Post("/repeated", items);
  1254. ASSERT_TRUE(res);
  1255. ASSERT_EQ(2U, values.size());
  1256. EXPECT_EQ("first", values[0]);
  1257. EXPECT_EQ("second", values[1]);
  1258. EXPECT_EQ("first", first);
  1259. EXPECT_EQ("second", second);
  1260. // std::multimap already kept entries sharing a name in insertion order, so
  1261. // everything above passes without this change too. The whole traversal is
  1262. // what tells the two apart: sorting by name would hoist "other" to the front
  1263. // and the two "tag" parts would end up adjacent.
  1264. EXPECT_EQ("tag=first other=x tag=second ", order);
  1265. // Advancing past the last entry of a name used to run off the container;
  1266. // the container's saturating increment makes it return the default instead.
  1267. EXPECT_EQ("", out_of_range);
  1268. }
  1269. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1270. // Server::read_content() keeps a FormFields::iterator alive across the
  1271. // content callbacks that fill the part it points at. The container is
  1272. // vector-backed, so a later emplace can reallocate and invalidate an older
  1273. // iterator; 64 parts grow the vector through seven reallocations, which
  1274. // checks that every part's content still lands in its own entry.
  1275. const size_t part_count = 64;
  1276. // One formula for both the parts sent and the values expected back, so the
  1277. // two cannot drift apart.
  1278. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1279. auto content_of = [](size_t i) {
  1280. return std::string(64, static_cast<char>('a' + (i % 26)));
  1281. };
  1282. Server svr;
  1283. std::vector<std::pair<std::string, std::string>> received;
  1284. svr.Post("/many", [&](const Request &req, Response &res) {
  1285. for (const auto &field : req.form.fields) {
  1286. received.emplace_back(field.first, field.second.content);
  1287. }
  1288. res.set_content("ok", "text/plain");
  1289. });
  1290. auto port = svr.bind_to_any_port(HOST);
  1291. thread t = thread([&] { svr.listen_after_bind(); });
  1292. auto se = detail::scope_exit([&] {
  1293. svr.stop();
  1294. t.join();
  1295. ASSERT_FALSE(svr.is_running());
  1296. });
  1297. svr.wait_until_ready();
  1298. UploadFormDataItems items;
  1299. for (size_t i = 0; i < part_count; i++) {
  1300. items.push_back({name_of(i), content_of(i), "", ""});
  1301. }
  1302. Client cli(HOST, port);
  1303. auto res = cli.Post("/many", items);
  1304. ASSERT_TRUE(res);
  1305. ASSERT_EQ(part_count, received.size());
  1306. for (size_t i = 0; i < part_count; i++) {
  1307. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1308. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1309. }
  1310. }
  1311. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1312. string content_type = "multipart/form-data; boundary=something";
  1313. string boundary;
  1314. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1315. EXPECT_TRUE(ret);
  1316. EXPECT_EQ(boundary, "something");
  1317. }
  1318. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1319. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1320. string boundary;
  1321. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1322. EXPECT_TRUE(ret);
  1323. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1324. }
  1325. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1326. string content_type =
  1327. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1328. string boundary;
  1329. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1330. EXPECT_TRUE(ret);
  1331. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1332. }
  1333. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1334. string content_type =
  1335. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1336. string boundary;
  1337. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1338. EXPECT_TRUE(ret);
  1339. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1340. }
  1341. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1342. const string boundary(70, 'a');
  1343. string content_type = "multipart/form-data; boundary=" + boundary;
  1344. string parsed;
  1345. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1346. EXPECT_TRUE(ret);
  1347. EXPECT_EQ(parsed, boundary);
  1348. }
  1349. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1350. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1351. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1352. string parsed;
  1353. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1354. EXPECT_FALSE(ret);
  1355. }
  1356. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1357. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1358. // is 72 characters on the wire and still valid.
  1359. const string boundary(70, 'a');
  1360. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1361. string parsed;
  1362. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1363. EXPECT_EQ(parsed, boundary);
  1364. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1365. parsed.clear();
  1366. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1367. }
  1368. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1369. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1370. // The parameter parser must not treat that '=' as the key/value separator.
  1371. string content_type =
  1372. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1373. "charset=UTF-8";
  1374. string parsed;
  1375. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1376. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1377. }
  1378. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1379. // A ';' inside the quoted-string is part of the value, not a parameter
  1380. // separator, so it must not truncate the boundary.
  1381. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1382. string parsed;
  1383. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1384. EXPECT_EQ(parsed, "a;b");
  1385. }
  1386. TEST(ParseDispositionParamsTest, QuotedValues) {
  1387. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1388. // ';' and '=' are ordinary characters inside one.
  1389. struct {
  1390. const char *value;
  1391. std::vector<std::pair<const char *, const char *>> expected;
  1392. } cases[] = {
  1393. {"name=\"file1\"; filename=\"a.txt\"",
  1394. {{"name", "file1"}, {"filename", "a.txt"}}},
  1395. // Whitespace around '=' and ';' is still trimmed
  1396. {"name=\"file2\" ;filename = \"a.html\"",
  1397. {{"name", "file2"}, {"filename", "a.html"}}},
  1398. // '=' inside the value used to leave only the text after the last one
  1399. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1400. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1401. {"name=\"x=y\"", {{"name", "x=y"}}},
  1402. // ';' inside the value used to truncate the pair and leave a bogus one
  1403. {"name=\"file3\"; filename=\"a;b.txt\"",
  1404. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1405. // An unquoted value keeps working, and so does filename*
  1406. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1407. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1408. // A parameter with no key is dropped rather than turned into one whose
  1409. // key is the value
  1410. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1411. };
  1412. for (const auto &c : cases) {
  1413. Params params;
  1414. detail::parse_disposition_params(c.value, params);
  1415. for (const auto &kv : c.expected) {
  1416. auto it = params.find(kv.first);
  1417. ASSERT_NE(it, params.end())
  1418. << "value: " << c.value << ", key: " << kv.first;
  1419. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1420. }
  1421. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1422. }
  1423. }
  1424. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1425. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1426. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1427. Server svr;
  1428. std::string field_value, file_name, file_filename;
  1429. bool has_field = false, has_file = false;
  1430. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1431. has_field = req.form.has_field("x=y");
  1432. field_value = req.form.get_field("x=y");
  1433. has_file = req.form.has_file("file1");
  1434. const auto &file = req.form.get_file("file1");
  1435. file_name = file.name;
  1436. file_filename = file.filename;
  1437. res.set_content("ok", "text/plain");
  1438. });
  1439. auto port = svr.bind_to_any_port(HOST);
  1440. thread t = thread([&] { svr.listen_after_bind(); });
  1441. auto se = detail::scope_exit([&] {
  1442. svr.stop();
  1443. t.join();
  1444. ASSERT_FALSE(svr.is_running());
  1445. });
  1446. svr.wait_until_ready();
  1447. UploadFormDataItems items = {
  1448. {"x=y", "field-value", "", ""},
  1449. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1450. };
  1451. Client cli(HOST, port);
  1452. auto res = cli.Post("/quoted", items);
  1453. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1454. ASSERT_EQ(StatusCode::OK_200, res->status);
  1455. EXPECT_TRUE(has_field);
  1456. EXPECT_EQ("field-value", field_value);
  1457. EXPECT_TRUE(has_file);
  1458. EXPECT_EQ("file1", file_name);
  1459. EXPECT_EQ("a;b=report.pdf", file_filename);
  1460. }
  1461. TEST(GetHeaderValueTest, DefaultValue) {
  1462. Headers headers = {{"Dummy", "Dummy"}};
  1463. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1464. EXPECT_STREQ("text/plain", val);
  1465. }
  1466. TEST(GetHeaderValueTest, DefaultValueInt) {
  1467. Headers headers = {{"Dummy", "Dummy"}};
  1468. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1469. EXPECT_EQ(100ull, val);
  1470. }
  1471. TEST(GetHeaderValueTest, RegularValue) {
  1472. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1473. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1474. EXPECT_STREQ("text/html", val);
  1475. }
  1476. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1477. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1478. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1479. EXPECT_STREQ("text/html", val);
  1480. }
  1481. TEST(GetHeaderValueTest, SetContent) {
  1482. Response res;
  1483. res.set_content("html", "text/html");
  1484. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1485. res.set_content("text", "text/plain");
  1486. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1487. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1488. }
  1489. TEST(GetHeaderValueTest, RegularValueInt) {
  1490. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1491. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1492. EXPECT_EQ(100ull, val);
  1493. }
  1494. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1495. Headers headers = {{"Content-Length", "x"}};
  1496. auto is_invalid_value = false;
  1497. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1498. is_invalid_value);
  1499. EXPECT_EQ(0ull, val);
  1500. EXPECT_TRUE(is_invalid_value);
  1501. }
  1502. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1503. // An all-digit value that overflows size_t must be reported as invalid, not
  1504. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1505. // a large length to a small one on 32-bit builds, leaving the framing length
  1506. // wrong while is_invalid_value stayed false.
  1507. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1508. auto is_invalid_value = false;
  1509. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1510. is_invalid_value);
  1511. EXPECT_TRUE(is_invalid_value);
  1512. // A well-formed length is unaffected.
  1513. Headers ok = {{"Content-Length", "1234"}};
  1514. is_invalid_value = false;
  1515. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1516. is_invalid_value);
  1517. EXPECT_EQ(1234ull, val);
  1518. EXPECT_FALSE(is_invalid_value);
  1519. }
  1520. TEST(GetHeaderValueTest, Range) {
  1521. {
  1522. Headers headers = {make_range_header({{1, -1}})};
  1523. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1524. EXPECT_STREQ("bytes=1-", val);
  1525. }
  1526. {
  1527. Headers headers = {make_range_header({{-1, 1}})};
  1528. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1529. EXPECT_STREQ("bytes=-1", val);
  1530. }
  1531. {
  1532. Headers headers = {make_range_header({{1, 10}})};
  1533. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1534. EXPECT_STREQ("bytes=1-10", val);
  1535. }
  1536. {
  1537. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1538. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1539. EXPECT_STREQ("bytes=1-10, 100-", val);
  1540. }
  1541. {
  1542. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1543. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1544. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1545. }
  1546. {
  1547. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1548. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1549. EXPECT_STREQ("bytes=0-0, -1", val);
  1550. }
  1551. }
  1552. TEST(BearerTokenAuthTest, SchemeValidation) {
  1553. // A value shorter than "Bearer " must not throw from the fixed-length
  1554. // substr, and a non-Bearer scheme must not be reported as a token.
  1555. struct {
  1556. const char *value;
  1557. const char *expected;
  1558. } cases[] = {
  1559. {"x", ""},
  1560. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1561. {"Bearer abc123", "abc123"},
  1562. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1563. };
  1564. for (const auto &c : cases) {
  1565. Request req;
  1566. req.set_header("Authorization", c.value);
  1567. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1568. }
  1569. }
  1570. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1571. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1572. // to depend on the standard library (libstdc++ handed back duplicates in
  1573. // reverse insertion order, libc++ in insertion order).
  1574. Request req;
  1575. req.set_header("Accept-Encoding", "gzip");
  1576. req.set_header("Accept-Encoding", "deflate");
  1577. req.set_header("Accept-Encoding", "br");
  1578. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1579. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1580. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1581. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1582. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1583. }
  1584. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1585. Request req;
  1586. req.set_header("X-Test", "only");
  1587. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1588. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1589. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1590. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1591. }
  1592. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1593. Headers headers;
  1594. headers.emplace("Host", "example.com");
  1595. headers.emplace("Accept-Encoding", "gzip");
  1596. headers.emplace("User-Agent", "test");
  1597. headers.emplace("Accept-Encoding", "deflate");
  1598. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1599. "Accept-Encoding=deflate ",
  1600. entries_to_string(headers));
  1601. }
  1602. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1603. Headers headers = {{"Content-Type", "text/html"},
  1604. {"CONTENT-TYPE", "text/xml"}};
  1605. EXPECT_EQ(2U, headers.count("content-type"));
  1606. auto it = headers.find("content-type");
  1607. ASSERT_TRUE(it != headers.end());
  1608. EXPECT_EQ("text/html", it->second);
  1609. }
  1610. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1611. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1612. // drop only those fields and leave everything positioned between them.
  1613. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1614. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1615. auto rng = headers.equal_range("a");
  1616. headers.erase(rng.first, rng.second);
  1617. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1618. }
  1619. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1620. Headers headers = {
  1621. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1622. EXPECT_EQ(3U, headers.erase("A"));
  1623. EXPECT_EQ(0U, headers.count("A"));
  1624. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1625. }
  1626. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1627. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1628. headers.emplace_front("Host", "example.com");
  1629. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1630. entries_to_string(headers));
  1631. }
  1632. TEST(ParseHeaderValueTest, Range) {
  1633. {
  1634. Ranges ranges;
  1635. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1636. EXPECT_TRUE(ret);
  1637. EXPECT_EQ(1u, ranges.size());
  1638. EXPECT_EQ(1u, ranges[0].first);
  1639. EXPECT_EQ(-1, ranges[0].second);
  1640. }
  1641. {
  1642. Ranges ranges;
  1643. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1644. EXPECT_TRUE(ret);
  1645. EXPECT_EQ(1u, ranges.size());
  1646. EXPECT_EQ(-1, ranges[0].first);
  1647. EXPECT_EQ(1u, ranges[0].second);
  1648. }
  1649. {
  1650. Ranges ranges;
  1651. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1652. EXPECT_TRUE(ret);
  1653. EXPECT_EQ(1u, ranges.size());
  1654. EXPECT_EQ(1u, ranges[0].first);
  1655. EXPECT_EQ(10u, ranges[0].second);
  1656. }
  1657. {
  1658. Ranges ranges;
  1659. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1660. EXPECT_FALSE(ret);
  1661. }
  1662. {
  1663. Ranges ranges;
  1664. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1665. EXPECT_TRUE(ret);
  1666. EXPECT_EQ(2u, ranges.size());
  1667. EXPECT_EQ(1u, ranges[0].first);
  1668. EXPECT_EQ(10u, ranges[0].second);
  1669. EXPECT_EQ(100u, ranges[1].first);
  1670. EXPECT_EQ(-1, ranges[1].second);
  1671. }
  1672. {
  1673. Ranges ranges;
  1674. auto ret =
  1675. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1676. EXPECT_TRUE(ret);
  1677. EXPECT_EQ(3u, ranges.size());
  1678. EXPECT_EQ(1u, ranges[0].first);
  1679. EXPECT_EQ(10u, ranges[0].second);
  1680. EXPECT_EQ(100u, ranges[1].first);
  1681. EXPECT_EQ(200u, ranges[1].second);
  1682. EXPECT_EQ(300u, ranges[2].first);
  1683. EXPECT_EQ(400u, ranges[2].second);
  1684. }
  1685. {
  1686. Ranges ranges;
  1687. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1688. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1689. EXPECT_FALSE(detail::parse_range_header("bytes=0", 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=,", 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=a-b", ranges));
  1696. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1697. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1698. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1699. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1700. EXPECT_TRUE(ranges.empty());
  1701. }
  1702. }
  1703. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  1704. Request req;
  1705. req.set_header("Accept-Encoding", "gzip");
  1706. Response res;
  1707. res.set_header("Content-Type", "text/plain");
  1708. auto ret = detail::encoding_type(req, res);
  1709. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1710. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1711. #else
  1712. EXPECT_TRUE(ret == detail::EncodingType::None);
  1713. #endif
  1714. }
  1715. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1716. Request req;
  1717. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  1718. Response res;
  1719. res.set_header("Content-Type", "text/plain");
  1720. auto ret = detail::encoding_type(req, res);
  1721. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1722. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1723. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1724. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1725. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1726. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1727. #else
  1728. EXPECT_TRUE(ret == detail::EncodingType::None);
  1729. #endif
  1730. }
  1731. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  1732. Request req;
  1733. req.set_header("Accept-Encoding",
  1734. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  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(ParseAcceptEncoding4, AcceptEncodingQZero) {
  1749. // All supported encodings rejected with q=0 should return None
  1750. Request req;
  1751. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  1752. Response res;
  1753. res.set_header("Content-Type", "text/plain");
  1754. auto ret = detail::encoding_type(req, res);
  1755. EXPECT_TRUE(ret == detail::EncodingType::None);
  1756. }
  1757. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1758. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1759. Request req;
  1760. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1761. Response res;
  1762. res.set_header("Content-Type", "text/plain");
  1763. auto ret = detail::encoding_type(req, res);
  1764. EXPECT_TRUE(ret == detail::EncodingType::None);
  1765. }
  1766. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1767. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1768. Request req;
  1769. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1770. Response res;
  1771. res.set_header("Content-Type", "text/plain");
  1772. auto ret = detail::encoding_type(req, res);
  1773. EXPECT_TRUE(ret == detail::EncodingType::None);
  1774. }
  1775. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1776. // RFC 7231: Accept-Encoding values are case-insensitive
  1777. Request req;
  1778. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1779. Response res;
  1780. res.set_header("Content-Type", "text/plain");
  1781. auto ret = detail::encoding_type(req, res);
  1782. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1783. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1784. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1785. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1786. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1787. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1788. #else
  1789. EXPECT_TRUE(ret == detail::EncodingType::None);
  1790. #endif
  1791. }
  1792. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1793. // q value should determine priority, not hardcoded order
  1794. Request req;
  1795. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  1796. Response res;
  1797. res.set_header("Content-Type", "text/plain");
  1798. auto ret = detail::encoding_type(req, res);
  1799. // gzip has highest q=1.0, so it should be selected even though
  1800. // br and zstd are also supported
  1801. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1802. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1803. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1804. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1805. #elif CPPHTTPLIB_BROTLI_SUPPORT
  1806. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1807. #else
  1808. EXPECT_TRUE(ret == detail::EncodingType::None);
  1809. #endif
  1810. }
  1811. TEST(BufferStreamTest, read) {
  1812. detail::BufferStream strm1;
  1813. Stream &strm = strm1;
  1814. EXPECT_EQ(5, strm.write("hello"));
  1815. char buf[512];
  1816. EXPECT_EQ(2, strm.read(buf, 2));
  1817. EXPECT_EQ('h', buf[0]);
  1818. EXPECT_EQ('e', buf[1]);
  1819. EXPECT_EQ(2, strm.read(buf, 2));
  1820. EXPECT_EQ('l', buf[0]);
  1821. EXPECT_EQ('l', buf[1]);
  1822. EXPECT_EQ(1, strm.read(buf, 1));
  1823. EXPECT_EQ('o', buf[0]);
  1824. EXPECT_EQ(0, strm.read(buf, 1));
  1825. }
  1826. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1827. auto host = "www.httpwatch.com";
  1828. auto ip = hosted_at(host);
  1829. EXPECT_EQ("23.96.13.243", ip);
  1830. std::vector<std::string> addrs;
  1831. hosted_at(host, addrs);
  1832. EXPECT_EQ(1u, addrs.size());
  1833. }
  1834. #if 0 // It depends on each test environment...
  1835. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1836. auto host = "www.youtube.com";
  1837. std::vector<std::string> addrs;
  1838. hosted_at(host, addrs);
  1839. EXPECT_EQ(20u, addrs.size());
  1840. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1841. EXPECT_TRUE(it != addrs.end());
  1842. }
  1843. #endif
  1844. class ChunkedEncodingTest : public ::testing::Test {
  1845. protected:
  1846. ChunkedEncodingTest()
  1847. : cli_(HOST, PORT)
  1848. #ifdef CPPHTTPLIB_SSL_ENABLED
  1849. ,
  1850. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1851. #endif
  1852. {
  1853. cli_.set_connection_timeout(2);
  1854. #ifdef CPPHTTPLIB_SSL_ENABLED
  1855. cli_.enable_server_certificate_verification(false);
  1856. #endif
  1857. }
  1858. virtual void SetUp() {
  1859. read_file("./image.jpg", image_data_);
  1860. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1861. res.set_content("Hello World!", "text/plain");
  1862. });
  1863. svr_.Get(
  1864. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1865. res.set_chunked_content_provider(
  1866. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1867. size_t remaining = image_data_.size() - offset;
  1868. if (remaining == 0) {
  1869. sink.done();
  1870. } else {
  1871. constexpr size_t CHUNK_SIZE = 1024;
  1872. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1873. sink.write(&image_data_[offset], send_size);
  1874. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1875. }
  1876. return true;
  1877. });
  1878. });
  1879. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1880. svr_.wait_until_ready();
  1881. }
  1882. virtual void TearDown() {
  1883. svr_.stop();
  1884. if (!request_threads_.empty()) {
  1885. std::this_thread::sleep_for(std::chrono::seconds(1));
  1886. for (auto &t : request_threads_) {
  1887. t.join();
  1888. }
  1889. }
  1890. t_.join();
  1891. }
  1892. #ifdef CPPHTTPLIB_SSL_ENABLED
  1893. SSLClient cli_;
  1894. SSLServer svr_;
  1895. #else
  1896. Client cli_;
  1897. Server svr_;
  1898. #endif
  1899. thread t_;
  1900. std::vector<thread> request_threads_;
  1901. std::string image_data_;
  1902. };
  1903. TEST_F(ChunkedEncodingTest, NormalGet) {
  1904. auto res = cli_.Get("/chunked");
  1905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1906. std::string out;
  1907. read_file("./image.jpg", out);
  1908. EXPECT_EQ(StatusCode::OK_200, res->status);
  1909. EXPECT_EQ(out, res->body);
  1910. }
  1911. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1912. std::string body;
  1913. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1914. body.append(data, data_length);
  1915. return true;
  1916. });
  1917. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1918. std::string out;
  1919. read_file("./image.jpg", out);
  1920. EXPECT_EQ(StatusCode::OK_200, res->status);
  1921. EXPECT_EQ(out, body);
  1922. }
  1923. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1924. std::string body;
  1925. auto res = cli_.Get(
  1926. "/chunked",
  1927. [&](const Response &response) {
  1928. EXPECT_EQ(StatusCode::OK_200, response.status);
  1929. return true;
  1930. },
  1931. [&](const char *data, size_t data_length) {
  1932. body.append(data, data_length);
  1933. return true;
  1934. });
  1935. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1936. std::string out;
  1937. read_file("./image.jpg", out);
  1938. EXPECT_EQ(StatusCode::OK_200, res->status);
  1939. EXPECT_EQ(out, body);
  1940. }
  1941. TEST(RangeTest, FromHTTPBin_Online) {
  1942. auto host = "httpbingo.org";
  1943. auto path = std::string{"/range/32"};
  1944. #ifdef CPPHTTPLIB_SSL_ENABLED
  1945. auto port = 443;
  1946. SSLClient cli(host, port);
  1947. #else
  1948. auto port = 80;
  1949. Client cli(host, port);
  1950. #endif
  1951. cli.set_connection_timeout(5);
  1952. {
  1953. auto res = cli.Get(path);
  1954. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1955. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1956. EXPECT_EQ(StatusCode::OK_200, res->status);
  1957. }
  1958. {
  1959. Headers headers = {make_range_header({{1, -1}})};
  1960. auto res = cli.Get(path, headers);
  1961. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1962. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1963. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1964. }
  1965. {
  1966. Headers headers = {make_range_header({{1, 10}})};
  1967. auto res = cli.Get(path, headers);
  1968. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1969. EXPECT_EQ("bcdefghijk", res->body);
  1970. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1971. }
  1972. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  1973. // entire resource, while the original httpbin returned 200. Both are
  1974. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  1975. {
  1976. Headers headers = {make_range_header({{0, 31}})};
  1977. auto res = cli.Get(path, headers);
  1978. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1979. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1980. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1981. res->status == StatusCode::PartialContent_206);
  1982. }
  1983. {
  1984. Headers headers = {make_range_header({{0, -1}})};
  1985. auto res = cli.Get(path, headers);
  1986. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1987. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1988. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1989. res->status == StatusCode::PartialContent_206);
  1990. }
  1991. // go-httpbin returns 206 with clamped range for over-range requests,
  1992. // while the original httpbin returned 416. Both behaviors are observed
  1993. // in real servers, so we only verify the request succeeds.
  1994. {
  1995. Headers headers = {make_range_header({{0, 32}})};
  1996. auto res = cli.Get(path, headers);
  1997. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1998. }
  1999. }
  2000. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2001. auto host = "unresolvableaddress.local";
  2002. auto path = std::string{"/"};
  2003. #ifdef CPPHTTPLIB_SSL_ENABLED
  2004. auto port = 443;
  2005. SSLClient cli(host, port);
  2006. #else
  2007. auto port = 80;
  2008. Client cli(host, port);
  2009. #endif
  2010. cli.set_connection_timeout(1);
  2011. {
  2012. auto res = cli.Get(path);
  2013. ASSERT_FALSE(res);
  2014. }
  2015. std::this_thread::sleep_for(std::chrono::seconds(8));
  2016. }
  2017. #if defined(__linux__) && defined(__GLIBC__) && \
  2018. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2019. // Forward declaration: in split builds split.py strips `inline` and moves the
  2020. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2021. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2022. // against the symbol in both header-only and split builds.
  2023. namespace httplib {
  2024. namespace detail {
  2025. int getaddrinfo_with_timeout(const char *node, const char *service,
  2026. const struct addrinfo *hints,
  2027. struct addrinfo **res, time_t timeout_sec);
  2028. } // namespace detail
  2029. } // namespace httplib
  2030. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2031. //
  2032. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2033. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2034. // gai_suspend() call hits the connection timeout the function calls
  2035. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2036. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2037. // still alive and still references the now-destroyed stack frame.
  2038. //
  2039. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2040. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2041. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2042. // and runs them in a container.
  2043. namespace {
  2044. bool should_run_issue_2431_tests() {
  2045. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2046. return v && *v && std::string(v) != "0";
  2047. }
  2048. std::string unique_unresolvable_host(int n) {
  2049. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2050. // glibc still asks the configured nameserver — which is exactly the path
  2051. // we want to exercise. A unique label per call avoids the resolver cache.
  2052. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2053. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2054. std::to_string(n) + ".invalid";
  2055. }
  2056. } // namespace
  2057. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2058. if (!should_run_issue_2431_tests()) {
  2059. GTEST_SKIP()
  2060. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2061. }
  2062. for (int i = 0; i < 8; ++i) {
  2063. struct addrinfo hints;
  2064. memset(&hints, 0, sizeof(hints));
  2065. hints.ai_family = AF_UNSPEC;
  2066. hints.ai_socktype = SOCK_STREAM;
  2067. auto host = unique_unresolvable_host(i);
  2068. struct addrinfo *result = nullptr;
  2069. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2070. &result, /*timeout_sec=*/1);
  2071. if (rc == 0 && result) { freeaddrinfo(result); }
  2072. }
  2073. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2074. // stack region they still believe holds their gaicb.
  2075. std::this_thread::sleep_for(std::chrono::seconds(3));
  2076. }
  2077. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2078. if (!should_run_issue_2431_tests()) {
  2079. GTEST_SKIP()
  2080. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2081. }
  2082. std::atomic<bool> stop{false};
  2083. std::vector<std::thread> threads;
  2084. for (int t = 0; t < 8; ++t) {
  2085. threads.emplace_back([t, &stop] {
  2086. int i = 0;
  2087. while (!stop.load(std::memory_order_relaxed)) {
  2088. struct addrinfo hints;
  2089. memset(&hints, 0, sizeof(hints));
  2090. hints.ai_family = AF_UNSPEC;
  2091. hints.ai_socktype = SOCK_STREAM;
  2092. auto host = unique_unresolvable_host(t * 100000 + i++);
  2093. struct addrinfo *result = nullptr;
  2094. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2095. &result, /*timeout_sec=*/1);
  2096. if (rc == 0 && result) { freeaddrinfo(result); }
  2097. }
  2098. });
  2099. }
  2100. std::this_thread::sleep_for(std::chrono::seconds(8));
  2101. stop.store(true, std::memory_order_relaxed);
  2102. for (auto &th : threads) {
  2103. th.join();
  2104. }
  2105. std::this_thread::sleep_for(std::chrono::seconds(3));
  2106. }
  2107. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2108. if (!should_run_issue_2431_tests()) {
  2109. GTEST_SKIP()
  2110. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2111. }
  2112. std::atomic<bool> stop{false};
  2113. std::vector<std::thread> threads;
  2114. for (int t = 0; t < 8; ++t) {
  2115. threads.emplace_back([t, &stop] {
  2116. int i = 0;
  2117. while (!stop.load(std::memory_order_relaxed)) {
  2118. auto host = unique_unresolvable_host(t * 100000 + i++);
  2119. Client cli(host, 80);
  2120. cli.set_connection_timeout(1, 0);
  2121. cli.set_read_timeout(1, 0);
  2122. cli.set_write_timeout(1, 0);
  2123. (void)cli.Get("/");
  2124. }
  2125. });
  2126. }
  2127. std::this_thread::sleep_for(std::chrono::seconds(8));
  2128. stop.store(true, std::memory_order_relaxed);
  2129. for (auto &th : threads) {
  2130. th.join();
  2131. }
  2132. std::this_thread::sleep_for(std::chrono::seconds(3));
  2133. }
  2134. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2135. TEST(ConnectionErrorTest, InvalidHost) {
  2136. auto host = "-abcde.com";
  2137. #ifdef CPPHTTPLIB_SSL_ENABLED
  2138. auto port = 443;
  2139. SSLClient cli(host, port);
  2140. #else
  2141. auto port = 80;
  2142. Client cli(host, port);
  2143. #endif
  2144. cli.set_connection_timeout(std::chrono::seconds(2));
  2145. auto res = cli.Get("/");
  2146. ASSERT_TRUE(!res);
  2147. EXPECT_EQ(Error::Connection, res.error());
  2148. }
  2149. TEST(ConnectionErrorTest, InvalidHost2) {
  2150. auto host = "httpcan.org/";
  2151. #ifdef CPPHTTPLIB_SSL_ENABLED
  2152. SSLClient cli(host);
  2153. #else
  2154. Client cli(host);
  2155. #endif
  2156. cli.set_connection_timeout(std::chrono::seconds(2));
  2157. auto res = cli.Get("/");
  2158. ASSERT_TRUE(!res);
  2159. EXPECT_EQ(Error::Connection, res.error());
  2160. }
  2161. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2162. auto host = "httpcan.org/";
  2163. #ifdef CPPHTTPLIB_SSL_ENABLED
  2164. SSLClient cli(host);
  2165. #else
  2166. Client cli(host);
  2167. #endif
  2168. cli.set_connection_timeout(std::chrono::seconds(2));
  2169. auto res = cli.Get("/");
  2170. ASSERT_TRUE(!res);
  2171. stringstream s;
  2172. s << "error code: " << res.error();
  2173. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2174. }
  2175. TEST(ConnectionErrorTest, InvalidPort) {
  2176. auto host = "localhost";
  2177. auto port = 44380;
  2178. #ifdef CPPHTTPLIB_SSL_ENABLED
  2179. SSLClient cli(host, port);
  2180. #else
  2181. Client cli(host, port);
  2182. #endif
  2183. cli.set_connection_timeout(std::chrono::seconds(2));
  2184. auto res = cli.Get("/");
  2185. ASSERT_TRUE(!res);
  2186. EXPECT_TRUE(Error::Connection == res.error() ||
  2187. Error::ConnectionTimeout == res.error());
  2188. }
  2189. TEST(ConnectionErrorTest, Timeout_Online) {
  2190. auto host = "google.com";
  2191. #ifdef CPPHTTPLIB_SSL_ENABLED
  2192. auto port = 44380;
  2193. SSLClient cli(host, port);
  2194. #else
  2195. auto port = 8080;
  2196. Client cli(host, port);
  2197. #endif
  2198. cli.set_connection_timeout(std::chrono::seconds(2));
  2199. // only probe one address type so that the error reason
  2200. // correlates to the timed-out IPv4, not the unsupported
  2201. // IPv6 connection attempt
  2202. cli.set_address_family(AF_INET);
  2203. auto res = cli.Get("/");
  2204. ASSERT_TRUE(!res);
  2205. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2206. }
  2207. TEST(CancelTest, NoCancel_Online) {
  2208. auto host = "httpbingo.org";
  2209. auto path = std::string{"/range/32"};
  2210. #ifdef CPPHTTPLIB_SSL_ENABLED
  2211. auto port = 443;
  2212. SSLClient cli(host, port);
  2213. #else
  2214. auto port = 80;
  2215. Client cli(host, port);
  2216. #endif
  2217. cli.set_connection_timeout(std::chrono::seconds(5));
  2218. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2220. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2221. EXPECT_EQ(StatusCode::OK_200, res->status);
  2222. }
  2223. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2224. // Use /bytes with a large payload so that the DownloadProgress callback
  2225. // (which only fires for Content-Length responses) is invoked before the
  2226. // entire body is received, giving cancellation a chance to fire.
  2227. auto host = "httpbingo.org";
  2228. auto path = std::string{"/bytes/524288"};
  2229. #ifdef CPPHTTPLIB_SSL_ENABLED
  2230. auto port = 443;
  2231. SSLClient cli(host, port);
  2232. #else
  2233. auto port = 80;
  2234. Client cli(host, port);
  2235. #endif
  2236. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2237. cli.set_connection_timeout(std::chrono::seconds(5));
  2238. ASSERT_TRUE(!res);
  2239. EXPECT_EQ(Error::Canceled, res.error());
  2240. }
  2241. TEST(CancelTest, WithCancelLargePayload_Online) {
  2242. auto host = "httpbingo.org";
  2243. auto path = std::string{"/bytes/524288"};
  2244. #ifdef CPPHTTPLIB_SSL_ENABLED
  2245. auto port = 443;
  2246. SSLClient cli(host, port);
  2247. #else
  2248. auto port = 80;
  2249. Client cli(host, port);
  2250. #endif
  2251. cli.set_connection_timeout(std::chrono::seconds(5));
  2252. uint32_t count = 0;
  2253. auto res =
  2254. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2255. ASSERT_TRUE(!res);
  2256. EXPECT_EQ(Error::Canceled, res.error());
  2257. }
  2258. TEST(CancelTest, NoCancelPost) {
  2259. Server svr;
  2260. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2261. res.set_content("Hello World!", "text/plain");
  2262. });
  2263. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2264. auto se = detail::scope_exit([&] {
  2265. svr.stop();
  2266. thread.join();
  2267. ASSERT_FALSE(svr.is_running());
  2268. });
  2269. svr.wait_until_ready();
  2270. Client cli(HOST, PORT);
  2271. cli.set_connection_timeout(std::chrono::seconds(5));
  2272. auto res =
  2273. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2274. "application/json", [](uint64_t, uint64_t) { return true; });
  2275. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2276. EXPECT_EQ("Hello World!", res->body);
  2277. EXPECT_EQ(StatusCode::OK_200, res->status);
  2278. }
  2279. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2280. Server svr;
  2281. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2282. res.set_content("Hello World!", "text/plain");
  2283. });
  2284. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2285. auto se = detail::scope_exit([&] {
  2286. svr.stop();
  2287. thread.join();
  2288. ASSERT_FALSE(svr.is_running());
  2289. });
  2290. svr.wait_until_ready();
  2291. Client cli(HOST, PORT);
  2292. cli.set_connection_timeout(std::chrono::seconds(5));
  2293. auto res =
  2294. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2295. "application/json", [](uint64_t, uint64_t) { return false; });
  2296. ASSERT_TRUE(!res);
  2297. EXPECT_EQ(Error::Canceled, res.error());
  2298. }
  2299. TEST(CancelTest, WithCancelLargePayloadPost) {
  2300. Server svr;
  2301. svr.set_payload_max_length(200 * 1024 * 1024);
  2302. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2303. res.set_content(LARGE_DATA, "text/plain");
  2304. });
  2305. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2306. auto se = detail::scope_exit([&] {
  2307. svr.stop();
  2308. thread.join();
  2309. ASSERT_FALSE(svr.is_running());
  2310. });
  2311. svr.wait_until_ready();
  2312. Client cli(HOST, PORT);
  2313. cli.set_payload_max_length(200 * 1024 * 1024);
  2314. cli.set_connection_timeout(std::chrono::seconds(5));
  2315. auto res =
  2316. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2317. "application/json", [](uint64_t, uint64_t) { return false; });
  2318. ASSERT_TRUE(!res);
  2319. EXPECT_EQ(Error::Canceled, res.error());
  2320. }
  2321. TEST(CancelTest, NoCancelPut) {
  2322. Server svr;
  2323. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2324. res.set_content("Hello World!", "text/plain");
  2325. });
  2326. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2327. auto se = detail::scope_exit([&] {
  2328. svr.stop();
  2329. thread.join();
  2330. ASSERT_FALSE(svr.is_running());
  2331. });
  2332. svr.wait_until_ready();
  2333. Client cli(HOST, PORT);
  2334. cli.set_connection_timeout(std::chrono::seconds(5));
  2335. auto res =
  2336. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2337. "application/json", [](uint64_t, uint64_t) { return true; });
  2338. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2339. EXPECT_EQ("Hello World!", res->body);
  2340. EXPECT_EQ(StatusCode::OK_200, res->status);
  2341. }
  2342. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2343. Server svr;
  2344. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2345. res.set_content("Hello World!", "text/plain");
  2346. });
  2347. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2348. auto se = detail::scope_exit([&] {
  2349. svr.stop();
  2350. thread.join();
  2351. ASSERT_FALSE(svr.is_running());
  2352. });
  2353. svr.wait_until_ready();
  2354. Client cli(HOST, PORT);
  2355. cli.set_connection_timeout(std::chrono::seconds(5));
  2356. auto res =
  2357. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2358. "application/json", [](uint64_t, uint64_t) { return false; });
  2359. ASSERT_TRUE(!res);
  2360. EXPECT_EQ(Error::Canceled, res.error());
  2361. }
  2362. TEST(CancelTest, WithCancelLargePayloadPut) {
  2363. Server svr;
  2364. svr.set_payload_max_length(200 * 1024 * 1024);
  2365. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2366. res.set_content(LARGE_DATA, "text/plain");
  2367. });
  2368. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2369. auto se = detail::scope_exit([&] {
  2370. svr.stop();
  2371. thread.join();
  2372. ASSERT_FALSE(svr.is_running());
  2373. });
  2374. svr.wait_until_ready();
  2375. Client cli(HOST, PORT);
  2376. cli.set_payload_max_length(200 * 1024 * 1024);
  2377. cli.set_connection_timeout(std::chrono::seconds(5));
  2378. auto res =
  2379. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2380. "application/json", [](uint64_t, uint64_t) { return false; });
  2381. ASSERT_TRUE(!res);
  2382. EXPECT_EQ(Error::Canceled, res.error());
  2383. }
  2384. TEST(CancelTest, NoCancelPatch) {
  2385. Server svr;
  2386. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2387. res.set_content("Hello World!", "text/plain");
  2388. });
  2389. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2390. auto se = detail::scope_exit([&] {
  2391. svr.stop();
  2392. thread.join();
  2393. ASSERT_FALSE(svr.is_running());
  2394. });
  2395. svr.wait_until_ready();
  2396. Client cli(HOST, PORT);
  2397. cli.set_connection_timeout(std::chrono::seconds(5));
  2398. auto res =
  2399. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2400. "application/json", [](uint64_t, uint64_t) { return true; });
  2401. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2402. EXPECT_EQ("Hello World!", res->body);
  2403. EXPECT_EQ(StatusCode::OK_200, res->status);
  2404. }
  2405. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2406. Server svr;
  2407. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2408. res.set_content("Hello World!", "text/plain");
  2409. });
  2410. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2411. auto se = detail::scope_exit([&] {
  2412. svr.stop();
  2413. thread.join();
  2414. ASSERT_FALSE(svr.is_running());
  2415. });
  2416. svr.wait_until_ready();
  2417. Client cli(HOST, PORT);
  2418. cli.set_connection_timeout(std::chrono::seconds(5));
  2419. auto res =
  2420. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2421. "application/json", [](uint64_t, uint64_t) { return false; });
  2422. ASSERT_TRUE(!res);
  2423. EXPECT_EQ(Error::Canceled, res.error());
  2424. }
  2425. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2426. Server svr;
  2427. svr.set_payload_max_length(200 * 1024 * 1024);
  2428. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2429. res.set_content(LARGE_DATA, "text/plain");
  2430. });
  2431. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2432. auto se = detail::scope_exit([&] {
  2433. svr.stop();
  2434. thread.join();
  2435. ASSERT_FALSE(svr.is_running());
  2436. });
  2437. svr.wait_until_ready();
  2438. Client cli(HOST, PORT);
  2439. cli.set_payload_max_length(200 * 1024 * 1024);
  2440. cli.set_connection_timeout(std::chrono::seconds(5));
  2441. auto res =
  2442. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2443. "application/json", [](uint64_t, uint64_t) { return false; });
  2444. ASSERT_TRUE(!res);
  2445. EXPECT_EQ(Error::Canceled, res.error());
  2446. }
  2447. TEST(CancelTest, NoCancelDelete) {
  2448. Server svr;
  2449. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2450. res.set_content("Hello World!", "text/plain");
  2451. });
  2452. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2453. auto se = detail::scope_exit([&] {
  2454. svr.stop();
  2455. thread.join();
  2456. ASSERT_FALSE(svr.is_running());
  2457. });
  2458. svr.wait_until_ready();
  2459. Client cli(HOST, PORT);
  2460. cli.set_connection_timeout(std::chrono::seconds(5));
  2461. auto res =
  2462. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2463. "application/json", [](uint64_t, uint64_t) { return true; });
  2464. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2465. EXPECT_EQ("Hello World!", res->body);
  2466. EXPECT_EQ(StatusCode::OK_200, res->status);
  2467. }
  2468. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2469. Server svr;
  2470. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2471. res.set_content("Hello World!", "text/plain");
  2472. });
  2473. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2474. auto se = detail::scope_exit([&] {
  2475. svr.stop();
  2476. thread.join();
  2477. ASSERT_FALSE(svr.is_running());
  2478. });
  2479. svr.wait_until_ready();
  2480. Client cli(HOST, PORT);
  2481. cli.set_connection_timeout(std::chrono::seconds(5));
  2482. auto res =
  2483. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2484. "application/json", [](uint64_t, uint64_t) { return false; });
  2485. ASSERT_TRUE(!res);
  2486. EXPECT_EQ(Error::Canceled, res.error());
  2487. }
  2488. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2489. Server svr;
  2490. svr.set_payload_max_length(200 * 1024 * 1024);
  2491. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2492. res.set_content(LARGE_DATA, "text/plain");
  2493. });
  2494. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2495. auto se = detail::scope_exit([&] {
  2496. svr.stop();
  2497. thread.join();
  2498. ASSERT_FALSE(svr.is_running());
  2499. });
  2500. svr.wait_until_ready();
  2501. Client cli(HOST, PORT);
  2502. cli.set_payload_max_length(200 * 1024 * 1024);
  2503. cli.set_connection_timeout(std::chrono::seconds(5));
  2504. auto res =
  2505. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2506. "application/json", [](uint64_t, uint64_t) { return false; });
  2507. ASSERT_TRUE(!res);
  2508. EXPECT_EQ(Error::Canceled, res.error());
  2509. }
  2510. static std::string remove_whitespace(const std::string &input) {
  2511. std::string output;
  2512. output.reserve(input.size());
  2513. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2514. [](unsigned char c) { return !std::isspace(c); });
  2515. return output;
  2516. }
  2517. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2518. auto host = "httpbingo.org";
  2519. auto path = std::string{"/basic-auth/hello/world"};
  2520. #ifdef CPPHTTPLIB_SSL_ENABLED
  2521. auto port = 443;
  2522. SSLClient cli(host, port);
  2523. #else
  2524. auto port = 80;
  2525. Client cli(host, port);
  2526. #endif
  2527. {
  2528. auto res = cli.Get(path);
  2529. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2530. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2531. }
  2532. {
  2533. auto res = cli.Get(
  2534. path, Headers{make_basic_authentication_header("hello", "world")});
  2535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2536. auto body = remove_whitespace(res->body);
  2537. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2538. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2539. EXPECT_EQ(StatusCode::OK_200, res->status);
  2540. }
  2541. {
  2542. cli.set_basic_auth("hello", "world");
  2543. auto res = cli.Get(path);
  2544. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2545. auto body = remove_whitespace(res->body);
  2546. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2547. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2548. EXPECT_EQ(StatusCode::OK_200, res->status);
  2549. }
  2550. {
  2551. cli.set_basic_auth("hello", "bad");
  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. cli.set_basic_auth("bad", "world");
  2558. auto res = cli.Get(path);
  2559. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2560. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2561. }
  2562. }
  2563. #ifdef CPPHTTPLIB_SSL_ENABLED
  2564. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2565. auto host = "httpbingo.org";
  2566. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2567. auto paths = std::vector<std::string>{
  2568. "/digest-auth/auth/hello/world/MD5",
  2569. "/digest-auth/auth/hello/world/SHA-256",
  2570. };
  2571. auto port = 443;
  2572. SSLClient cli(host, port);
  2573. {
  2574. auto res = cli.Get(unauth_path);
  2575. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2576. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2577. }
  2578. {
  2579. cli.set_digest_auth("hello", "world");
  2580. for (const auto &path : paths) {
  2581. auto res = cli.Get(path.c_str());
  2582. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2583. auto body = remove_whitespace(res->body);
  2584. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2585. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2586. EXPECT_EQ(StatusCode::OK_200, res->status);
  2587. }
  2588. cli.set_digest_auth("hello", "bad");
  2589. for (const auto &path : paths) {
  2590. auto res = cli.Get(path.c_str());
  2591. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2592. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2593. }
  2594. }
  2595. }
  2596. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2597. // comma-separated list of challenges, and each challenge may itself carry a
  2598. // comma-separated auth-param list, so a server can legally offer Basic
  2599. // before Digest, either as two field lines or packed into one. Runs one 401
  2600. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2601. // value() joins them in receipt order) and checks that the retry carries a
  2602. // well-formed Digest Authorization header naming expected_realm.
  2603. static void
  2604. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2605. const std::string &expected_realm) {
  2606. std::atomic<int> hits{0};
  2607. Server svr;
  2608. svr.Get("/x", [&](const Request &req, Response &res) {
  2609. if (++hits == 1) {
  2610. res.status = StatusCode::Unauthorized_401;
  2611. for (const auto &challenge : challenges) {
  2612. res.set_header("WWW-Authenticate", challenge);
  2613. }
  2614. } else {
  2615. auto authorization = req.get_header_value("Authorization");
  2616. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2617. EXPECT_NE(std::string::npos,
  2618. authorization.find("realm=\"" + expected_realm + "\""));
  2619. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2620. res.set_content("ok", "text/plain");
  2621. }
  2622. });
  2623. auto port = svr.bind_to_any_port(HOST);
  2624. std::thread t([&]() { svr.listen_after_bind(); });
  2625. auto se = detail::scope_exit([&] {
  2626. svr.stop();
  2627. t.join();
  2628. });
  2629. svr.wait_until_ready();
  2630. Client cli(HOST, port);
  2631. cli.set_digest_auth("hello", "world");
  2632. auto res = cli.Get("/x");
  2633. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2634. EXPECT_EQ(2, hits.load());
  2635. }
  2636. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2637. static const char *kDigestChallenge =
  2638. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2639. "algorithm=MD5";
  2640. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2641. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2642. "testrealm");
  2643. }
  2644. // Same challenge list with the schemes in the opposite order, to make sure
  2645. // the fix above didn't just special-case "Basic first".
  2646. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2647. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2648. "testrealm");
  2649. }
  2650. // A comma inside a quoted auth-param value must not be mistaken for the
  2651. // separator between two challenges (or two auth-params).
  2652. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2653. run_digest_challenge_list_test(
  2654. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  2655. "algorithm=MD5"},
  2656. "test,realm");
  2657. }
  2658. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  2659. // make_digest_authentication_header() dereferences both unconditionally, so
  2660. // a server sending a challenge missing either one must not be treated as
  2661. // usable -- doing so used to crash the client with std::out_of_range.
  2662. static void run_digest_challenge_missing_field_test(const char *challenge) {
  2663. Server svr;
  2664. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  2665. res.status = StatusCode::Unauthorized_401;
  2666. res.set_header("WWW-Authenticate", challenge);
  2667. });
  2668. auto port = svr.bind_to_any_port(HOST);
  2669. std::thread t([&]() { svr.listen_after_bind(); });
  2670. auto se = detail::scope_exit([&] {
  2671. svr.stop();
  2672. t.join();
  2673. });
  2674. svr.wait_until_ready();
  2675. Client cli(HOST, port);
  2676. cli.set_digest_auth("hello", "world");
  2677. auto res = cli.Get("/x");
  2678. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2679. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2680. }
  2681. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  2682. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  2683. }
  2684. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  2685. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  2686. }
  2687. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  2688. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  2689. }
  2690. #endif
  2691. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  2692. auto host = "google.com";
  2693. auto another_host = "example.com";
  2694. auto wrong_ip = "0.0.0.0";
  2695. #ifdef CPPHTTPLIB_SSL_ENABLED
  2696. SSLClient cli(host);
  2697. #else
  2698. Client cli(host);
  2699. #endif
  2700. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  2701. auto res = cli.Get("/");
  2702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2703. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  2704. }
  2705. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  2706. auto host = "google.com";
  2707. auto wrong_ip = "0.0.0.0";
  2708. #ifdef CPPHTTPLIB_SSL_ENABLED
  2709. SSLClient cli(host);
  2710. #else
  2711. Client cli(host);
  2712. #endif
  2713. cli.set_hostname_addr_map({{host, wrong_ip}});
  2714. auto res = cli.Get("/");
  2715. ASSERT_TRUE(!res);
  2716. EXPECT_EQ(Error::Connection, res.error());
  2717. }
  2718. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  2719. // A mapped value that is not an IP literal must be resolved. "localhost"
  2720. // resolves from the hosts file, so this test needs no external DNS.
  2721. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  2722. auto host = "target.invalid";
  2723. Server svr;
  2724. std::string received_host;
  2725. svr.Get("/hi", [&](const Request &req, Response &res) {
  2726. received_host = req.get_header_value("Host");
  2727. res.set_content("Hello World!", "text/plain");
  2728. });
  2729. auto port = svr.bind_to_any_port(HOST);
  2730. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2731. auto se = detail::scope_exit([&] {
  2732. svr.stop();
  2733. thread.join();
  2734. ASSERT_FALSE(svr.is_running());
  2735. });
  2736. svr.wait_until_ready();
  2737. Client cli(host, port);
  2738. cli.set_hostname_addr_map({{host, HOST}});
  2739. auto res = cli.Get("/hi");
  2740. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2741. EXPECT_EQ(StatusCode::OK_200, res->status);
  2742. // The mapping only redirects the connection; the identity stays host_.
  2743. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  2744. }
  2745. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  2746. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  2747. auto host = "target.invalid";
  2748. Server svr;
  2749. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2750. res.set_content("Hello World!", "text/plain");
  2751. });
  2752. auto port = svr.bind_to_any_port("127.0.0.1");
  2753. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2754. auto se = detail::scope_exit([&] {
  2755. svr.stop();
  2756. thread.join();
  2757. ASSERT_FALSE(svr.is_running());
  2758. });
  2759. svr.wait_until_ready();
  2760. Client cli(host, port);
  2761. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  2762. auto res = cli.Get("/hi");
  2763. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2764. EXPECT_EQ(StatusCode::OK_200, res->status);
  2765. }
  2766. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  2767. // An empty mapped value must leave host_ as the connection target. Without
  2768. // that guard the empty value would become the host argument, getaddrinfo
  2769. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  2770. // loopback - silently connecting somewhere the caller never asked for.
  2771. // The server listens on loopback, so such a fallback would succeed and is
  2772. // therefore observable as a failure of this test.
  2773. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  2774. Server svr;
  2775. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2776. res.set_content("Hello World!", "text/plain");
  2777. });
  2778. auto port = svr.bind_to_any_port(HOST);
  2779. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2780. auto se = detail::scope_exit([&] {
  2781. svr.stop();
  2782. thread.join();
  2783. ASSERT_FALSE(svr.is_running());
  2784. });
  2785. svr.wait_until_ready();
  2786. Client cli(blackhole, port);
  2787. cli.set_hostname_addr_map({{blackhole, ""}});
  2788. cli.set_connection_timeout(1);
  2789. auto res = cli.Get("/hi");
  2790. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  2791. }
  2792. TEST(AbsoluteRedirectTest, Redirect_Online) {
  2793. auto host = "httpbingo.org";
  2794. auto path = std::string{"/absolute-redirect/3"};
  2795. #ifdef CPPHTTPLIB_SSL_ENABLED
  2796. SSLClient cli(host);
  2797. #else
  2798. Client cli(host);
  2799. #endif
  2800. cli.set_follow_location(true);
  2801. auto res = cli.Get(path);
  2802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2803. EXPECT_EQ(StatusCode::OK_200, res->status);
  2804. }
  2805. TEST(RedirectTest, Redirect_Online) {
  2806. auto host = "httpbingo.org";
  2807. auto path = std::string{"/redirect/3"};
  2808. #ifdef CPPHTTPLIB_SSL_ENABLED
  2809. SSLClient cli(host);
  2810. #else
  2811. Client cli(host);
  2812. #endif
  2813. cli.set_follow_location(true);
  2814. auto res = cli.Get(path);
  2815. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2816. EXPECT_EQ(StatusCode::OK_200, res->status);
  2817. }
  2818. TEST(RelativeRedirectTest, Redirect_Online) {
  2819. auto host = "httpbingo.org";
  2820. auto path = std::string{"/relative-redirect/3"};
  2821. #ifdef CPPHTTPLIB_SSL_ENABLED
  2822. SSLClient cli(host);
  2823. #else
  2824. Client cli(host);
  2825. #endif
  2826. cli.set_follow_location(true);
  2827. auto res = cli.Get(path);
  2828. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2829. EXPECT_EQ(StatusCode::OK_200, res->status);
  2830. }
  2831. TEST(TooManyRedirectTest, Redirect_Online) {
  2832. auto host = "httpbingo.org";
  2833. auto path = std::string{"/redirect/21"};
  2834. #ifdef CPPHTTPLIB_SSL_ENABLED
  2835. SSLClient cli(host);
  2836. #else
  2837. Client cli(host);
  2838. #endif
  2839. cli.set_follow_location(true);
  2840. auto res = cli.Get(path);
  2841. ASSERT_TRUE(!res);
  2842. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  2843. }
  2844. #ifdef CPPHTTPLIB_SSL_ENABLED
  2845. TEST(YahooRedirectTest, Redirect_Online) {
  2846. Client cli("yahoo.com");
  2847. auto res = cli.Get("/");
  2848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2849. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  2850. cli.set_follow_location(true);
  2851. res = cli.Get("/");
  2852. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2853. EXPECT_EQ(StatusCode::OK_200, res->status);
  2854. EXPECT_EQ("https://www.yahoo.com/", res->location);
  2855. }
  2856. // Previously "nghttp2.org" "/httpbin/redirect-to"
  2857. #define REDIR_HOST "httpbingo.org"
  2858. #define REDIR_PATH "/redirect-to"
  2859. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  2860. SSLClient cli(REDIR_HOST);
  2861. cli.set_follow_location(true);
  2862. auto res =
  2863. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  2864. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2865. EXPECT_EQ(StatusCode::OK_200, res->status);
  2866. }
  2867. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  2868. SSLClient cli(REDIR_HOST);
  2869. cli.set_follow_location(true);
  2870. Params params;
  2871. params.emplace("url", "http://example.com");
  2872. params.emplace("status_code", "302");
  2873. auto res = cli.Get(REDIR_PATH, params, Headers{});
  2874. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2875. EXPECT_EQ(StatusCode::OK_200, res->status);
  2876. }
  2877. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  2878. SSLClient cli(REDIR_HOST);
  2879. cli.set_follow_location(true);
  2880. Params params;
  2881. params.emplace("url", "http://example.com");
  2882. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  2883. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2884. EXPECT_EQ(StatusCode::OK_200, res->status);
  2885. }
  2886. TEST(UrlWithSpace, Redirect_Online) {
  2887. SSLClient cli("edge.forgecdn.net");
  2888. cli.set_follow_location(true);
  2889. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  2890. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2891. EXPECT_EQ(StatusCode::OK_200, res->status);
  2892. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  2893. }
  2894. #endif
  2895. #if !defined(_WIN32) && !defined(_WIN64)
  2896. TEST(ReceiveSignals, Signal) {
  2897. auto setupSignalHandlers = []() {
  2898. struct sigaction act;
  2899. sigemptyset(&act.sa_mask);
  2900. act.sa_flags = SA_SIGINFO;
  2901. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  2902. switch (sig) {
  2903. case SIGINT:
  2904. default: break;
  2905. }
  2906. };
  2907. ::sigaction(SIGINT, &act, nullptr);
  2908. };
  2909. Server svr;
  2910. int port = 0;
  2911. auto thread = std::thread([&]() {
  2912. setupSignalHandlers();
  2913. port = svr.bind_to_any_port(HOST);
  2914. svr.listen_after_bind();
  2915. });
  2916. auto se = detail::scope_exit([&] {
  2917. svr.stop();
  2918. thread.join();
  2919. ASSERT_FALSE(svr.is_running());
  2920. });
  2921. svr.wait_until_ready();
  2922. ASSERT_TRUE(svr.is_running());
  2923. pthread_kill(thread.native_handle(), SIGINT);
  2924. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  2925. ASSERT_TRUE(svr.is_running());
  2926. }
  2927. #endif
  2928. TEST(RedirectToDifferentPort, Redirect) {
  2929. Server svr1;
  2930. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  2931. res.set_content("Hello World!", "text/plain");
  2932. });
  2933. int svr1_port = 0;
  2934. auto thread1 = std::thread([&]() {
  2935. svr1_port = svr1.bind_to_any_port(HOST);
  2936. svr1.listen_after_bind();
  2937. });
  2938. Server svr2;
  2939. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  2940. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  2941. });
  2942. int svr2_port = 0;
  2943. auto thread2 = std::thread([&]() {
  2944. svr2_port = svr2.bind_to_any_port(HOST);
  2945. svr2.listen_after_bind();
  2946. });
  2947. auto se = detail::scope_exit([&] {
  2948. svr2.stop();
  2949. thread2.join();
  2950. svr1.stop();
  2951. thread1.join();
  2952. ASSERT_FALSE(svr2.is_running());
  2953. ASSERT_FALSE(svr1.is_running());
  2954. });
  2955. svr1.wait_until_ready();
  2956. svr2.wait_until_ready();
  2957. Client cli("localhost", svr2_port);
  2958. cli.set_follow_location(true);
  2959. auto res = cli.Get("/2");
  2960. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2961. EXPECT_EQ(StatusCode::OK_200, res->status);
  2962. EXPECT_EQ("Hello World!", res->body);
  2963. }
  2964. static void
  2965. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  2966. Server svr1;
  2967. std::string captured_authorization;
  2968. svr1.Get("/target", [&](const Request &req, Response &res) {
  2969. captured_authorization = req.get_header_value("Authorization");
  2970. res.set_content("OK", "text/plain");
  2971. });
  2972. int svr1_port = 0;
  2973. auto thread1 = std::thread([&]() {
  2974. svr1_port = svr1.bind_to_any_port(HOST);
  2975. svr1.listen_after_bind();
  2976. });
  2977. Server svr2;
  2978. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2979. res.set_redirect(
  2980. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  2981. });
  2982. int svr2_port = 0;
  2983. auto thread2 = std::thread([&]() {
  2984. svr2_port = svr2.bind_to_any_port(HOST);
  2985. svr2.listen_after_bind();
  2986. });
  2987. auto se = detail::scope_exit([&] {
  2988. svr2.stop();
  2989. thread2.join();
  2990. svr1.stop();
  2991. thread1.join();
  2992. ASSERT_FALSE(svr2.is_running());
  2993. ASSERT_FALSE(svr1.is_running());
  2994. });
  2995. svr1.wait_until_ready();
  2996. svr2.wait_until_ready();
  2997. Client cli("localhost", svr2_port);
  2998. cli.set_follow_location(true);
  2999. set_auth(cli);
  3000. auto res = cli.Get("/redir");
  3001. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3002. EXPECT_EQ(StatusCode::OK_200, res->status);
  3003. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3004. EXPECT_TRUE(captured_authorization.empty());
  3005. }
  3006. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3007. TestDoNotForwardCredentialsOnRedirect(
  3008. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3009. }
  3010. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3011. TestDoNotForwardCredentialsOnRedirect(
  3012. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3013. }
  3014. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3015. Server svr1;
  3016. std::string captured_cookie;
  3017. bool target_hit = false;
  3018. svr1.Get("/target", [&](const Request &req, Response &res) {
  3019. captured_cookie = req.get_header_value("Cookie");
  3020. target_hit = true;
  3021. res.set_content("OK", "text/plain");
  3022. });
  3023. int svr1_port = 0;
  3024. auto thread1 = std::thread([&]() {
  3025. svr1_port = svr1.bind_to_any_port(HOST);
  3026. svr1.listen_after_bind();
  3027. });
  3028. Server svr2;
  3029. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3030. res.set_redirect(
  3031. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  3032. });
  3033. int svr2_port = 0;
  3034. auto thread2 = std::thread([&]() {
  3035. svr2_port = svr2.bind_to_any_port(HOST);
  3036. svr2.listen_after_bind();
  3037. });
  3038. auto se = detail::scope_exit([&] {
  3039. svr2.stop();
  3040. thread2.join();
  3041. svr1.stop();
  3042. thread1.join();
  3043. ASSERT_FALSE(svr2.is_running());
  3044. ASSERT_FALSE(svr1.is_running());
  3045. });
  3046. svr1.wait_until_ready();
  3047. svr2.wait_until_ready();
  3048. Client cli("localhost", svr2_port);
  3049. cli.set_follow_location(true);
  3050. Headers headers = {{"Cookie", "session_id=SECRET; auth=PRIVATE"}};
  3051. auto res = cli.Get("/redir", headers);
  3052. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3053. EXPECT_EQ(StatusCode::OK_200, res->status);
  3054. EXPECT_TRUE(target_hit);
  3055. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3056. EXPECT_TRUE(captured_cookie.empty());
  3057. }
  3058. TEST(RedirectToSamePort, ForwardCookie) {
  3059. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3060. // header so that ordinary session flows keep working.
  3061. Server svr;
  3062. std::string captured_cookie;
  3063. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3064. res.set_redirect("/target", 302);
  3065. });
  3066. svr.Get("/target", [&](const Request &req, Response &res) {
  3067. captured_cookie = req.get_header_value("Cookie");
  3068. res.set_content("OK", "text/plain");
  3069. });
  3070. auto port = svr.bind_to_any_port(HOST);
  3071. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3072. auto se = detail::scope_exit([&] {
  3073. svr.stop();
  3074. thread.join();
  3075. ASSERT_FALSE(svr.is_running());
  3076. });
  3077. svr.wait_until_ready();
  3078. Client cli(HOST, port);
  3079. cli.set_follow_location(true);
  3080. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3081. auto res = cli.Get("/redir", headers);
  3082. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3083. EXPECT_EQ(StatusCode::OK_200, res->status);
  3084. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3085. }
  3086. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3087. Server svr;
  3088. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3089. // Port number that overflows int — should not crash
  3090. res.set_redirect("http://localhost:99999999999999999999/target");
  3091. });
  3092. auto port = svr.bind_to_any_port(HOST);
  3093. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3094. auto se = detail::scope_exit([&] {
  3095. svr.stop();
  3096. thread.join();
  3097. ASSERT_FALSE(svr.is_running());
  3098. });
  3099. svr.wait_until_ready();
  3100. Client cli(HOST, port);
  3101. cli.set_follow_location(true);
  3102. auto res = cli.Get("/redir");
  3103. // Should fail gracefully, not crash (no valid response due to bad port)
  3104. EXPECT_FALSE(res);
  3105. }
  3106. TEST(RedirectFromPageWithContent, Redirect) {
  3107. Server svr;
  3108. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3109. res.set_content("___", "text/plain");
  3110. res.set_redirect("/2");
  3111. });
  3112. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3113. res.set_content("Hello World!", "text/plain");
  3114. });
  3115. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3116. auto se = detail::scope_exit([&] {
  3117. svr.stop();
  3118. th.join();
  3119. ASSERT_FALSE(svr.is_running());
  3120. });
  3121. svr.wait_until_ready();
  3122. {
  3123. Client cli("localhost", PORT);
  3124. cli.set_follow_location(true);
  3125. std::string body;
  3126. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3127. body.append(data, data_length);
  3128. return true;
  3129. });
  3130. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3131. EXPECT_EQ(StatusCode::OK_200, res->status);
  3132. EXPECT_EQ("Hello World!", body);
  3133. }
  3134. {
  3135. Client cli("localhost", PORT);
  3136. std::string body;
  3137. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3138. body.append(data, data_length);
  3139. return true;
  3140. });
  3141. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3142. EXPECT_EQ(StatusCode::Found_302, res->status);
  3143. EXPECT_EQ("___", body);
  3144. }
  3145. }
  3146. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3147. Server svr;
  3148. auto port_str = std::to_string(PORT);
  3149. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3150. auto expected_host = "[::1]:" + port_str;
  3151. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3152. res.set_content("___", "text/plain");
  3153. // res.set_redirect("/2");
  3154. res.set_redirect(redirect_url);
  3155. });
  3156. svr.Get("/2", [&](const Request &req, Response &res) {
  3157. auto host_header = req.headers.find("Host");
  3158. ASSERT_TRUE(host_header != req.headers.end());
  3159. EXPECT_EQ(expected_host, host_header->second);
  3160. res.set_content("Hello World!", "text/plain");
  3161. });
  3162. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3163. auto se = detail::scope_exit([&] {
  3164. svr.stop();
  3165. th.join();
  3166. ASSERT_FALSE(svr.is_running());
  3167. });
  3168. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3169. // actually starts anything, so the condition !svr.is_running() will
  3170. // always remain true, and the loop never stops.
  3171. // This basically counts how many milliseconds have passed since the
  3172. // call to svr.listen(), and if after 5 seconds nothing started yet
  3173. // aborts the test.
  3174. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3175. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3176. ASSERT_LT(milliseconds, 5000U);
  3177. }
  3178. {
  3179. Client cli("::1", PORT);
  3180. cli.set_follow_location(true);
  3181. std::string body;
  3182. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3183. body.append(data, data_length);
  3184. return true;
  3185. });
  3186. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3187. EXPECT_EQ(StatusCode::OK_200, res->status);
  3188. EXPECT_EQ("Hello World!", body);
  3189. }
  3190. {
  3191. Client cli("::1", PORT);
  3192. std::string body;
  3193. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3194. body.append(data, data_length);
  3195. return true;
  3196. });
  3197. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3198. EXPECT_EQ(StatusCode::Found_302, res->status);
  3199. EXPECT_EQ("___", body);
  3200. }
  3201. }
  3202. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3203. Server svr;
  3204. svr.Get("/foo", [](const Request &req, Response &res) {
  3205. auto a = req.params.find("a");
  3206. if (a != req.params.end()) {
  3207. res.set_content((*a).second, "text/plain");
  3208. res.status = StatusCode::OK_200;
  3209. } else {
  3210. res.status = StatusCode::BadRequest_400;
  3211. }
  3212. });
  3213. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3214. auto se = detail::scope_exit([&] {
  3215. svr.stop();
  3216. thread.join();
  3217. ASSERT_FALSE(svr.is_running());
  3218. });
  3219. svr.wait_until_ready();
  3220. {
  3221. Client cli(HOST, PORT);
  3222. cli.set_path_encode(false);
  3223. auto res = cli.Get("/foo?a=explicitly+encoded");
  3224. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3225. EXPECT_EQ(StatusCode::OK_200, res->status);
  3226. // This expects it back with a space, as the `+` won't have been
  3227. // url-encoded, and server-side the params get decoded turning `+`
  3228. // into spaces.
  3229. EXPECT_EQ("explicitly encoded", res->body);
  3230. }
  3231. }
  3232. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3233. // When path encoding is disabled the client must transmit the supplied
  3234. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3235. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3236. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3237. // than a space (0x20). Assert on the raw wire target to catch this.
  3238. Server svr;
  3239. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3240. svr.Get("/foo", [&](const Request &req, Response &res) {
  3241. EXPECT_EQ(expected_target, req.target);
  3242. res.status = StatusCode::OK_200;
  3243. });
  3244. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3245. auto se = detail::scope_exit([&] {
  3246. svr.stop();
  3247. thread.join();
  3248. ASSERT_FALSE(svr.is_running());
  3249. });
  3250. svr.wait_until_ready();
  3251. {
  3252. Client cli(HOST, PORT);
  3253. cli.set_path_encode(false);
  3254. auto res = cli.Get(expected_target.c_str());
  3255. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3256. EXPECT_EQ(StatusCode::OK_200, res->status);
  3257. }
  3258. }
  3259. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3260. // `open_stream()` used to skip the path encoding that the buffered send
  3261. // path applies, so the same `path` produced different bytes in the request
  3262. // line depending on which API was used. Assert the two agree.
  3263. Server svr;
  3264. std::string target;
  3265. svr.Get(".*", [&](const Request &req, Response &res) {
  3266. target = req.target;
  3267. res.status = StatusCode::OK_200;
  3268. });
  3269. auto port = svr.bind_to_any_port(HOST);
  3270. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3271. auto se = detail::scope_exit([&] {
  3272. svr.stop();
  3273. thread.join();
  3274. ASSERT_FALSE(svr.is_running());
  3275. });
  3276. svr.wait_until_ready();
  3277. struct {
  3278. const char *path;
  3279. const char *expected;
  3280. } cases[] = {
  3281. {"/a b?x=1", "/a%20b?x=1"},
  3282. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3283. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3284. };
  3285. for (const auto &c : cases) {
  3286. Client cli(HOST, port);
  3287. target.clear();
  3288. auto res = cli.Get(c.path);
  3289. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3290. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3291. auto buffered_target = target;
  3292. target.clear();
  3293. auto handle = cli.open_stream("GET", c.path);
  3294. EXPECT_TRUE(handle.is_valid())
  3295. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3296. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3297. }
  3298. }
  3299. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3300. // The `set_path_encode(false)` contract — transmit the supplied target
  3301. // verbatim — must hold for the streaming API too.
  3302. Server svr;
  3303. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3304. std::string target;
  3305. svr.Get("/foo", [&](const Request &req, Response &res) {
  3306. target = req.target;
  3307. res.status = StatusCode::OK_200;
  3308. });
  3309. auto port = svr.bind_to_any_port(HOST);
  3310. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3311. auto se = detail::scope_exit([&] {
  3312. svr.stop();
  3313. thread.join();
  3314. ASSERT_FALSE(svr.is_running());
  3315. });
  3316. svr.wait_until_ready();
  3317. {
  3318. Client cli(HOST, port);
  3319. cli.set_path_encode(false);
  3320. auto handle = cli.open_stream("GET", expected_target);
  3321. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3322. EXPECT_EQ(expected_target, target);
  3323. }
  3324. }
  3325. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3326. // With path encoding enabled a CR/LF in the target is percent-encoded
  3327. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3328. // write_request_line still backstops `set_path_encode(false)`, which is
  3329. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3330. Server svr;
  3331. // Captured before routing: the decoded path contains a newline, which a
  3332. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3333. std::string target;
  3334. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3335. target = req.target;
  3336. res.status = StatusCode::OK_200;
  3337. return Server::HandlerResponse::Handled;
  3338. });
  3339. auto port = svr.bind_to_any_port(HOST);
  3340. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3341. auto se = detail::scope_exit([&] {
  3342. svr.stop();
  3343. thread.join();
  3344. ASSERT_FALSE(svr.is_running());
  3345. });
  3346. svr.wait_until_ready();
  3347. {
  3348. Client cli(HOST, port);
  3349. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3350. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3351. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3352. }
  3353. }
  3354. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3355. // Nothing may reach the wire: a raw CR/LF target would split the request
  3356. // line and inject headers.
  3357. Server svr;
  3358. // Pre-routing so that "not called" means nothing reached the server at all,
  3359. // rather than merely failing to match a handler pattern.
  3360. auto handler_called = false;
  3361. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3362. handler_called = true;
  3363. res.status = StatusCode::OK_200;
  3364. return Server::HandlerResponse::Handled;
  3365. });
  3366. auto port = svr.bind_to_any_port(HOST);
  3367. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3368. auto se = detail::scope_exit([&] {
  3369. svr.stop();
  3370. thread.join();
  3371. ASSERT_FALSE(svr.is_running());
  3372. });
  3373. svr.wait_until_ready();
  3374. {
  3375. Client cli(HOST, port);
  3376. cli.set_path_encode(false);
  3377. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3378. EXPECT_FALSE(handle.is_valid());
  3379. EXPECT_EQ(Error::Write, handle.error);
  3380. EXPECT_FALSE(handler_called);
  3381. }
  3382. }
  3383. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3384. // Which of the two branches runs is decided by whether the query component
  3385. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3386. // an empty query and must still fall back to building one from
  3387. // `req.params`, while a non-empty query must win over `req.params`.
  3388. Server svr;
  3389. std::string target;
  3390. svr.Get("/foo", [&](const Request &req, Response &res) {
  3391. target = req.target;
  3392. res.status = StatusCode::OK_200;
  3393. });
  3394. auto port = svr.bind_to_any_port(HOST);
  3395. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3396. auto se = detail::scope_exit([&] {
  3397. svr.stop();
  3398. thread.join();
  3399. ASSERT_FALSE(svr.is_running());
  3400. });
  3401. svr.wait_until_ready();
  3402. {
  3403. // Trailing `?` -> empty query component -> `req.params` is used.
  3404. Client cli(HOST, port);
  3405. Request req;
  3406. req.method = "GET";
  3407. req.path = "/foo?";
  3408. req.params.emplace("a", "1");
  3409. target.clear();
  3410. auto res = cli.send(req);
  3411. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3412. EXPECT_EQ("/foo?a=1", target);
  3413. }
  3414. {
  3415. // Non-empty query in `req.path` -> `req.params` is not appended.
  3416. Client cli(HOST, port);
  3417. Request req;
  3418. req.method = "GET";
  3419. req.path = "/foo?b=2";
  3420. req.params.emplace("a", "1");
  3421. target.clear();
  3422. auto res = cli.send(req);
  3423. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3424. EXPECT_EQ("/foo?b=2", target);
  3425. }
  3426. }
  3427. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3428. Server svr;
  3429. svr.Get("/", [](const Request &req, Response &) {
  3430. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3431. });
  3432. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3433. auto se = detail::scope_exit([&] {
  3434. svr.stop();
  3435. thread.join();
  3436. ASSERT_FALSE(svr.is_running());
  3437. });
  3438. svr.wait_until_ready();
  3439. {
  3440. Client cli(HOST, PORT);
  3441. cli.set_path_encode(false);
  3442. auto res = cli.Get("/?something=%0A");
  3443. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3444. EXPECT_EQ(StatusCode::OK_200, res->status);
  3445. }
  3446. }
  3447. TEST(BindServerTest, BindDualStack) {
  3448. Server svr;
  3449. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3450. res.set_content("Hello World!", "text/plain");
  3451. });
  3452. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3453. auto se = detail::scope_exit([&] {
  3454. svr.stop();
  3455. thread.join();
  3456. ASSERT_FALSE(svr.is_running());
  3457. });
  3458. svr.wait_until_ready();
  3459. {
  3460. Client cli("127.0.0.1", PORT);
  3461. auto res = cli.Get("/1");
  3462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3463. EXPECT_EQ(StatusCode::OK_200, res->status);
  3464. EXPECT_EQ("Hello World!", res->body);
  3465. }
  3466. {
  3467. Client cli("::1", PORT);
  3468. auto res = cli.Get("/1");
  3469. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3470. EXPECT_EQ(StatusCode::OK_200, res->status);
  3471. EXPECT_EQ("Hello World!", res->body);
  3472. }
  3473. }
  3474. TEST(BindServerTest, BindAndListenSeparately) {
  3475. Server svr;
  3476. int port = svr.bind_to_any_port("0.0.0.0");
  3477. ASSERT_TRUE(svr.is_valid());
  3478. ASSERT_TRUE(port > 0);
  3479. svr.stop();
  3480. }
  3481. // Reports whether anything is still listening on a loopback port. A plain
  3482. // connect() is used instead of a Client request because a socket left bound by
  3483. // mistake accepts the connection into its backlog and never answers, which
  3484. // would hang the test instead of failing it.
  3485. static bool is_loopback_port_accepting(int port) {
  3486. sockaddr_in addr{};
  3487. addr.sin_family = AF_INET;
  3488. addr.sin_port = htons(static_cast<uint16_t>(port));
  3489. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3490. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3491. EXPECT_NE(sock, INVALID_SOCKET);
  3492. if (sock == INVALID_SOCKET) { return false; }
  3493. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3494. static_cast<socklen_t>(sizeof(addr)));
  3495. detail::close_socket(sock);
  3496. return ret == 0;
  3497. }
  3498. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3499. Server svr;
  3500. auto port = svr.bind_to_any_port("127.0.0.1");
  3501. ASSERT_TRUE(port > 0);
  3502. svr.stop();
  3503. // bind_to_any_port() already called listen(2), so until stop() closed the
  3504. // descriptor the port kept accepting connections into the backlog. ASSERT
  3505. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3506. // below blocks forever in the accept loop.
  3507. ASSERT_FALSE(is_loopback_port_accepting(port));
  3508. // Nothing is left to accept on, so listen_after_bind() must report failure
  3509. // instead of returning success without ever serving.
  3510. EXPECT_FALSE(svr.listen_after_bind());
  3511. // The failed listen marks the server decommissioned, so a waiter returns
  3512. // instead of spinning forever.
  3513. svr.wait_until_ready();
  3514. }
  3515. #ifdef CPPHTTPLIB_SSL_ENABLED
  3516. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3517. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3518. CLIENT_CA_CERT_DIR);
  3519. int port = svr.bind_to_any_port("0.0.0.0");
  3520. ASSERT_TRUE(svr.is_valid());
  3521. ASSERT_TRUE(port > 0);
  3522. svr.stop();
  3523. }
  3524. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  3525. // or a rejected CustomRoute() registration would not stop the server binding.
  3526. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  3527. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3528. CLIENT_CA_CERT_DIR);
  3529. ASSERT_TRUE(svr.is_valid());
  3530. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  3531. EXPECT_FALSE(svr.is_valid());
  3532. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  3533. }
  3534. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  3535. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  3536. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  3537. int port = svr.bind_to_any_port("0.0.0.0");
  3538. ASSERT_TRUE(svr.is_valid());
  3539. ASSERT_TRUE(port > 0);
  3540. svr.stop();
  3541. }
  3542. TEST(BindServerTest, UpdateCertsPem) {
  3543. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3544. int port = svr.bind_to_any_port("0.0.0.0");
  3545. ASSERT_TRUE(svr.is_valid());
  3546. ASSERT_TRUE(port > 0);
  3547. // Read PEM files
  3548. std::string cert_pem, key_pem, ca_pem;
  3549. read_file(SERVER_CERT_FILE, cert_pem);
  3550. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3551. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3552. // Update server certificates using PEM API
  3553. ASSERT_TRUE(
  3554. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3555. ASSERT_TRUE(svr.is_valid());
  3556. svr.stop();
  3557. }
  3558. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  3559. // Start server with client CA (enables client auth)
  3560. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3561. ASSERT_TRUE(svr.is_valid());
  3562. bool handler_called = false;
  3563. svr.Get("/test", [&](const Request &req, Response &res) {
  3564. handler_called = true;
  3565. // Verify client certificate is present
  3566. auto cert = req.peer_cert();
  3567. EXPECT_TRUE(static_cast<bool>(cert));
  3568. res.set_content("ok", "text/plain");
  3569. });
  3570. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3571. auto se = detail::scope_exit([&] {
  3572. svr.stop();
  3573. t.join();
  3574. ASSERT_FALSE(svr.is_running());
  3575. });
  3576. svr.wait_until_ready();
  3577. // Read PEM files
  3578. std::string cert_pem, key_pem, ca_pem;
  3579. read_file(SERVER_CERT_FILE, cert_pem);
  3580. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3581. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3582. // Update server certificates and client CA using PEM API while server running
  3583. ASSERT_TRUE(
  3584. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3585. // Connect with client certificate
  3586. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3587. cli.enable_server_certificate_verification(false);
  3588. cli.set_connection_timeout(30);
  3589. auto res = cli.Get("/test");
  3590. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3591. ASSERT_EQ(StatusCode::OK_200, res->status);
  3592. ASSERT_TRUE(handler_called);
  3593. EXPECT_EQ("ok", res->body);
  3594. }
  3595. #endif
  3596. TEST(ErrorHandlerTest, ContentLength) {
  3597. Server svr;
  3598. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3599. res.status = StatusCode::OK_200;
  3600. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3601. "text/html"); // <= Content-Length still 13
  3602. });
  3603. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3604. res.set_content("Hello World!\n", "text/plain");
  3605. res.status = 524;
  3606. });
  3607. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3608. auto se = detail::scope_exit([&] {
  3609. svr.stop();
  3610. thread.join();
  3611. ASSERT_FALSE(svr.is_running());
  3612. });
  3613. svr.wait_until_ready();
  3614. {
  3615. Client cli(HOST, PORT);
  3616. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3617. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3618. EXPECT_EQ(StatusCode::OK_200, res->status);
  3619. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3620. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3621. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3622. }
  3623. }
  3624. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3625. TEST(ExceptionTest, WithoutExceptionHandler) {
  3626. Server svr;
  3627. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  3628. throw std::runtime_error("exception...");
  3629. });
  3630. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  3631. throw std::runtime_error("exception\r\n...");
  3632. });
  3633. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3634. auto se = detail::scope_exit([&] {
  3635. svr.stop();
  3636. listen_thread.join();
  3637. ASSERT_FALSE(svr.is_running());
  3638. });
  3639. svr.wait_until_ready();
  3640. Client cli("localhost", PORT);
  3641. {
  3642. auto res = cli.Get("/exception");
  3643. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3644. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3645. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3646. }
  3647. {
  3648. auto res = cli.Get("/unknown");
  3649. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3650. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3651. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3652. }
  3653. }
  3654. TEST(ExceptionTest, WithExceptionHandler) {
  3655. Server svr;
  3656. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  3657. std::exception_ptr ep) {
  3658. EXPECT_FALSE(ep == nullptr);
  3659. try {
  3660. std::rethrow_exception(ep);
  3661. } catch (std::exception &e) {
  3662. EXPECT_EQ("abc", std::string(e.what()));
  3663. } catch (...) {}
  3664. res.status = StatusCode::InternalServerError_500;
  3665. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3666. "text/html"); // <= Content-Length still 13 at this point
  3667. });
  3668. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3669. res.set_content("Hello World!\n", "text/plain");
  3670. throw std::runtime_error("abc");
  3671. });
  3672. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3673. auto se = detail::scope_exit([&] {
  3674. svr.stop();
  3675. thread.join();
  3676. ASSERT_FALSE(svr.is_running());
  3677. });
  3678. svr.wait_until_ready();
  3679. for (size_t i = 0; i < 10; i++) {
  3680. Client cli(HOST, PORT);
  3681. for (size_t j = 0; j < 100; j++) {
  3682. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3683. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3684. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3685. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3686. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3687. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3688. }
  3689. cli.set_keep_alive(true);
  3690. for (size_t j = 0; j < 100; j++) {
  3691. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3692. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3693. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3694. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3695. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3696. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3697. }
  3698. }
  3699. }
  3700. TEST(ExceptionTest, AndErrorHandler) {
  3701. Server svr;
  3702. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3703. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  3704. });
  3705. svr.set_exception_handler(
  3706. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  3707. EXPECT_FALSE(ep == nullptr);
  3708. try {
  3709. std::rethrow_exception(ep);
  3710. } catch (std::exception &e) {
  3711. res.set_content(e.what(), "text/html");
  3712. } catch (...) {}
  3713. res.status = StatusCode::InternalServerError_500;
  3714. });
  3715. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  3716. throw std::runtime_error("EXCEPTION");
  3717. });
  3718. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  3719. res.set_content("ERROR", "text/html");
  3720. res.status = StatusCode::InternalServerError_500;
  3721. });
  3722. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3723. auto se = detail::scope_exit([&] {
  3724. svr.stop();
  3725. thread.join();
  3726. ASSERT_FALSE(svr.is_running());
  3727. });
  3728. svr.wait_until_ready();
  3729. Client cli(HOST, PORT);
  3730. {
  3731. auto res = cli.Get("/exception");
  3732. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3733. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3734. EXPECT_EQ("EXCEPTION", res->body);
  3735. }
  3736. {
  3737. auto res = cli.Get("/error");
  3738. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3739. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3740. EXPECT_EQ("ERROR", res->body);
  3741. }
  3742. {
  3743. auto res = cli.Get("/invalid");
  3744. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3745. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3746. EXPECT_EQ("NOT_FOUND", res->body);
  3747. }
  3748. }
  3749. #endif
  3750. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3751. // process_request() wraps only routing() in a try/catch, so an exception from
  3752. // any other user callback used to unwind into the task queue - which does not
  3753. // catch - and terminate the process. Each test below runs the server on a
  3754. // single worker thread: a guard that catches the exception but still loses the
  3755. // thread would otherwise be hidden by a spare worker serving the follow-up
  3756. // request. Note that a regression here aborts the whole test binary rather
  3757. // than failing one test.
  3758. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  3759. Server svr;
  3760. svr.new_task_queue = [] { return new ThreadPool(1); };
  3761. std::atomic<int> reported{0};
  3762. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  3763. if (err == Error::UserCallbackException) { reported++; }
  3764. });
  3765. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  3766. res.set_content_provider(
  3767. 1024, "text/plain",
  3768. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  3769. sink.write("hello", 5);
  3770. throw std::runtime_error("from the content provider");
  3771. });
  3772. });
  3773. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  3774. res.set_content("ok", "text/plain");
  3775. });
  3776. auto port = svr.bind_to_any_port(HOST);
  3777. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3778. auto se = detail::scope_exit([&] {
  3779. svr.stop();
  3780. listen_thread.join();
  3781. ASSERT_FALSE(svr.is_running());
  3782. });
  3783. svr.wait_until_ready();
  3784. {
  3785. Client cli(HOST, port);
  3786. cli.set_read_timeout(5, 0);
  3787. EXPECT_FALSE(cli.Get("/throw"));
  3788. }
  3789. EXPECT_TRUE(svr.is_running());
  3790. EXPECT_EQ(1, reported.load());
  3791. // A request on a fresh connection is still served.
  3792. {
  3793. Client cli(HOST, port);
  3794. auto res = cli.Get("/ok");
  3795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3796. EXPECT_EQ(StatusCode::OK_200, res->status);
  3797. EXPECT_EQ("ok", res->body);
  3798. }
  3799. }
  3800. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  3801. Server svr;
  3802. svr.new_task_queue = [] { return new ThreadPool(1); };
  3803. std::atomic<bool> should_throw{true};
  3804. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3805. res.set_content("hi", "text/plain");
  3806. });
  3807. svr.set_post_routing_handler(
  3808. [&](const Request & /*req*/, Response & /*res*/) {
  3809. if (should_throw) {
  3810. throw std::runtime_error("from the post-routing handler");
  3811. }
  3812. });
  3813. auto port = svr.bind_to_any_port(HOST);
  3814. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3815. auto se = detail::scope_exit([&] {
  3816. svr.stop();
  3817. listen_thread.join();
  3818. ASSERT_FALSE(svr.is_running());
  3819. });
  3820. svr.wait_until_ready();
  3821. {
  3822. Client cli(HOST, port);
  3823. cli.set_read_timeout(5, 0);
  3824. EXPECT_FALSE(cli.Get("/hi"));
  3825. }
  3826. EXPECT_TRUE(svr.is_running());
  3827. should_throw = false;
  3828. {
  3829. Client cli(HOST, port);
  3830. auto res = cli.Get("/hi");
  3831. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3832. EXPECT_EQ(StatusCode::OK_200, res->status);
  3833. EXPECT_EQ("hi", res->body);
  3834. }
  3835. }
  3836. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  3837. // The guard reports the caught exception through the error logger, which is
  3838. // a user callback too. A logger that throws has to be contained as well, or
  3839. // the process would terminate from inside the catch.
  3840. Server svr;
  3841. svr.new_task_queue = [] { return new ThreadPool(1); };
  3842. std::atomic<int> reported{0};
  3843. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  3844. if (err == Error::UserCallbackException) {
  3845. reported++;
  3846. throw std::runtime_error("from the error logger");
  3847. }
  3848. });
  3849. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  3850. res.set_content_provider(
  3851. 1024, "text/plain",
  3852. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  3853. sink.write("hello", 5);
  3854. throw std::runtime_error("from the content provider");
  3855. });
  3856. });
  3857. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  3858. res.set_content("ok", "text/plain");
  3859. });
  3860. auto port = svr.bind_to_any_port(HOST);
  3861. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3862. auto se = detail::scope_exit([&] {
  3863. svr.stop();
  3864. listen_thread.join();
  3865. ASSERT_FALSE(svr.is_running());
  3866. });
  3867. svr.wait_until_ready();
  3868. {
  3869. Client cli(HOST, port);
  3870. cli.set_read_timeout(5, 0);
  3871. EXPECT_FALSE(cli.Get("/throw"));
  3872. }
  3873. EXPECT_TRUE(svr.is_running());
  3874. EXPECT_EQ(1, reported.load());
  3875. {
  3876. Client cli(HOST, port);
  3877. auto res = cli.Get("/ok");
  3878. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3879. EXPECT_EQ(StatusCode::OK_200, res->status);
  3880. EXPECT_EQ("ok", res->body);
  3881. }
  3882. }
  3883. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  3884. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  3885. // so the exception unwinds through the ws::WebSocket object on its way to
  3886. // the guard. None of the HTTP cases above cross that.
  3887. Server svr;
  3888. svr.new_task_queue = [] { return new ThreadPool(1); };
  3889. std::atomic<int> reported{0};
  3890. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  3891. if (err == Error::UserCallbackException) { reported++; }
  3892. });
  3893. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  3894. throw std::runtime_error("from the WebSocket handler");
  3895. });
  3896. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  3897. res.set_content("ok", "text/plain");
  3898. });
  3899. auto port = svr.bind_to_any_port(HOST);
  3900. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3901. auto se = detail::scope_exit([&] {
  3902. svr.stop();
  3903. listen_thread.join();
  3904. ASSERT_FALSE(svr.is_running());
  3905. });
  3906. svr.wait_until_ready();
  3907. {
  3908. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  3909. "/ws");
  3910. auto res = client.connect();
  3911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3912. // The server dropped the connection instead of dying.
  3913. std::string msg;
  3914. EXPECT_FALSE(client.read(msg));
  3915. client.close();
  3916. }
  3917. EXPECT_TRUE(svr.is_running());
  3918. EXPECT_EQ(1, reported.load());
  3919. {
  3920. Client cli(HOST, port);
  3921. auto res = cli.Get("/ok");
  3922. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3923. EXPECT_EQ(StatusCode::OK_200, res->status);
  3924. EXPECT_EQ("ok", res->body);
  3925. }
  3926. }
  3927. #ifdef CPPHTTPLIB_SSL_ENABLED
  3928. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  3929. // SSLServer::process_and_close_socket() is a separate overload with its own
  3930. // guard, so it is exercised on its own.
  3931. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  3932. ASSERT_TRUE(svr.is_valid());
  3933. svr.new_task_queue = [] { return new ThreadPool(1); };
  3934. std::atomic<int> reported{0};
  3935. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  3936. if (err == Error::UserCallbackException) { reported++; }
  3937. });
  3938. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  3939. res.set_content_provider(
  3940. 1024, "text/plain",
  3941. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  3942. sink.write("hello", 5);
  3943. throw std::runtime_error("from the content provider");
  3944. });
  3945. });
  3946. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  3947. res.set_content("ok", "text/plain");
  3948. });
  3949. auto port = svr.bind_to_any_port(HOST);
  3950. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3951. auto se = detail::scope_exit([&] {
  3952. svr.stop();
  3953. listen_thread.join();
  3954. ASSERT_FALSE(svr.is_running());
  3955. });
  3956. svr.wait_until_ready();
  3957. {
  3958. SSLClient cli(HOST, port);
  3959. cli.enable_server_certificate_verification(false);
  3960. cli.set_read_timeout(5, 0);
  3961. EXPECT_FALSE(cli.Get("/throw"));
  3962. }
  3963. EXPECT_TRUE(svr.is_running());
  3964. EXPECT_EQ(1, reported.load());
  3965. {
  3966. SSLClient cli(HOST, port);
  3967. cli.enable_server_certificate_verification(false);
  3968. auto res = cli.Get("/ok");
  3969. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3970. EXPECT_EQ(StatusCode::OK_200, res->status);
  3971. EXPECT_EQ("ok", res->body);
  3972. }
  3973. }
  3974. #endif
  3975. #endif
  3976. TEST(NoContentTest, ContentLength) {
  3977. Server svr;
  3978. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3979. res.status = StatusCode::NoContent_204;
  3980. });
  3981. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3982. auto se = detail::scope_exit([&] {
  3983. svr.stop();
  3984. thread.join();
  3985. ASSERT_FALSE(svr.is_running());
  3986. });
  3987. svr.wait_until_ready();
  3988. {
  3989. Client cli(HOST, PORT);
  3990. auto res = cli.Get("/hi");
  3991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3992. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  3993. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3994. }
  3995. }
  3996. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  3997. #ifdef CPPHTTPLIB_SSL_ENABLED
  3998. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  3999. ASSERT_TRUE(svr.is_valid());
  4000. #else
  4001. Server svr;
  4002. #endif
  4003. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  4004. if (req.path == "/routing_handler") {
  4005. res.set_header("PRE_ROUTING", "on");
  4006. res.set_content("Routing Handler", "text/plain");
  4007. return httplib::Server::HandlerResponse::Handled;
  4008. }
  4009. return httplib::Server::HandlerResponse::Unhandled;
  4010. });
  4011. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4012. res.set_content("Error", "text/html");
  4013. });
  4014. svr.set_post_routing_handler([](const Request &req, Response &res) {
  4015. if (req.path == "/routing_handler") {
  4016. res.set_header("POST_ROUTING", "on");
  4017. }
  4018. });
  4019. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4020. res.set_content("Hello World!\n", "text/plain");
  4021. });
  4022. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4023. auto se = detail::scope_exit([&] {
  4024. svr.stop();
  4025. thread.join();
  4026. ASSERT_FALSE(svr.is_running());
  4027. });
  4028. svr.wait_until_ready();
  4029. {
  4030. #ifdef CPPHTTPLIB_SSL_ENABLED
  4031. SSLClient cli(HOST, PORT);
  4032. cli.enable_server_certificate_verification(false);
  4033. #else
  4034. Client cli(HOST, PORT);
  4035. #endif
  4036. auto res = cli.Get("/routing_handler");
  4037. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4038. EXPECT_EQ(StatusCode::OK_200, res->status);
  4039. EXPECT_EQ("Routing Handler", res->body);
  4040. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  4041. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  4042. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  4043. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  4044. }
  4045. {
  4046. #ifdef CPPHTTPLIB_SSL_ENABLED
  4047. SSLClient cli(HOST, PORT);
  4048. cli.enable_server_certificate_verification(false);
  4049. #else
  4050. Client cli(HOST, PORT);
  4051. #endif
  4052. auto res = cli.Get("/hi");
  4053. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4054. EXPECT_EQ(StatusCode::OK_200, res->status);
  4055. EXPECT_EQ("Hello World!\n", res->body);
  4056. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4057. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4058. }
  4059. {
  4060. #ifdef CPPHTTPLIB_SSL_ENABLED
  4061. SSLClient cli(HOST, PORT);
  4062. cli.enable_server_certificate_verification(false);
  4063. #else
  4064. Client cli(HOST, PORT);
  4065. #endif
  4066. auto res = cli.Get("/aaa");
  4067. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4068. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4069. EXPECT_EQ("Error", res->body);
  4070. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4071. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4072. }
  4073. }
  4074. TEST(RequestHandlerTest, PreRequestHandler) {
  4075. auto route_path = "/user/:user";
  4076. Server svr;
  4077. svr.Get("/hi", [](const Request &, Response &res) {
  4078. res.set_content("hi", "text/plain");
  4079. });
  4080. svr.Get(route_path, [](const Request &req, Response &res) {
  4081. res.set_content(req.path_params.at("user"), "text/plain");
  4082. });
  4083. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  4084. if (req.matched_route == route_path) {
  4085. auto user = req.path_params.at("user");
  4086. if (user != "john") {
  4087. res.status = StatusCode::Forbidden_403;
  4088. res.set_content("error", "text/html");
  4089. return Server::HandlerResponse::Handled;
  4090. }
  4091. }
  4092. return Server::HandlerResponse::Unhandled;
  4093. });
  4094. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4095. auto se = detail::scope_exit([&] {
  4096. svr.stop();
  4097. thread.join();
  4098. ASSERT_FALSE(svr.is_running());
  4099. });
  4100. svr.wait_until_ready();
  4101. Client cli(HOST, PORT);
  4102. {
  4103. auto res = cli.Get("/hi");
  4104. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4105. EXPECT_EQ(StatusCode::OK_200, res->status);
  4106. EXPECT_EQ("hi", res->body);
  4107. }
  4108. {
  4109. auto res = cli.Get("/user/john");
  4110. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4111. EXPECT_EQ(StatusCode::OK_200, res->status);
  4112. EXPECT_EQ("john", res->body);
  4113. }
  4114. {
  4115. auto res = cli.Get("/user/invalid-user");
  4116. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4117. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4118. EXPECT_EQ("error", res->body);
  4119. }
  4120. }
  4121. // The pre-request handler must run before the request body is read, so a
  4122. // rejected request never forces the server to buffer a (potentially large)
  4123. // body. Here the posted body is larger than the payload limit: if the body
  4124. // were read first the server would answer 413, but because the pre-request
  4125. // handler runs first it answers 403 and the body is never read.
  4126. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  4127. Server svr;
  4128. svr.set_payload_max_length(8);
  4129. auto handler_ran = false;
  4130. svr.Post("/reject", [&](const Request &req, Response &res) {
  4131. handler_ran = true;
  4132. res.set_content(req.body, "text/plain");
  4133. });
  4134. svr.Post("/accept", [](const Request &req, Response &res) {
  4135. res.set_content(req.body, "text/plain");
  4136. });
  4137. svr.set_pre_request_handler([](const Request &req, Response &res) {
  4138. if (req.matched_route == "/reject") {
  4139. res.status = StatusCode::Forbidden_403;
  4140. res.set_content("denied", "text/plain");
  4141. return Server::HandlerResponse::Handled;
  4142. }
  4143. return Server::HandlerResponse::Unhandled;
  4144. });
  4145. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4146. auto se = detail::scope_exit([&] {
  4147. svr.stop();
  4148. thread.join();
  4149. ASSERT_FALSE(svr.is_running());
  4150. });
  4151. svr.wait_until_ready();
  4152. Client cli(HOST, PORT);
  4153. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  4154. // rejects with 403 before the body is read, so 413 is never reached.
  4155. {
  4156. auto res = cli.Post("/reject", "0123456789", "text/plain");
  4157. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4158. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4159. EXPECT_EQ("denied", res->body);
  4160. EXPECT_FALSE(handler_ran);
  4161. }
  4162. // An approved route still reads the body and enforces the payload limit.
  4163. {
  4164. auto res = cli.Post("/accept", "0123456789", "text/plain");
  4165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4166. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  4167. }
  4168. }
  4169. TEST(UserDataTest, BasicOperations) {
  4170. httplib::UserData ud;
  4171. // Initially empty
  4172. EXPECT_FALSE(ud.has("key"));
  4173. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4174. // set and get
  4175. ud.set("key", 42);
  4176. EXPECT_TRUE(ud.has("key"));
  4177. auto *p = ud.get<int>("key");
  4178. ASSERT_NE(nullptr, p);
  4179. EXPECT_EQ(42, *p);
  4180. // Type mismatch → nullptr
  4181. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  4182. // Overwrite with different type
  4183. ud.set("key", std::string("hello"));
  4184. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4185. auto *s = ud.get<std::string>("key");
  4186. ASSERT_NE(nullptr, s);
  4187. EXPECT_EQ("hello", *s);
  4188. // erase
  4189. ud.erase("key");
  4190. EXPECT_FALSE(ud.has("key"));
  4191. // clear
  4192. ud.set("a", 1);
  4193. ud.set("b", 2);
  4194. ud.clear();
  4195. EXPECT_FALSE(ud.has("a"));
  4196. EXPECT_FALSE(ud.has("b"));
  4197. }
  4198. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  4199. struct AuthCtx {
  4200. std::string user_id;
  4201. };
  4202. Server svr;
  4203. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  4204. res.user_data.set("auth", AuthCtx{"alice"});
  4205. return Server::HandlerResponse::Unhandled;
  4206. });
  4207. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  4208. auto *ctx = res.user_data.get<AuthCtx>("auth");
  4209. ASSERT_NE(nullptr, ctx);
  4210. res.set_content("Hello " + ctx->user_id, "text/plain");
  4211. });
  4212. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4213. auto se = detail::scope_exit([&] {
  4214. svr.stop();
  4215. thread.join();
  4216. ASSERT_FALSE(svr.is_running());
  4217. });
  4218. svr.wait_until_ready();
  4219. Client cli(HOST, PORT);
  4220. auto res = cli.Get("/me");
  4221. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4222. EXPECT_EQ(StatusCode::OK_200, res->status);
  4223. EXPECT_EQ("Hello alice", res->body);
  4224. }
  4225. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  4226. struct RoleCtx {
  4227. std::string role;
  4228. };
  4229. Server svr;
  4230. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  4231. res.user_data.set("role", RoleCtx{"admin"});
  4232. return Server::HandlerResponse::Unhandled;
  4233. });
  4234. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  4235. auto *ctx = res.user_data.get<RoleCtx>("role");
  4236. ASSERT_NE(nullptr, ctx);
  4237. res.set_content(ctx->role, "text/plain");
  4238. });
  4239. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4240. auto se = detail::scope_exit([&] {
  4241. svr.stop();
  4242. thread.join();
  4243. ASSERT_FALSE(svr.is_running());
  4244. });
  4245. svr.wait_until_ready();
  4246. Client cli(HOST, PORT);
  4247. auto res = cli.Get("/role");
  4248. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4249. EXPECT_EQ(StatusCode::OK_200, res->status);
  4250. EXPECT_EQ("admin", res->body);
  4251. }
  4252. TEST(InvalidFormatTest, StatusCode) {
  4253. Server svr;
  4254. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4255. res.set_content("Hello World!\n", "text/plain");
  4256. res.status = 9999; // Status should be a three-digit code...
  4257. });
  4258. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4259. auto se = detail::scope_exit([&] {
  4260. svr.stop();
  4261. thread.join();
  4262. ASSERT_FALSE(svr.is_running());
  4263. });
  4264. svr.wait_until_ready();
  4265. {
  4266. Client cli(HOST, PORT);
  4267. auto res = cli.Get("/hi");
  4268. ASSERT_FALSE(res);
  4269. }
  4270. }
  4271. TEST(URLFragmentTest, WithFragment) {
  4272. Server svr;
  4273. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  4274. EXPECT_TRUE(req.target == "/hi");
  4275. });
  4276. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4277. auto se = detail::scope_exit([&] {
  4278. svr.stop();
  4279. thread.join();
  4280. ASSERT_FALSE(svr.is_running());
  4281. });
  4282. svr.wait_until_ready();
  4283. {
  4284. Client cli(HOST, PORT);
  4285. auto res = cli.Get("/hi#key1=val1=key2=val2");
  4286. EXPECT_TRUE(res);
  4287. EXPECT_EQ(StatusCode::OK_200, res->status);
  4288. res = cli.Get("/hi%23key1=val1=key2=val2");
  4289. EXPECT_TRUE(res);
  4290. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4291. }
  4292. }
  4293. TEST(HeaderWriter, SetHeaderWriter) {
  4294. Server svr;
  4295. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  4296. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  4297. return detail::write_headers(strm, hdrs);
  4298. });
  4299. svr.Get("/hi", [](const Request &req, Response &res) {
  4300. auto it = req.headers.find("CustomClientHeader");
  4301. EXPECT_TRUE(it != req.headers.end());
  4302. EXPECT_EQ(it->second, "CustomClientValue");
  4303. res.set_content("Hello World!\n", "text/plain");
  4304. });
  4305. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4306. auto se = detail::scope_exit([&] {
  4307. svr.stop();
  4308. thread.join();
  4309. ASSERT_FALSE(svr.is_running());
  4310. });
  4311. svr.wait_until_ready();
  4312. {
  4313. Client cli(HOST, PORT);
  4314. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  4315. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  4316. return detail::write_headers(strm, hdrs);
  4317. });
  4318. auto res = cli.Get("/hi");
  4319. EXPECT_TRUE(res);
  4320. EXPECT_EQ(StatusCode::OK_200, res->status);
  4321. auto it = res->headers.find("CustomServerHeader");
  4322. EXPECT_TRUE(it != res->headers.end());
  4323. EXPECT_EQ(it->second, "CustomServerValue");
  4324. }
  4325. }
  4326. class ServerTest : public ::testing::Test {
  4327. protected:
  4328. ServerTest()
  4329. : cli_(HOST, PORT)
  4330. #ifdef CPPHTTPLIB_SSL_ENABLED
  4331. ,
  4332. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  4333. #endif
  4334. {
  4335. #ifdef CPPHTTPLIB_SSL_ENABLED
  4336. cli_.enable_server_certificate_verification(false);
  4337. #endif
  4338. // Allow LARGE_DATA (100MB) responses
  4339. cli_.set_payload_max_length(200 * 1024 * 1024);
  4340. }
  4341. virtual void SetUp() {
  4342. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  4343. svr_.set_payload_max_length(200 * 1024 * 1024);
  4344. svr_.set_mount_point("/", "./www");
  4345. svr_.set_mount_point("/mount", "./www2");
  4346. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  4347. svr_.Get("/hi",
  4348. [&](const Request & /*req*/, Response &res) {
  4349. res.set_content("Hello World!", "text/plain");
  4350. })
  4351. .Get("/file_content",
  4352. [&](const Request & /*req*/, Response &res) {
  4353. res.set_file_content("./www/dir/test.html");
  4354. })
  4355. .Get("/file_content_with_content_type",
  4356. [&](const Request & /*req*/, Response &res) {
  4357. res.set_file_content("./www/file", "text/plain");
  4358. })
  4359. .Get("/invalid_file_content",
  4360. [&](const Request & /*req*/, Response &res) {
  4361. res.set_file_content("./www/dir/invalid_file_path");
  4362. })
  4363. .Get("/http_response_splitting",
  4364. [&](const Request & /*req*/, Response &res) {
  4365. res.set_header("a", "1\r\nSet-Cookie: a=1");
  4366. EXPECT_EQ(0U, res.headers.size());
  4367. EXPECT_FALSE(res.has_header("a"));
  4368. res.set_header("a", "1\nSet-Cookie: a=1");
  4369. EXPECT_EQ(0U, res.headers.size());
  4370. EXPECT_FALSE(res.has_header("a"));
  4371. res.set_header("a", "1\rSet-Cookie: a=1");
  4372. EXPECT_EQ(0U, res.headers.size());
  4373. EXPECT_FALSE(res.has_header("a"));
  4374. res.set_header("a\r\nb", "0");
  4375. EXPECT_EQ(0U, res.headers.size());
  4376. EXPECT_FALSE(res.has_header("a"));
  4377. res.set_header("a\rb", "0");
  4378. EXPECT_EQ(0U, res.headers.size());
  4379. EXPECT_FALSE(res.has_header("a"));
  4380. res.set_header("a\nb", "0");
  4381. EXPECT_EQ(0U, res.headers.size());
  4382. EXPECT_FALSE(res.has_header("a"));
  4383. res.set_redirect("1\r\nSet-Cookie: a=1");
  4384. EXPECT_EQ(0U, res.headers.size());
  4385. EXPECT_FALSE(res.has_header("Location"));
  4386. })
  4387. .Get("/slow",
  4388. [&](const Request & /*req*/, Response &res) {
  4389. std::this_thread::sleep_for(std::chrono::seconds(4));
  4390. res.set_content("slow", "text/plain");
  4391. })
  4392. #if 0
  4393. .Post("/slowpost",
  4394. [&](const Request & /*req*/, Response &res) {
  4395. std::this_thread::sleep_for(std::chrono::seconds(2));
  4396. res.set_content("slow", "text/plain");
  4397. })
  4398. #endif
  4399. .Get("/remote_addr",
  4400. [&](const Request &req, Response &res) {
  4401. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  4402. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  4403. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4404. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  4405. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  4406. #endif
  4407. res.set_content(req.remote_addr, "text/plain");
  4408. })
  4409. .Get("/local_addr",
  4410. [&](const Request &req, Response &res) {
  4411. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  4412. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  4413. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4414. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  4415. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  4416. #endif
  4417. auto local_addr = req.local_addr;
  4418. auto local_port = std::to_string(req.local_port);
  4419. res.set_content(local_addr.append(":").append(local_port),
  4420. "text/plain");
  4421. })
  4422. .Get("/endwith%",
  4423. [&](const Request & /*req*/, Response &res) {
  4424. res.set_content("Hello World!", "text/plain");
  4425. })
  4426. .Get("/a\\+\\+b",
  4427. [&](const Request &req, Response &res) {
  4428. ASSERT_TRUE(req.has_param("a +b"));
  4429. auto val = req.get_param_value("a +b");
  4430. res.set_content(val, "text/plain");
  4431. })
  4432. .Get("/", [&](const Request & /*req*/,
  4433. Response &res) { res.set_redirect("/hi"); })
  4434. .Post("/1",
  4435. [](const Request & /*req*/, Response &res) {
  4436. res.set_redirect("/2", StatusCode::SeeOther_303);
  4437. })
  4438. .Get("/2",
  4439. [](const Request & /*req*/, Response &res) {
  4440. res.set_content("redirected.", "text/plain");
  4441. res.status = StatusCode::OK_200;
  4442. })
  4443. .Post("/person",
  4444. [&](const Request &req, Response &res) {
  4445. if (req.has_param("name") && req.has_param("note")) {
  4446. persons_[req.get_param_value("name")] =
  4447. req.get_param_value("note");
  4448. } else {
  4449. res.status = StatusCode::BadRequest_400;
  4450. }
  4451. })
  4452. .Put("/person",
  4453. [&](const Request &req, Response &res) {
  4454. if (req.has_param("name") && req.has_param("note")) {
  4455. persons_[req.get_param_value("name")] =
  4456. req.get_param_value("note");
  4457. } else {
  4458. res.status = StatusCode::BadRequest_400;
  4459. }
  4460. })
  4461. .Get("/person/(.*)",
  4462. [&](const Request &req, Response &res) {
  4463. string name = req.matches[1];
  4464. if (persons_.find(name) != persons_.end()) {
  4465. auto note = persons_[name];
  4466. res.set_content(note, "text/plain");
  4467. } else {
  4468. res.status = StatusCode::NotFound_404;
  4469. }
  4470. })
  4471. .Delete("/person",
  4472. [&](const Request &req, Response &res) {
  4473. if (req.has_param("name")) {
  4474. string name = req.get_param_value("name");
  4475. if (persons_.find(name) != persons_.end()) {
  4476. persons_.erase(name);
  4477. res.set_content("DELETED", "text/plain");
  4478. } else {
  4479. res.status = StatusCode::NotFound_404;
  4480. }
  4481. } else {
  4482. res.status = StatusCode::BadRequest_400;
  4483. }
  4484. })
  4485. .Post("/x-www-form-urlencoded-json",
  4486. [&](const Request &req, Response &res) {
  4487. auto json = req.get_param_value("json");
  4488. ASSERT_EQ(JSON_DATA, json);
  4489. res.set_content(json, "appliation/json");
  4490. res.status = StatusCode::OK_200;
  4491. })
  4492. .Get("/streamed-chunked",
  4493. [&](const Request & /*req*/, Response &res) {
  4494. res.set_chunked_content_provider(
  4495. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  4496. sink.os << "123";
  4497. sink.os << "456";
  4498. sink.os << "789";
  4499. sink.done();
  4500. return true;
  4501. });
  4502. })
  4503. .Get("/streamed-chunked-with-prohibited-trailer",
  4504. [&](const Request & /*req*/, Response &res) {
  4505. auto i = new int(0);
  4506. // Declare both a prohibited trailer (Content-Length) and an
  4507. // allowed one
  4508. res.set_header("Trailer", "Content-Length, X-Allowed");
  4509. res.set_chunked_content_provider(
  4510. "text/plain",
  4511. [i](size_t /*offset*/, DataSink &sink) {
  4512. switch (*i) {
  4513. case 0: sink.os << "123"; break;
  4514. case 1: sink.os << "456"; break;
  4515. case 2: sink.os << "789"; break;
  4516. case 3: {
  4517. sink.done_with_trailer(
  4518. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  4519. } break;
  4520. }
  4521. (*i)++;
  4522. return true;
  4523. },
  4524. [i](bool success) {
  4525. EXPECT_TRUE(success);
  4526. delete i;
  4527. });
  4528. })
  4529. .Get("/streamed-chunked2",
  4530. [&](const Request & /*req*/, Response &res) {
  4531. auto i = new int(0);
  4532. res.set_chunked_content_provider(
  4533. "text/plain",
  4534. [i](size_t /*offset*/, DataSink &sink) {
  4535. switch (*i) {
  4536. case 0: sink.os << "123"; break;
  4537. case 1: sink.os << "456"; break;
  4538. case 2: sink.os << "789"; break;
  4539. case 3: sink.done(); break;
  4540. }
  4541. (*i)++;
  4542. return true;
  4543. },
  4544. [i](bool success) {
  4545. EXPECT_TRUE(success);
  4546. delete i;
  4547. });
  4548. })
  4549. .Get("/streamed-chunked-with-trailer",
  4550. [&](const Request & /*req*/, Response &res) {
  4551. auto i = new int(0);
  4552. res.set_header("Trailer", "Dummy1, Dummy2");
  4553. res.set_chunked_content_provider(
  4554. "text/plain",
  4555. [i](size_t /*offset*/, DataSink &sink) {
  4556. switch (*i) {
  4557. case 0: sink.os << "123"; break;
  4558. case 1: sink.os << "456"; break;
  4559. case 2: sink.os << "789"; break;
  4560. case 3: {
  4561. sink.done_with_trailer(
  4562. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  4563. } break;
  4564. }
  4565. (*i)++;
  4566. return true;
  4567. },
  4568. [i](bool success) {
  4569. EXPECT_TRUE(success);
  4570. delete i;
  4571. });
  4572. })
  4573. .Get("/streamed",
  4574. [&](const Request & /*req*/, Response &res) {
  4575. res.set_content_provider(
  4576. 6, "text/plain",
  4577. [](size_t offset, size_t /*length*/, DataSink &sink) {
  4578. sink.os << (offset < 3 ? "a" : "b");
  4579. return true;
  4580. });
  4581. })
  4582. .Get("/streamed-without-length",
  4583. [&](const Request & /*req*/, Response &res) {
  4584. auto data = new std::string("abcdefg");
  4585. res.set_content_provider(
  4586. "text/plain",
  4587. [data](size_t offset, DataSink &sink) {
  4588. if (offset < data->size()) {
  4589. sink.os << data->substr(offset);
  4590. }
  4591. sink.done();
  4592. return true;
  4593. },
  4594. [data](bool success) {
  4595. EXPECT_TRUE(success);
  4596. delete data;
  4597. });
  4598. })
  4599. .Get("/streamed-with-range",
  4600. [&](const Request &req, Response &res) {
  4601. auto data = new std::string("abcdefg");
  4602. // An explicit status keeps the server from picking the 206 it
  4603. // would otherwise choose for a ranged request, so the response
  4604. // is not a partial representation.
  4605. auto status = req.get_param_value("status");
  4606. if (status == "200") {
  4607. res.status = StatusCode::OK_200;
  4608. } else if (status == "403") {
  4609. res.status = StatusCode::Forbidden_403;
  4610. }
  4611. res.set_content_provider(
  4612. data->size(), "text/plain",
  4613. [data](size_t offset, size_t length, DataSink &sink) {
  4614. size_t DATA_CHUNK_SIZE = 4;
  4615. const auto &d = *data;
  4616. auto out_len =
  4617. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  4618. auto ret =
  4619. sink.write(&d[static_cast<size_t>(offset)], out_len);
  4620. EXPECT_TRUE(ret);
  4621. return true;
  4622. },
  4623. [data, &req](bool success) {
  4624. EXPECT_EQ(success, !req.has_param("error"));
  4625. delete data;
  4626. });
  4627. })
  4628. .Get("/streamed-cancel",
  4629. [&](const Request & /*req*/, Response &res) {
  4630. res.set_content_provider(
  4631. size_t(-1), "text/plain",
  4632. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4633. sink.os << "data_chunk";
  4634. return true;
  4635. });
  4636. })
  4637. .Get("/regex-with-delimiter",
  4638. [&](const Request &req, Response & /*res*/) {
  4639. ASSERT_TRUE(req.has_param("key"));
  4640. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  4641. })
  4642. .Get("/with-range",
  4643. [&](const Request & /*req*/, Response &res) {
  4644. res.set_content("abcdefg", "text/plain");
  4645. })
  4646. .Get("/test-start-time",
  4647. [&](const Request &req, Response & /*res*/) {
  4648. EXPECT_NE(req.start_time_,
  4649. std::chrono::steady_clock::time_point::min());
  4650. })
  4651. .Get("/with-range-customized-response",
  4652. [&](const Request & /*req*/, Response &res) {
  4653. res.status = StatusCode::BadRequest_400;
  4654. res.set_content(JSON_DATA, "application/json");
  4655. })
  4656. .Post("/chunked",
  4657. [&](const Request &req, Response & /*res*/) {
  4658. EXPECT_EQ(req.body, "dechunked post body");
  4659. })
  4660. .Post("/large-chunked",
  4661. [&](const Request &req, Response & /*res*/) {
  4662. std::string expected(6 * 30 * 1024u, 'a');
  4663. EXPECT_EQ(req.body, expected);
  4664. })
  4665. .Post("/multipart",
  4666. [&](const Request &req, Response & /*res*/) {
  4667. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  4668. req.form.get_field_count("text2") +
  4669. req.form.get_field_count("file3") +
  4670. req.form.get_field_count("file4"));
  4671. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  4672. req.form.get_file_count("file2"));
  4673. ASSERT_TRUE(!req.form.has_file("???"));
  4674. ASSERT_TRUE(!req.form.has_field("???"));
  4675. ASSERT_TRUE(req.body.empty());
  4676. {
  4677. const auto &text = req.form.get_field("text1");
  4678. EXPECT_EQ("text default", text);
  4679. }
  4680. {
  4681. const auto &text = req.form.get_field("text2");
  4682. EXPECT_EQ("aωb", text);
  4683. }
  4684. {
  4685. const auto &file = req.form.get_file("file1");
  4686. EXPECT_EQ("hello.txt", file.filename);
  4687. EXPECT_EQ("text/plain", file.content_type);
  4688. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  4689. }
  4690. {
  4691. const auto &file = req.form.get_file("file2");
  4692. EXPECT_EQ("world.json", file.filename);
  4693. EXPECT_EQ("application/json", file.content_type);
  4694. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  4695. }
  4696. {
  4697. const auto &text = req.form.get_field("file3");
  4698. EXPECT_EQ(0u, text.size());
  4699. }
  4700. {
  4701. const auto &text = req.form.get_field("file4");
  4702. EXPECT_EQ(0u, text.size());
  4703. }
  4704. })
  4705. .Post("/multipart/multi_file_values",
  4706. [&](const Request &req, Response & /*res*/) {
  4707. EXPECT_EQ(3u, req.form.get_field_count("text") +
  4708. req.form.get_field_count("multi_text1"));
  4709. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  4710. ASSERT_TRUE(!req.form.has_file("???"));
  4711. ASSERT_TRUE(!req.form.has_field("???"));
  4712. ASSERT_TRUE(req.body.empty());
  4713. {
  4714. const auto &text = req.form.get_field("text");
  4715. EXPECT_EQ("default text", text);
  4716. }
  4717. {
  4718. const auto &text1_values = req.form.get_fields("multi_text1");
  4719. EXPECT_EQ(2u, text1_values.size());
  4720. EXPECT_EQ("aaaaa", text1_values[0]);
  4721. EXPECT_EQ("bbbbb", text1_values[1]);
  4722. }
  4723. {
  4724. const auto &file1_values = req.form.get_files("multi_file1");
  4725. EXPECT_EQ(2u, file1_values.size());
  4726. auto file1 = file1_values[0];
  4727. EXPECT_EQ(file1.filename, "hello.txt");
  4728. EXPECT_EQ(file1.content_type, "text/plain");
  4729. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  4730. auto file2 = file1_values[1];
  4731. EXPECT_EQ(file2.filename, "world.json");
  4732. EXPECT_EQ(file2.content_type, "application/json");
  4733. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  4734. }
  4735. })
  4736. .Post("/empty",
  4737. [&](const Request &req, Response &res) {
  4738. EXPECT_EQ(req.body, "");
  4739. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  4740. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4741. res.set_content("empty", "text/plain");
  4742. })
  4743. .Post("/empty-no-content-type",
  4744. [&](const Request &req, Response &res) {
  4745. EXPECT_EQ(req.body, "");
  4746. EXPECT_FALSE(req.has_header("Content-Type"));
  4747. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4748. res.set_content("empty-no-content-type", "text/plain");
  4749. })
  4750. .Post("/path-only",
  4751. [&](const Request &req, Response &res) {
  4752. EXPECT_EQ(req.body, "");
  4753. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4754. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4755. res.set_content("path-only", "text/plain");
  4756. })
  4757. .Post("/path-headers-only",
  4758. [&](const Request &req, Response &res) {
  4759. EXPECT_EQ(req.body, "");
  4760. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4761. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4762. EXPECT_EQ("world", req.get_header_value("hello"));
  4763. EXPECT_EQ("world2", req.get_header_value("hello2"));
  4764. res.set_content("path-headers-only", "text/plain");
  4765. })
  4766. .Post("/post-large",
  4767. [&](const Request &req, Response &res) {
  4768. EXPECT_EQ(req.body, LARGE_DATA);
  4769. res.set_content(req.body, "text/plain");
  4770. })
  4771. .Post("/post-loopback",
  4772. [&](const Request &, Response &res,
  4773. ContentReader const &content_reader) {
  4774. std::string body;
  4775. content_reader([&](const char *data, size_t data_length) {
  4776. body.append(data, data_length);
  4777. return true;
  4778. });
  4779. res.set_content(body, "text/plain");
  4780. })
  4781. .Put("/put-loopback",
  4782. [&](const Request &, Response &res,
  4783. ContentReader const &content_reader) {
  4784. std::string body;
  4785. content_reader([&](const char *data, size_t data_length) {
  4786. body.append(data, data_length);
  4787. return true;
  4788. });
  4789. res.set_content(body, "text/plain");
  4790. })
  4791. .Patch("/patch-loopback",
  4792. [&](const Request &, Response &res,
  4793. ContentReader const &content_reader) {
  4794. std::string body;
  4795. content_reader([&](const char *data, size_t data_length) {
  4796. body.append(data, data_length);
  4797. return true;
  4798. });
  4799. res.set_content(body, "text/plain");
  4800. })
  4801. .Put("/empty-no-content-type",
  4802. [&](const Request &req, Response &res) {
  4803. EXPECT_EQ(req.body, "");
  4804. EXPECT_FALSE(req.has_header("Content-Type"));
  4805. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4806. res.set_content("empty-no-content-type", "text/plain");
  4807. })
  4808. .Put("/put",
  4809. [&](const Request &req, Response &res) {
  4810. EXPECT_EQ(req.body, "PUT");
  4811. res.set_content(req.body, "text/plain");
  4812. })
  4813. .Put("/put-large",
  4814. [&](const Request &req, Response &res) {
  4815. EXPECT_EQ(req.body, LARGE_DATA);
  4816. res.set_content(req.body, "text/plain");
  4817. })
  4818. .Patch("/patch",
  4819. [&](const Request &req, Response &res) {
  4820. EXPECT_EQ(req.body, "PATCH");
  4821. res.set_content(req.body, "text/plain");
  4822. })
  4823. .Delete("/delete",
  4824. [&](const Request & /*req*/, Response &res) {
  4825. res.set_content("DELETE", "text/plain");
  4826. })
  4827. .Delete("/delete-body",
  4828. [&](const Request &req, Response &res) {
  4829. EXPECT_EQ(req.body, "content");
  4830. res.set_content(req.body, "text/plain");
  4831. })
  4832. .Options(R"(\*)",
  4833. [&](const Request & /*req*/, Response &res) {
  4834. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  4835. })
  4836. .CustomRoute("PROPFIND", "/dav/:id",
  4837. [&](const Request &req, Response &res) {
  4838. res.set_header("x-body-size",
  4839. std::to_string(req.body.size()));
  4840. res.set_header("x-matched-route", req.matched_route);
  4841. res.set_header("x-dav-id", req.path_params.at("id"));
  4842. res.status = StatusCode::MultiStatus_207;
  4843. res.set_content(req.body, "application/xml");
  4844. })
  4845. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  4846. [&](const Request &req, Response &res) {
  4847. res.set_header("x-dav-match", req.matches[1]);
  4848. res.status = StatusCode::MultiStatus_207;
  4849. })
  4850. .CustomRoute("MKCOL", "/dav-mkcol",
  4851. [&](const Request &req, Response &res) {
  4852. EXPECT_TRUE(req.body.empty());
  4853. res.status = StatusCode::Created_201;
  4854. })
  4855. .CustomRoute(
  4856. "REPORT", "/dav-report",
  4857. [&](const Request & /*req*/, Response &res,
  4858. const ContentReader &content_reader) {
  4859. std::string body;
  4860. content_reader([&](const char *data, size_t data_length) {
  4861. body.append(data, data_length);
  4862. return true;
  4863. });
  4864. res.set_header("x-body-size", std::to_string(body.size()));
  4865. res.status = StatusCode::MultiStatus_207;
  4866. res.set_content(body, "application/xml");
  4867. })
  4868. .Get("/request-target",
  4869. [&](const Request &req, Response & /*res*/) {
  4870. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  4871. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  4872. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  4873. })
  4874. .Get("/long-query-value",
  4875. [&](const Request &req, Response & /*res*/) {
  4876. EXPECT_EQ(LONG_QUERY_URL, req.target);
  4877. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  4878. })
  4879. .Get("/too-long-query-value",
  4880. [&](const Request &req, Response & /*res*/) {
  4881. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  4882. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  4883. })
  4884. .Get("/array-param",
  4885. [&](const Request &req, Response & /*res*/) {
  4886. EXPECT_EQ(3u, req.get_param_value_count("array"));
  4887. EXPECT_EQ("value1", req.get_param_value("array", 0));
  4888. EXPECT_EQ("value2", req.get_param_value("array", 1));
  4889. EXPECT_EQ("value3", req.get_param_value("array", 2));
  4890. })
  4891. .Get("/array-param-values",
  4892. [&](const Request &req, Response & /*res*/) {
  4893. auto values = req.get_param_values("array");
  4894. EXPECT_EQ(3u, values.size());
  4895. EXPECT_EQ("value1", values[0]);
  4896. EXPECT_EQ("value2", values[1]);
  4897. EXPECT_EQ("value3", values[2]);
  4898. auto empty = req.get_param_values("nonexistent");
  4899. EXPECT_TRUE(empty.empty());
  4900. })
  4901. .Post("/validate-no-multiple-headers",
  4902. [&](const Request &req, Response & /*res*/) {
  4903. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  4904. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  4905. })
  4906. .Post("/content_receiver",
  4907. [&](const Request &req, Response &res,
  4908. const ContentReader &content_reader) {
  4909. if (req.is_multipart_form_data()) {
  4910. std::vector<FormData> items;
  4911. content_reader(
  4912. [&](const FormData &file) {
  4913. items.push_back(file);
  4914. return true;
  4915. },
  4916. [&](const char *data, size_t data_length) {
  4917. items.back().content.append(data, data_length);
  4918. return true;
  4919. });
  4920. EXPECT_EQ(5u, items.size());
  4921. {
  4922. const auto &file = get_file_value(items, "text1");
  4923. EXPECT_TRUE(file.filename.empty());
  4924. EXPECT_EQ("text default", file.content);
  4925. }
  4926. {
  4927. const auto &file = get_file_value(items, "text2");
  4928. EXPECT_TRUE(file.filename.empty());
  4929. EXPECT_EQ("aωb", file.content);
  4930. }
  4931. {
  4932. const auto &file = get_file_value(items, "file1");
  4933. EXPECT_EQ("hello.txt", file.filename);
  4934. EXPECT_EQ("text/plain", file.content_type);
  4935. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  4936. }
  4937. {
  4938. const auto &file = get_file_value(items, "file2");
  4939. EXPECT_EQ("world.json", file.filename);
  4940. EXPECT_EQ("application/json", file.content_type);
  4941. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  4942. }
  4943. {
  4944. const auto &file = get_file_value(items, "file3");
  4945. EXPECT_TRUE(file.filename.empty());
  4946. EXPECT_EQ("application/octet-stream", file.content_type);
  4947. EXPECT_EQ(0u, file.content.size());
  4948. }
  4949. } else {
  4950. std::string body;
  4951. content_reader([&](const char *data, size_t data_length) {
  4952. EXPECT_EQ(7U, data_length);
  4953. body.append(data, data_length);
  4954. return true;
  4955. });
  4956. EXPECT_EQ(body, "content");
  4957. res.set_content(body, "text/plain");
  4958. }
  4959. })
  4960. .Put("/content_receiver",
  4961. [&](const Request & /*req*/, Response &res,
  4962. const ContentReader &content_reader) {
  4963. std::string body;
  4964. content_reader([&](const char *data, size_t data_length) {
  4965. body.append(data, data_length);
  4966. return true;
  4967. });
  4968. EXPECT_EQ(body, "content");
  4969. res.set_content(body, "text/plain");
  4970. })
  4971. .Patch("/content_receiver",
  4972. [&](const Request & /*req*/, Response &res,
  4973. const ContentReader &content_reader) {
  4974. std::string body;
  4975. content_reader([&](const char *data, size_t data_length) {
  4976. body.append(data, data_length);
  4977. return true;
  4978. });
  4979. EXPECT_EQ(body, "content");
  4980. res.set_content(body, "text/plain");
  4981. })
  4982. .Post("/query-string-and-body",
  4983. [&](const Request &req, Response & /*res*/) {
  4984. ASSERT_TRUE(req.has_param("key"));
  4985. EXPECT_EQ(req.get_param_value("key"), "value");
  4986. EXPECT_EQ(req.body, "content");
  4987. })
  4988. .Get("/last-request",
  4989. [&](const Request &req, Response & /*res*/) {
  4990. EXPECT_EQ("close", req.get_header_value("Connection"));
  4991. })
  4992. .Get(R"(/redirect/(\d+))",
  4993. [&](const Request &req, Response &res) {
  4994. auto num = std::stoi(req.matches[1]) + 1;
  4995. std::string url = "/redirect/" + std::to_string(num);
  4996. res.set_redirect(url);
  4997. })
  4998. .Post("/binary",
  4999. [&](const Request &req, Response &res) {
  5000. EXPECT_EQ(4U, req.body.size());
  5001. EXPECT_EQ("application/octet-stream",
  5002. req.get_header_value("Content-Type"));
  5003. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5004. res.set_content(req.body, "application/octet-stream");
  5005. })
  5006. .Put("/binary",
  5007. [&](const Request &req, Response &res) {
  5008. EXPECT_EQ(4U, req.body.size());
  5009. EXPECT_EQ("application/octet-stream",
  5010. req.get_header_value("Content-Type"));
  5011. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5012. res.set_content(req.body, "application/octet-stream");
  5013. })
  5014. .Patch("/binary",
  5015. [&](const Request &req, Response &res) {
  5016. EXPECT_EQ(4U, req.body.size());
  5017. EXPECT_EQ("application/octet-stream",
  5018. req.get_header_value("Content-Type"));
  5019. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5020. res.set_content(req.body, "application/octet-stream");
  5021. })
  5022. .Delete("/binary",
  5023. [&](const Request &req, Response &res) {
  5024. EXPECT_EQ(4U, req.body.size());
  5025. EXPECT_EQ("application/octet-stream",
  5026. req.get_header_value("Content-Type"));
  5027. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5028. res.set_content(req.body, "application/octet-stream");
  5029. })
  5030. .Get("/issue1772",
  5031. [&](const Request & /*req*/, Response &res) {
  5032. res.status = 401;
  5033. res.set_header("WWW-Authenticate", "Basic realm=123456");
  5034. })
  5035. .Delete("/issue609",
  5036. [](const httplib::Request &, httplib::Response &res,
  5037. const httplib::ContentReader &) {
  5038. res.set_content("ok", "text/plain");
  5039. })
  5040. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  5041. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5042. .Get("/compress",
  5043. [&](const Request & /*req*/, Response &res) {
  5044. res.set_content(
  5045. "12345678901234567890123456789012345678901234567890123456789"
  5046. "01234567890123456789012345678901234567890",
  5047. "text/plain");
  5048. })
  5049. .Get("/compress-with-charset",
  5050. [&](const Request & /*req*/, Response &res) {
  5051. res.set_content(
  5052. "12345678901234567890123456789012345678901234567890123456789"
  5053. "01234567890123456789012345678901234567890",
  5054. "application/json; charset=utf-8");
  5055. })
  5056. .Get("/nocompress",
  5057. [&](const Request & /*req*/, Response &res) {
  5058. res.set_content(
  5059. "12345678901234567890123456789012345678901234567890123456789"
  5060. "01234567890123456789012345678901234567890",
  5061. "application/octet-stream");
  5062. })
  5063. .Post("/compress-multipart",
  5064. [&](const Request &req, Response & /*res*/) {
  5065. EXPECT_EQ(2u, req.form.fields.size());
  5066. ASSERT_TRUE(!req.form.has_field("???"));
  5067. {
  5068. const auto &text = req.form.get_field("key1");
  5069. EXPECT_EQ("test", text);
  5070. }
  5071. {
  5072. const auto &text = req.form.get_field("key2");
  5073. EXPECT_EQ("--abcdefg123", text);
  5074. }
  5075. })
  5076. #endif
  5077. ;
  5078. persons_["john"] = "programmer";
  5079. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  5080. svr_.wait_until_ready();
  5081. }
  5082. virtual void TearDown() {
  5083. svr_.stop();
  5084. if (!request_threads_.empty()) {
  5085. std::this_thread::sleep_for(std::chrono::seconds(1));
  5086. for (auto &t : request_threads_) {
  5087. t.join();
  5088. }
  5089. }
  5090. t_.join();
  5091. }
  5092. map<string, string> persons_;
  5093. #ifdef CPPHTTPLIB_SSL_ENABLED
  5094. SSLClient cli_;
  5095. SSLServer svr_;
  5096. #else
  5097. Client cli_;
  5098. Server svr_;
  5099. #endif
  5100. thread t_;
  5101. std::vector<thread> request_threads_;
  5102. };
  5103. TEST_F(ServerTest, GetMethod200) {
  5104. auto res = cli_.Get("/hi");
  5105. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5106. EXPECT_EQ("HTTP/1.1", res->version);
  5107. EXPECT_EQ(StatusCode::OK_200, res->status);
  5108. EXPECT_EQ("OK", res->reason);
  5109. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5110. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5111. EXPECT_EQ("Hello World!", res->body);
  5112. }
  5113. TEST_F(ServerTest, GetEmptyFile) {
  5114. auto res = cli_.Get("/empty_file");
  5115. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5116. EXPECT_EQ(StatusCode::OK_200, res->status);
  5117. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5118. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  5119. EXPECT_EQ("", res->body);
  5120. }
  5121. TEST_F(ServerTest, GetFileContent) {
  5122. auto res = cli_.Get("/file_content");
  5123. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5124. EXPECT_EQ(StatusCode::OK_200, res->status);
  5125. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5126. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  5127. EXPECT_EQ("test.html", res->body);
  5128. }
  5129. TEST_F(ServerTest, GetFileContentWithRange) {
  5130. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  5131. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5132. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5133. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5134. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  5135. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  5136. EXPECT_EQ("est", res->body);
  5137. }
  5138. TEST_F(ServerTest, GetFileContentWithContentType) {
  5139. auto res = cli_.Get("/file_content_with_content_type");
  5140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5141. EXPECT_EQ(StatusCode::OK_200, res->status);
  5142. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5143. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  5144. EXPECT_EQ("file\n", res->body);
  5145. }
  5146. TEST_F(ServerTest, GetInvalidFileContent) {
  5147. auto res = cli_.Get("/invalid_file_content");
  5148. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5149. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5150. }
  5151. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  5152. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  5153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5154. EXPECT_EQ("HTTP/1.1", res->version);
  5155. EXPECT_EQ(StatusCode::OK_200, res->status);
  5156. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5157. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5158. EXPECT_EQ("Hello World!", res->body);
  5159. }
  5160. TEST_F(ServerTest, GetMethod302) {
  5161. auto res = cli_.Get("/");
  5162. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5163. EXPECT_EQ(StatusCode::Found_302, res->status);
  5164. EXPECT_EQ("/hi", res->get_header_value("Location"));
  5165. }
  5166. TEST_F(ServerTest, GetMethod302Redirect) {
  5167. cli_.set_follow_location(true);
  5168. auto res = cli_.Get("/");
  5169. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5170. EXPECT_EQ(StatusCode::OK_200, res->status);
  5171. EXPECT_EQ("Hello World!", res->body);
  5172. EXPECT_EQ("/hi", res->location);
  5173. }
  5174. TEST_F(ServerTest, GetMethod404) {
  5175. auto res = cli_.Get("/invalid");
  5176. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5177. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5178. }
  5179. TEST_F(ServerTest, HeadMethod200) {
  5180. auto res = cli_.Head("/hi");
  5181. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5182. EXPECT_EQ(StatusCode::OK_200, res->status);
  5183. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5184. EXPECT_TRUE(res->body.empty());
  5185. }
  5186. TEST_F(ServerTest, HeadMethod200Static) {
  5187. auto res = cli_.Head("/mount/dir/index.html");
  5188. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5189. EXPECT_EQ(StatusCode::OK_200, res->status);
  5190. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5191. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  5192. EXPECT_TRUE(res->body.empty());
  5193. }
  5194. TEST_F(ServerTest, HeadMethod404) {
  5195. auto res = cli_.Head("/invalid");
  5196. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5197. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5198. EXPECT_TRUE(res->body.empty());
  5199. }
  5200. TEST_F(ServerTest, GetMethodPersonJohn) {
  5201. auto res = cli_.Get("/person/john");
  5202. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5203. EXPECT_EQ(StatusCode::OK_200, res->status);
  5204. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5205. EXPECT_EQ("programmer", res->body);
  5206. }
  5207. TEST_F(ServerTest, PostMethod1) {
  5208. auto res = cli_.Get("/person/john1");
  5209. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5210. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5211. res = cli_.Post("/person", "name=john1&note=coder",
  5212. "application/x-www-form-urlencoded");
  5213. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5214. ASSERT_EQ(StatusCode::OK_200, res->status);
  5215. res = cli_.Get("/person/john1");
  5216. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5217. ASSERT_EQ(StatusCode::OK_200, res->status);
  5218. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5219. ASSERT_EQ("coder", res->body);
  5220. }
  5221. TEST_F(ServerTest, PostMethod2) {
  5222. auto res = cli_.Get("/person/john2");
  5223. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5224. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5225. Params params;
  5226. params.emplace("name", "john2");
  5227. params.emplace("note", "coder");
  5228. res = cli_.Post("/person", params);
  5229. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5230. ASSERT_EQ(StatusCode::OK_200, res->status);
  5231. res = cli_.Get("/person/john2");
  5232. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5233. ASSERT_EQ(StatusCode::OK_200, res->status);
  5234. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5235. ASSERT_EQ("coder", res->body);
  5236. }
  5237. TEST_F(ServerTest, PutMethod3) {
  5238. auto res = cli_.Get("/person/john3");
  5239. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5240. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5241. Params params;
  5242. params.emplace("name", "john3");
  5243. params.emplace("note", "coder");
  5244. res = cli_.Put("/person", params);
  5245. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5246. ASSERT_EQ(StatusCode::OK_200, res->status);
  5247. res = cli_.Get("/person/john3");
  5248. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5249. ASSERT_EQ(StatusCode::OK_200, res->status);
  5250. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5251. ASSERT_EQ("coder", res->body);
  5252. }
  5253. TEST_F(ServerTest, DeleteMethod1) {
  5254. auto res = cli_.Get("/person/john4");
  5255. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5256. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5257. Params params;
  5258. params.emplace("name", "john4");
  5259. params.emplace("note", "coder");
  5260. res = cli_.Post("/person", params);
  5261. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5262. ASSERT_EQ(StatusCode::OK_200, res->status);
  5263. res = cli_.Get("/person/john4");
  5264. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5265. ASSERT_EQ(StatusCode::OK_200, res->status);
  5266. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5267. ASSERT_EQ("coder", res->body);
  5268. Params delete_params;
  5269. delete_params.emplace("name", "john4");
  5270. res = cli_.Delete("/person", delete_params);
  5271. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5272. ASSERT_EQ(StatusCode::OK_200, res->status);
  5273. ASSERT_EQ("DELETED", res->body);
  5274. res = cli_.Get("/person/john4");
  5275. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5276. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5277. }
  5278. TEST_F(ServerTest, DeleteMethod2) {
  5279. auto res = cli_.Get("/person/john5");
  5280. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5281. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5282. Params params;
  5283. params.emplace("name", "john5");
  5284. params.emplace("note", "developer");
  5285. res = cli_.Post("/person", params);
  5286. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5287. ASSERT_EQ(StatusCode::OK_200, res->status);
  5288. res = cli_.Get("/person/john5");
  5289. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5290. ASSERT_EQ(StatusCode::OK_200, res->status);
  5291. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5292. ASSERT_EQ("developer", res->body);
  5293. Params delete_params;
  5294. delete_params.emplace("name", "john5");
  5295. Headers headers;
  5296. headers.emplace("Custom-Header", "test-value");
  5297. res = cli_.Delete("/person", headers, delete_params);
  5298. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5299. ASSERT_EQ(StatusCode::OK_200, res->status);
  5300. ASSERT_EQ("DELETED", res->body);
  5301. res = cli_.Get("/person/john5");
  5302. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5303. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5304. }
  5305. TEST_F(ServerTest, DeleteMethod3) {
  5306. auto res = cli_.Get("/person/john6");
  5307. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5308. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5309. Params params;
  5310. params.emplace("name", "john6");
  5311. params.emplace("note", "tester");
  5312. res = cli_.Post("/person", params);
  5313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5314. ASSERT_EQ(StatusCode::OK_200, res->status);
  5315. res = cli_.Get("/person/john6");
  5316. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5317. ASSERT_EQ(StatusCode::OK_200, res->status);
  5318. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5319. ASSERT_EQ("tester", res->body);
  5320. Params delete_params;
  5321. delete_params.emplace("name", "john6");
  5322. Headers headers;
  5323. headers.emplace("Custom-Header", "test-value");
  5324. res = cli_.Delete("/person", headers, delete_params, nullptr);
  5325. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5326. ASSERT_EQ(StatusCode::OK_200, res->status);
  5327. ASSERT_EQ("DELETED", res->body);
  5328. res = cli_.Get("/person/john6");
  5329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5330. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5331. }
  5332. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  5333. Params params;
  5334. params.emplace("json", JSON_DATA);
  5335. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  5336. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5337. ASSERT_EQ(StatusCode::OK_200, res->status);
  5338. ASSERT_EQ(JSON_DATA, res->body);
  5339. }
  5340. TEST_F(ServerTest, PostEmptyContent) {
  5341. auto res = cli_.Post("/empty", "", "text/plain");
  5342. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5343. ASSERT_EQ(StatusCode::OK_200, res->status);
  5344. ASSERT_EQ("empty", res->body);
  5345. }
  5346. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  5347. auto res = cli_.Post("/empty-no-content-type");
  5348. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5349. ASSERT_EQ(StatusCode::OK_200, res->status);
  5350. ASSERT_EQ("empty-no-content-type", res->body);
  5351. }
  5352. TEST_F(ServerTest, PostPathOnly) {
  5353. auto res = cli_.Post("/path-only");
  5354. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5355. ASSERT_EQ(StatusCode::OK_200, res->status);
  5356. ASSERT_EQ("path-only", res->body);
  5357. }
  5358. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  5359. auto res = cli_.Post("/path-headers-only",
  5360. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  5361. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5362. ASSERT_EQ(StatusCode::OK_200, res->status);
  5363. ASSERT_EQ("path-headers-only", res->body);
  5364. }
  5365. TEST_F(ServerTest, PostLarge) {
  5366. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  5367. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5368. ASSERT_EQ(StatusCode::OK_200, res->status);
  5369. EXPECT_EQ(LARGE_DATA, res->body);
  5370. }
  5371. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  5372. auto res = cli_.Put("/empty-no-content-type");
  5373. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5374. ASSERT_EQ(StatusCode::OK_200, res->status);
  5375. ASSERT_EQ("empty-no-content-type", res->body);
  5376. }
  5377. TEST_F(ServerTest, GetMethodDir) {
  5378. auto res = cli_.Get("/dir/");
  5379. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5380. EXPECT_EQ(StatusCode::OK_200, res->status);
  5381. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5382. auto body = R"(<html>
  5383. <head>
  5384. </head>
  5385. <body>
  5386. <a href="/dir/test.html">Test</a>
  5387. <a href="/hi">hi</a>
  5388. </body>
  5389. </html>
  5390. )";
  5391. EXPECT_EQ(body, res->body);
  5392. }
  5393. TEST_F(ServerTest, GetMethodDirTest) {
  5394. auto res = cli_.Get("/dir/test.html");
  5395. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5396. EXPECT_EQ(StatusCode::OK_200, res->status);
  5397. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5398. EXPECT_EQ("test.html", res->body);
  5399. }
  5400. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  5401. auto res = cli_.Get("/dir/../dir/test.html");
  5402. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5403. EXPECT_EQ(StatusCode::OK_200, res->status);
  5404. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5405. EXPECT_EQ("test.html", res->body);
  5406. }
  5407. TEST_F(ServerTest, GetMethodInvalidPath) {
  5408. auto res = cli_.Get("/dir/../test.html");
  5409. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5410. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5411. }
  5412. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  5413. auto res = cli_.Get("/../www/dir/test.html");
  5414. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5415. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5416. }
  5417. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  5418. auto res = cli_.Get("/dir/../../www/dir/test.html");
  5419. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5420. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5421. }
  5422. TEST_F(ServerTest, GetMethodDirMountTest) {
  5423. auto res = cli_.Get("/mount/dir/test.html");
  5424. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5425. EXPECT_EQ(StatusCode::OK_200, res->status);
  5426. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5427. EXPECT_EQ("test.html", res->body);
  5428. }
  5429. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  5430. auto res = cli_.Get("/mount/dir/../dir/test.html");
  5431. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5432. EXPECT_EQ(StatusCode::OK_200, res->status);
  5433. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5434. EXPECT_EQ("test.html", res->body);
  5435. }
  5436. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  5437. auto res = cli_.Get("/mount/dir/../test.html");
  5438. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5439. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5440. }
  5441. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  5442. auto res = cli_.Get("/mount/dir/test.html%00.js");
  5443. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5444. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5445. }
  5446. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  5447. auto res = cli_.Get("/mount/../www2/dir/test.html");
  5448. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5449. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5450. }
  5451. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  5452. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  5453. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5454. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5455. }
  5456. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  5457. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  5458. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5459. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5460. }
  5461. TEST_F(ServerTest, PostMethod303) {
  5462. auto res = cli_.Post("/1", "body", "text/plain");
  5463. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5464. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  5465. EXPECT_EQ("/2", res->get_header_value("Location"));
  5466. }
  5467. TEST_F(ServerTest, PostMethod303Redirect) {
  5468. cli_.set_follow_location(true);
  5469. auto res = cli_.Post("/1", "body", "text/plain");
  5470. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5471. EXPECT_EQ(StatusCode::OK_200, res->status);
  5472. EXPECT_EQ("redirected.", res->body);
  5473. EXPECT_EQ("/2", res->location);
  5474. }
  5475. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  5476. auto res = cli_.Get("/dir/test.abcde");
  5477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5478. EXPECT_EQ(StatusCode::OK_200, res->status);
  5479. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5480. EXPECT_EQ("abcde", res->body);
  5481. }
  5482. TEST_F(ServerTest, StaticFileRange) {
  5483. auto res =
  5484. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  5485. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5486. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5487. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5488. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5489. EXPECT_EQ(true, res->has_header("Content-Range"));
  5490. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5491. EXPECT_EQ(std::string("cd"), res->body);
  5492. }
  5493. TEST_F(ServerTest, StaticFileRanges) {
  5494. auto res = cli_.Get("/dir/test.abcde",
  5495. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  5496. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5497. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5498. EXPECT_TRUE(
  5499. res->get_header_value("Content-Type")
  5500. .find(
  5501. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  5502. 0);
  5503. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  5504. }
  5505. TEST_F(ServerTest, StaticFileRangeHead) {
  5506. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  5507. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5508. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5509. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5510. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5511. EXPECT_EQ(true, res->has_header("Content-Range"));
  5512. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5513. }
  5514. TEST_F(ServerTest, StaticFileRangeBigFile) {
  5515. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  5516. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5517. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5518. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5519. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  5520. EXPECT_EQ(true, res->has_header("Content-Range"));
  5521. EXPECT_EQ("bytes 1048571-1048575/1048576",
  5522. res->get_header_value("Content-Range"));
  5523. EXPECT_EQ("LAST\n", res->body);
  5524. }
  5525. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  5526. auto res =
  5527. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  5528. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5529. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5530. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5531. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  5532. EXPECT_EQ(true, res->has_header("Content-Range"));
  5533. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  5534. }
  5535. TEST_F(ServerTest, StaticFileBigFile) {
  5536. auto res = cli_.Get("/dir/1MB.txt");
  5537. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5538. EXPECT_EQ(StatusCode::OK_200, res->status);
  5539. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5540. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  5541. }
  5542. TEST_F(ServerTest, InvalidBaseDirMount) {
  5543. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  5544. }
  5545. TEST_F(ServerTest, Binary) {
  5546. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  5547. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  5548. "application/octet-stream");
  5549. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5550. ASSERT_EQ(StatusCode::OK_200, res->status);
  5551. ASSERT_EQ(4U, res->body.size());
  5552. res = cli_.Put("/binary", binary.data(), binary.size(),
  5553. "application/octet-stream");
  5554. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5555. ASSERT_EQ(StatusCode::OK_200, res->status);
  5556. ASSERT_EQ(4U, res->body.size());
  5557. res = cli_.Patch("/binary", binary.data(), binary.size(),
  5558. "application/octet-stream");
  5559. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5560. ASSERT_EQ(StatusCode::OK_200, res->status);
  5561. ASSERT_EQ(4U, res->body.size());
  5562. res = cli_.Delete("/binary", binary.data(), binary.size(),
  5563. "application/octet-stream");
  5564. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5565. ASSERT_EQ(StatusCode::OK_200, res->status);
  5566. ASSERT_EQ(4U, res->body.size());
  5567. }
  5568. TEST_F(ServerTest, BinaryString) {
  5569. auto binary = std::string("\x00\x01\x02\x03", 4);
  5570. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  5571. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5572. ASSERT_EQ(StatusCode::OK_200, res->status);
  5573. ASSERT_EQ(4U, res->body.size());
  5574. res = cli_.Put("/binary", binary, "application/octet-stream");
  5575. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5576. ASSERT_EQ(StatusCode::OK_200, res->status);
  5577. ASSERT_EQ(4U, res->body.size());
  5578. res = cli_.Patch("/binary", binary, "application/octet-stream");
  5579. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5580. ASSERT_EQ(StatusCode::OK_200, res->status);
  5581. ASSERT_EQ(4U, res->body.size());
  5582. res = cli_.Delete("/binary", binary, "application/octet-stream");
  5583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5584. ASSERT_EQ(StatusCode::OK_200, res->status);
  5585. ASSERT_EQ(4U, res->body.size());
  5586. }
  5587. TEST_F(ServerTest, EmptyRequest) {
  5588. auto res = cli_.Get("");
  5589. ASSERT_TRUE(!res);
  5590. EXPECT_EQ(Error::Connection, res.error());
  5591. }
  5592. TEST_F(ServerTest, LongRequest) {
  5593. std::string request;
  5594. for (size_t i = 0; i < 545; i++) {
  5595. request += "/TooLongRequest";
  5596. }
  5597. request += "OK";
  5598. auto res = cli_.Get(request.c_str());
  5599. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5600. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5601. }
  5602. TEST_F(ServerTest, TooLongRequest) {
  5603. std::string request;
  5604. for (size_t i = 0; i < 546; i++) {
  5605. request += "/TooLongRequest";
  5606. }
  5607. request += "_NG";
  5608. auto start = std::chrono::high_resolution_clock::now();
  5609. cli_.set_keep_alive(true);
  5610. auto res = cli_.Get(request.c_str());
  5611. auto end = std::chrono::high_resolution_clock::now();
  5612. auto elapsed =
  5613. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5614. .count();
  5615. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5616. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5617. EXPECT_LE(elapsed, 1000);
  5618. EXPECT_EQ("close", res->get_header_value("Connection"));
  5619. EXPECT_FALSE(cli_.is_socket_open());
  5620. }
  5621. TEST_F(ServerTest, AlmostTooLongRequest) {
  5622. // test for #2046 - URI length check shouldn't include other content on req
  5623. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  5624. // leading /, space, HTTP/1.1)
  5625. std::string request =
  5626. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  5627. auto res = cli_.Get(request.c_str());
  5628. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5629. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5630. }
  5631. TEST_F(ServerTest, LongHeader) {
  5632. Request req;
  5633. req.method = "GET";
  5634. req.path = "/hi";
  5635. std::string host_and_port;
  5636. host_and_port += HOST;
  5637. host_and_port += ":";
  5638. host_and_port += std::to_string(PORT);
  5639. req.headers.emplace("Host", host_and_port.c_str());
  5640. req.headers.emplace("Accept", "*/*");
  5641. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5642. req.headers.emplace(
  5643. "Header-Name",
  5644. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5645. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5646. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5647. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5648. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5649. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5650. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5651. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5652. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5653. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5654. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5655. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5656. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5657. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5658. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5659. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5660. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5661. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5662. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5663. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5664. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5665. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5666. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5667. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5668. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5669. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5670. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5671. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5672. "@@@@@@@@@@@@@@@@");
  5673. auto res = std::make_shared<Response>();
  5674. auto error = Error::Success;
  5675. auto ret = cli_.send(req, *res, error);
  5676. ASSERT_TRUE(ret);
  5677. EXPECT_EQ(StatusCode::OK_200, res->status);
  5678. }
  5679. TEST_F(ServerTest, LongQueryValue) {
  5680. auto start = std::chrono::high_resolution_clock::now();
  5681. cli_.set_keep_alive(true);
  5682. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  5683. auto end = std::chrono::high_resolution_clock::now();
  5684. auto elapsed =
  5685. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5686. .count();
  5687. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5688. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5689. EXPECT_LE(elapsed, 1000);
  5690. EXPECT_EQ("close", res->get_header_value("Connection"));
  5691. EXPECT_FALSE(cli_.is_socket_open());
  5692. }
  5693. TEST_F(ServerTest, TooLongQueryValue) {
  5694. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  5695. ASSERT_FALSE(res);
  5696. EXPECT_EQ(Error::Read, res.error());
  5697. }
  5698. TEST_F(ServerTest, TooLongHeader) {
  5699. Request req;
  5700. req.method = "GET";
  5701. req.path = "/hi";
  5702. std::string host_and_port;
  5703. host_and_port += HOST;
  5704. host_and_port += ":";
  5705. host_and_port += std::to_string(PORT);
  5706. req.headers.emplace("Host", host_and_port.c_str());
  5707. req.headers.emplace("Accept", "*/*");
  5708. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5709. req.headers.emplace(
  5710. "Header-Name",
  5711. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5712. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5713. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5714. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5715. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5716. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5717. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5718. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5719. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5720. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5721. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5722. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5723. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5724. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5725. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5726. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5727. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5728. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5729. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5730. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5731. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5732. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5733. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5734. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5735. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5736. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5737. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5738. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5739. "@@@@@@@@@@@@@@@@@");
  5740. auto res = std::make_shared<Response>();
  5741. auto error = Error::Success;
  5742. auto ret = cli_.send(req, *res, error);
  5743. ASSERT_TRUE(ret);
  5744. EXPECT_EQ(StatusCode::OK_200, res->status);
  5745. }
  5746. TEST_F(ServerTest, HeaderCountAtLimit) {
  5747. // Test with headers just under the 100 limit
  5748. httplib::Headers headers;
  5749. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  5750. // This should keep us just under the 100 header limit
  5751. for (int i = 0; i < 95; i++) {
  5752. std::string name = "X-Test-Header-" + std::to_string(i);
  5753. std::string value = "value" + std::to_string(i);
  5754. headers.emplace(name, value);
  5755. }
  5756. // This should work fine as we're under the limit
  5757. auto res = cli_.Get("/hi", headers);
  5758. EXPECT_TRUE(res);
  5759. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  5760. }
  5761. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  5762. // Test with many headers to exceed the 100 limit
  5763. httplib::Headers headers;
  5764. // Add 150 headers to definitely exceed the 100 limit
  5765. for (int i = 0; i < 150; i++) {
  5766. std::string name = "X-Test-Header-" + std::to_string(i);
  5767. std::string value = "value" + std::to_string(i);
  5768. headers.emplace(name, value);
  5769. }
  5770. // This should fail due to exceeding header count limit
  5771. cli_.set_keep_alive(true);
  5772. auto res = cli_.Get("/hi", headers);
  5773. // The server should respond with 400 Bad Request
  5774. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5775. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5776. EXPECT_EQ("close", res->get_header_value("Connection"));
  5777. EXPECT_FALSE(cli_.is_socket_open());
  5778. }
  5779. TEST_F(ServerTest, PercentEncoding) {
  5780. auto res = cli_.Get("/e%6edwith%");
  5781. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5782. EXPECT_EQ(StatusCode::OK_200, res->status);
  5783. }
  5784. TEST_F(ServerTest, PercentEncodingUnicode) {
  5785. auto res = cli_.Get("/e%u006edwith%");
  5786. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5787. EXPECT_EQ(StatusCode::OK_200, res->status);
  5788. }
  5789. TEST_F(ServerTest, InvalidPercentEncoding) {
  5790. auto res = cli_.Get("/%endwith%");
  5791. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5792. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5793. }
  5794. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  5795. auto res = cli_.Get("/%uendwith%");
  5796. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5797. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5798. }
  5799. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  5800. auto res = cli_.Get("/hello?aaa=bbb%");
  5801. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5802. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5803. }
  5804. TEST_F(ServerTest, PlusSignEncoding) {
  5805. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  5806. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5807. EXPECT_EQ(StatusCode::OK_200, res->status);
  5808. EXPECT_EQ("a +b", res->body);
  5809. }
  5810. TEST_F(ServerTest, HeaderCountSecurityTest) {
  5811. // This test simulates a potential DoS attack using many headers
  5812. // to verify our security fix prevents memory exhaustion
  5813. httplib::Headers attack_headers;
  5814. // Attempt to add many headers like an attacker would (200 headers to far
  5815. // exceed limit)
  5816. for (int i = 0; i < 200; i++) {
  5817. std::string name = "X-Attack-Header-" + std::to_string(i);
  5818. std::string value = "attack_payload_" + std::to_string(i);
  5819. attack_headers.emplace(name, value);
  5820. }
  5821. // Try to POST with excessive headers
  5822. cli_.set_keep_alive(true);
  5823. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  5824. // Should either fail or return 400 Bad Request due to security limit
  5825. if (res) {
  5826. // If we get a response, it should be 400 Bad Request
  5827. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5828. EXPECT_EQ("close", res->get_header_value("Connection"));
  5829. }
  5830. EXPECT_FALSE(cli_.is_socket_open());
  5831. }
  5832. TEST_F(ServerTest, MultipartFormData) {
  5833. UploadFormDataItems items = {
  5834. {"text1", "text default", "", ""},
  5835. {"text2", "aωb", "", ""},
  5836. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5837. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  5838. {"file3", "", "", "application/octet-stream"},
  5839. {"file4", "", "", " application/json tmp-string "}};
  5840. auto res = cli_.Post("/multipart", items);
  5841. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5842. EXPECT_EQ(StatusCode::OK_200, res->status);
  5843. }
  5844. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  5845. UploadFormDataItems items = {
  5846. {"text", "default text", "", ""},
  5847. {"multi_text1", "aaaaa", "", ""},
  5848. {"multi_text1", "bbbbb", "", ""},
  5849. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5850. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  5851. "application/json"},
  5852. };
  5853. auto res = cli_.Post("/multipart/multi_file_values", items);
  5854. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5855. EXPECT_EQ(StatusCode::OK_200, res->status);
  5856. }
  5857. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  5858. auto res = cli_.Get("/hi");
  5859. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5860. EXPECT_EQ(StatusCode::OK_200, res->status);
  5861. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  5862. EXPECT_EQ("Hello World!", res->body);
  5863. }
  5864. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  5865. Request req;
  5866. req.method = "POST";
  5867. req.path = "/chunked";
  5868. std::string host_and_port;
  5869. host_and_port += HOST;
  5870. host_and_port += ":";
  5871. host_and_port += std::to_string(PORT);
  5872. req.headers.emplace("Host", host_and_port.c_str());
  5873. req.headers.emplace("Accept", "*/*");
  5874. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5875. req.headers.emplace("Content-Type", "text/plain");
  5876. req.headers.emplace("Content-Length", "0");
  5877. req.headers.emplace(
  5878. "Transfer-Encoding",
  5879. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  5880. // Client does not chunk, so make a chunked body manually.
  5881. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  5882. auto res = std::make_shared<Response>();
  5883. auto error = Error::Success;
  5884. auto ret = cli_.send(req, *res, error);
  5885. ASSERT_TRUE(ret);
  5886. EXPECT_EQ(StatusCode::OK_200, res->status);
  5887. }
  5888. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  5889. // rather than treat them as valid lengths.
  5890. template <typename ClientT>
  5891. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  5892. Request req;
  5893. req.method = "POST";
  5894. req.path = "/chunked";
  5895. std::string host_and_port;
  5896. host_and_port += HOST;
  5897. host_and_port += ":";
  5898. host_and_port += std::to_string(PORT);
  5899. req.headers.emplace("Host", host_and_port.c_str());
  5900. req.headers.emplace("Content-Length", "0");
  5901. req.headers.emplace("Transfer-Encoding", "chunked");
  5902. req.body = body;
  5903. auto res = std::make_shared<Response>();
  5904. auto error = Error::Success;
  5905. ASSERT_TRUE(cli.send(req, *res, error));
  5906. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5907. }
  5908. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  5909. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  5910. }
  5911. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  5912. expect_chunked_body_rejected(
  5913. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  5914. }
  5915. TEST_F(ServerTest, GetStreamed2) {
  5916. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  5917. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5918. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5919. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5920. EXPECT_EQ(true, res->has_header("Content-Range"));
  5921. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  5922. EXPECT_EQ(std::string("ab"), res->body);
  5923. }
  5924. TEST_F(ServerTest, GetStreamed) {
  5925. auto res = cli_.Get("/streamed");
  5926. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5927. EXPECT_EQ(StatusCode::OK_200, res->status);
  5928. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5929. EXPECT_EQ(std::string("aaabbb"), res->body);
  5930. }
  5931. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  5932. auto res = cli_.Get("/streamed-without-length",
  5933. Headers{make_range_header({{0, -1}})});
  5934. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5935. EXPECT_EQ(StatusCode::OK_200, res->status);
  5936. EXPECT_EQ(false, res->has_header("Content-Length"));
  5937. EXPECT_EQ(false, res->has_header("Content-Range"));
  5938. EXPECT_EQ(std::string("abcdefg"), res->body);
  5939. }
  5940. TEST_F(ServerTest, GetStreamedWithRange1) {
  5941. auto res =
  5942. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  5943. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5944. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5945. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5946. EXPECT_EQ(true, res->has_header("Content-Range"));
  5947. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  5948. EXPECT_EQ(std::string("def"), res->body);
  5949. }
  5950. TEST_F(ServerTest, GetStreamedWithRange2) {
  5951. auto res =
  5952. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  5953. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5954. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5955. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5956. EXPECT_EQ(true, res->has_header("Content-Range"));
  5957. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  5958. EXPECT_EQ(std::string("bcdefg"), res->body);
  5959. }
  5960. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  5961. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  5962. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5963. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5964. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5965. EXPECT_EQ(true, res->has_header("Content-Range"));
  5966. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  5967. EXPECT_EQ(std::string("efg"), res->body);
  5968. }
  5969. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  5970. auto res =
  5971. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-9999"}});
  5972. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5973. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5974. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5975. EXPECT_EQ(false, res->has_header("Content-Range"));
  5976. EXPECT_EQ(0U, res->body.size());
  5977. }
  5978. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  5979. // Only a 206 is served as a partial representation. Under any other status
  5980. // `apply_ranges()` reported the full content length, so the body must match
  5981. // that header, and the content provider must never be asked for an offset
  5982. // outside the representation.
  5983. auto check = [&](int status, const char *range) {
  5984. auto path =
  5985. std::string("/streamed-with-range?status=") + std::to_string(status);
  5986. auto ctx = path + " Range: " + range;
  5987. auto res = cli_.Get(path, Headers{{"Range", range}});
  5988. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  5989. EXPECT_EQ(status, res->status) << ctx;
  5990. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  5991. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  5992. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  5993. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  5994. };
  5995. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  5996. check(403, "bytes=3-5");
  5997. // The offset is far past the representation.
  5998. check(403, "bytes=100000-100200");
  5999. // `first_pos` is still -1 here, and the bounds asserts in
  6000. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  6001. check(403, "bytes=-3");
  6002. // `apply_ranges()` makes no boundary for a non-206 response, so the
  6003. // multipart branch would have written one that is empty.
  6004. check(403, "bytes=1-2, 4-5");
  6005. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  6006. // covers the whole representation.
  6007. check(200, "bytes=3-5");
  6008. check(200, "bytes=1-2, 4-5");
  6009. }
  6010. TEST_F(ServerTest, GetStreamedWithRangeError) {
  6011. auto res =
  6012. cli_.Get("/streamed-with-range",
  6013. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  6014. "92233720368547758079223372036854775807"}});
  6015. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6016. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6017. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6018. EXPECT_EQ(false, res->has_header("Content-Range"));
  6019. EXPECT_EQ(0U, res->body.size());
  6020. }
  6021. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  6022. auto res = cli_.Get(
  6023. "/with-range",
  6024. Headers{{"Range",
  6025. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  6026. {"Accept-Encoding", ""}});
  6027. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6028. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6029. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6030. EXPECT_EQ(true, res->has_header("Content-Range"));
  6031. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6032. EXPECT_EQ(std::string("abcdefg"), res->body);
  6033. }
  6034. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  6035. auto res = cli_.Get("/with-range", Headers{
  6036. {"Range", "bytes=0-"},
  6037. {"Accept-Encoding", ""},
  6038. });
  6039. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6040. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6041. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6042. EXPECT_EQ(true, res->has_header("Content-Range"));
  6043. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6044. EXPECT_EQ(std::string("abcdefg"), res->body);
  6045. }
  6046. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  6047. auto res = cli_.Get("/streamed-with-range",
  6048. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6049. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6050. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6051. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6052. EXPECT_EQ(false, res->has_header("Content-Range"));
  6053. EXPECT_EQ(267U, res->body.size());
  6054. // Check that both range contents are present
  6055. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  6056. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6057. // Check that Content-Range headers are present for both ranges
  6058. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  6059. std::string::npos);
  6060. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6061. std::string::npos);
  6062. }
  6063. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  6064. Ranges ranges;
  6065. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  6066. ranges.emplace_back(0, -1);
  6067. }
  6068. auto res = cli_.Get("/streamed-with-range?error",
  6069. Headers{{make_range_header(ranges)}});
  6070. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6071. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6072. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6073. EXPECT_EQ(false, res->has_header("Content-Range"));
  6074. EXPECT_EQ(0U, res->body.size());
  6075. }
  6076. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  6077. auto res = cli_.Get("/streamed-with-range",
  6078. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  6079. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6080. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6081. EXPECT_EQ(5U, res->body.size());
  6082. // Check that overlapping ranges are coalesced into a single range
  6083. EXPECT_EQ("bcdef", res->body);
  6084. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  6085. // Should be single range, not multipart
  6086. EXPECT_TRUE(res->has_header("Content-Range"));
  6087. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6088. }
  6089. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  6090. auto res = cli_.Get("/streamed-with-range",
  6091. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  6092. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6093. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6094. EXPECT_EQ(268U, res->body.size());
  6095. // Check that both range contents are present
  6096. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6097. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  6098. // Check that Content-Range headers are present for both ranges
  6099. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6100. std::string::npos);
  6101. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  6102. std::string::npos);
  6103. }
  6104. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  6105. auto res = cli_.Get("/streamed-with-range",
  6106. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  6107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6108. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6109. EXPECT_EQ(269U, res->body.size());
  6110. // Check that both duplicate range contents are present
  6111. size_t first_abc = res->body.find("abc\r\n");
  6112. EXPECT_TRUE(first_abc != std::string::npos);
  6113. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  6114. EXPECT_TRUE(second_abc != std::string::npos);
  6115. // Check that Content-Range headers are present for both ranges
  6116. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  6117. EXPECT_TRUE(first_range != std::string::npos);
  6118. size_t second_range =
  6119. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  6120. EXPECT_TRUE(second_range != std::string::npos);
  6121. }
  6122. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  6123. auto res =
  6124. cli_.Get("/streamed-with-range?error",
  6125. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  6126. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6127. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6128. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6129. EXPECT_EQ(false, res->has_header("Content-Range"));
  6130. EXPECT_EQ(0U, res->body.size());
  6131. }
  6132. TEST_F(ServerTest, GetStreamedEndless) {
  6133. uint64_t offset = 0;
  6134. auto res = cli_.Get("/streamed-cancel",
  6135. [&](const char * /*data*/, uint64_t data_length) {
  6136. if (offset < 100) {
  6137. offset += data_length;
  6138. return true;
  6139. }
  6140. return false;
  6141. });
  6142. ASSERT_TRUE(!res);
  6143. EXPECT_EQ(Error::Canceled, res.error());
  6144. }
  6145. TEST_F(ServerTest, ClientStop) {
  6146. std::atomic_size_t count{4};
  6147. std::vector<std::thread> threads;
  6148. for (auto i = count.load(); i != 0; --i) {
  6149. threads.emplace_back([&]() {
  6150. auto res = cli_.Get("/streamed-cancel",
  6151. [&](const char *, uint64_t) { return true; });
  6152. --count;
  6153. ASSERT_TRUE(!res);
  6154. EXPECT_TRUE(res.error() == Error::Canceled ||
  6155. res.error() == Error::Read || res.error() == Error::Write);
  6156. });
  6157. }
  6158. std::this_thread::sleep_for(std::chrono::seconds(2));
  6159. while (count != 0) {
  6160. cli_.stop();
  6161. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  6162. }
  6163. for (auto &t : threads) {
  6164. t.join();
  6165. }
  6166. }
  6167. TEST_F(ServerTest, GetWithRange1) {
  6168. auto res = cli_.Get("/with-range", Headers{
  6169. make_range_header({{3, 5}}),
  6170. {"Accept-Encoding", ""},
  6171. });
  6172. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6173. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6174. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6175. EXPECT_EQ(true, res->has_header("Content-Range"));
  6176. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6177. EXPECT_EQ(std::string("def"), res->body);
  6178. }
  6179. TEST_F(ServerTest, GetWithRange2) {
  6180. auto res = cli_.Get("/with-range", Headers{
  6181. make_range_header({{1, -1}}),
  6182. {"Accept-Encoding", ""},
  6183. });
  6184. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6185. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6186. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6187. EXPECT_EQ(true, res->has_header("Content-Range"));
  6188. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6189. EXPECT_EQ(std::string("bcdefg"), res->body);
  6190. }
  6191. TEST_F(ServerTest, GetWithRange3) {
  6192. auto res = cli_.Get("/with-range", Headers{
  6193. make_range_header({{0, 0}}),
  6194. {"Accept-Encoding", ""},
  6195. });
  6196. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6197. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6198. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  6199. EXPECT_EQ(true, res->has_header("Content-Range"));
  6200. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  6201. EXPECT_EQ(std::string("a"), res->body);
  6202. }
  6203. TEST_F(ServerTest, GetWithRange4) {
  6204. auto res = cli_.Get("/with-range", Headers{
  6205. make_range_header({{-1, 2}}),
  6206. {"Accept-Encoding", ""},
  6207. });
  6208. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6209. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6210. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6211. EXPECT_EQ(true, res->has_header("Content-Range"));
  6212. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  6213. EXPECT_EQ(std::string("fg"), res->body);
  6214. }
  6215. TEST_F(ServerTest, GetWithRange5) {
  6216. auto res = cli_.Get("/with-range", Headers{
  6217. make_range_header({{0, 5}}),
  6218. {"Accept-Encoding", ""},
  6219. });
  6220. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6221. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6222. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6223. EXPECT_EQ(true, res->has_header("Content-Range"));
  6224. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  6225. EXPECT_EQ(std::string("abcdef"), res->body);
  6226. }
  6227. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  6228. auto res =
  6229. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  6230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6231. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6232. }
  6233. TEST_F(ServerTest, GetWithRangeMultipart) {
  6234. auto res =
  6235. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6236. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6237. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6238. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6239. EXPECT_EQ(false, res->has_header("Content-Range"));
  6240. EXPECT_EQ(267U, res->body.size());
  6241. }
  6242. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  6243. auto res = cli_.Get("/with-range",
  6244. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  6245. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6246. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6247. }
  6248. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  6249. auto res = cli_.Get("/with-range-customized-response",
  6250. Headers{{make_range_header({{1, 2}})}});
  6251. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6252. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6253. EXPECT_EQ(true, res->has_header("Content-Length"));
  6254. EXPECT_EQ(false, res->has_header("Content-Range"));
  6255. EXPECT_EQ(JSON_DATA, res->body);
  6256. }
  6257. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  6258. auto res = cli_.Get("/with-range-customized-response",
  6259. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6260. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6261. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6262. EXPECT_EQ(true, res->has_header("Content-Length"));
  6263. EXPECT_EQ(false, res->has_header("Content-Range"));
  6264. EXPECT_EQ(JSON_DATA, res->body);
  6265. }
  6266. TEST_F(ServerTest, Issue1772) {
  6267. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  6268. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6269. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  6270. }
  6271. TEST_F(ServerTest, Issue609) {
  6272. auto res = cli_.Delete("/issue609");
  6273. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6274. EXPECT_EQ(StatusCode::OK_200, res->status);
  6275. EXPECT_EQ(std::string("ok"), res->body);
  6276. }
  6277. TEST_F(ServerTest, GetStreamedChunked) {
  6278. auto res = cli_.Get("/streamed-chunked");
  6279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6280. EXPECT_EQ(StatusCode::OK_200, res->status);
  6281. EXPECT_EQ(std::string("123456789"), res->body);
  6282. }
  6283. TEST_F(ServerTest, GetStreamedChunked2) {
  6284. auto res = cli_.Get("/streamed-chunked2");
  6285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6286. EXPECT_EQ(StatusCode::OK_200, res->status);
  6287. EXPECT_EQ(std::string("123456789"), res->body);
  6288. }
  6289. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  6290. auto res = cli_.Get("/streamed-chunked-with-trailer");
  6291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6292. EXPECT_EQ(StatusCode::OK_200, res->status);
  6293. EXPECT_EQ(std::string("123456789"), res->body);
  6294. EXPECT_TRUE(res->has_header("Trailer"));
  6295. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  6296. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  6297. // Trailers are now stored separately from headers (security fix)
  6298. EXPECT_EQ(2U, res->trailers.size());
  6299. EXPECT_TRUE(res->has_trailer("Dummy1"));
  6300. EXPECT_TRUE(res->has_trailer("Dummy2"));
  6301. EXPECT_FALSE(res->has_trailer("Dummy3"));
  6302. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  6303. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  6304. // Verify trailers are NOT in headers (security verification)
  6305. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  6306. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  6307. }
  6308. TEST_F(ServerTest, LargeChunkedPost) {
  6309. Request req;
  6310. req.method = "POST";
  6311. req.path = "/large-chunked";
  6312. std::string host_and_port;
  6313. host_and_port += HOST;
  6314. host_and_port += ":";
  6315. host_and_port += std::to_string(PORT);
  6316. req.headers.emplace("Host", host_and_port.c_str());
  6317. req.headers.emplace("Accept", "*/*");
  6318. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6319. req.headers.emplace("Content-Type", "text/plain");
  6320. req.headers.emplace("Content-Length", "0");
  6321. req.headers.emplace("Transfer-Encoding", "chunked");
  6322. std::string long_string(30 * 1024u, 'a');
  6323. std::string chunk = "7800\r\n" + long_string + "\r\n";
  6324. // Attempt to make a large enough post to exceed OS buffers, to test that
  6325. // the server handles short reads if the full chunk data isn't available.
  6326. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  6327. auto res = std::make_shared<Response>();
  6328. auto error = Error::Success;
  6329. auto ret = cli_.send(req, *res, error);
  6330. ASSERT_TRUE(ret);
  6331. EXPECT_EQ(StatusCode::OK_200, res->status);
  6332. }
  6333. TEST_F(ServerTest, GetMethodRemoteAddr) {
  6334. auto res = cli_.Get("/remote_addr");
  6335. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6336. EXPECT_EQ(StatusCode::OK_200, res->status);
  6337. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6338. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  6339. }
  6340. TEST_F(ServerTest, GetMethodLocalAddr) {
  6341. auto res = cli_.Get("/local_addr");
  6342. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6343. EXPECT_EQ(StatusCode::OK_200, res->status);
  6344. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6345. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  6346. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  6347. }
  6348. TEST_F(ServerTest, HTTPResponseSplitting) {
  6349. auto res = cli_.Get("/http_response_splitting");
  6350. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6351. EXPECT_EQ(StatusCode::OK_200, res->status);
  6352. }
  6353. TEST_F(ServerTest, SlowRequest) {
  6354. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6355. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6356. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6357. }
  6358. #if 0
  6359. TEST_F(ServerTest, SlowPost) {
  6360. char buffer[64 * 1024];
  6361. memset(buffer, 0x42, sizeof(buffer));
  6362. auto res = cli_.Post(
  6363. "/slowpost", 64 * 1024 * 1024,
  6364. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6365. auto ret = sink.write(buffer, sizeof(buffer));
  6366. EXPECT_TRUE(ret);
  6367. return true;
  6368. },
  6369. "text/plain");
  6370. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6371. EXPECT_EQ(StatusCode::OK_200, res->status);
  6372. }
  6373. TEST_F(ServerTest, SlowPostFail) {
  6374. char buffer[64 * 1024];
  6375. memset(buffer, 0x42, sizeof(buffer));
  6376. cli_.set_write_timeout(std::chrono::seconds(0));
  6377. auto res = cli_.Post(
  6378. "/slowpost", 64 * 1024 * 1024,
  6379. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6380. sink.write(buffer, sizeof(buffer));
  6381. return true;
  6382. },
  6383. "text/plain");
  6384. ASSERT_TRUE(!res);
  6385. EXPECT_EQ(Error::Write, res.error());
  6386. }
  6387. #endif
  6388. TEST_F(ServerTest, Put) {
  6389. auto res = cli_.Put("/put", "PUT", "text/plain");
  6390. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6391. EXPECT_EQ(StatusCode::OK_200, res->status);
  6392. EXPECT_EQ("PUT", res->body);
  6393. }
  6394. TEST_F(ServerTest, PutWithContentProvider) {
  6395. auto res = cli_.Put(
  6396. "/put", 3,
  6397. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6398. sink.os << "PUT";
  6399. return true;
  6400. },
  6401. "text/plain");
  6402. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6403. EXPECT_EQ(StatusCode::OK_200, res->status);
  6404. EXPECT_EQ("PUT", res->body);
  6405. }
  6406. TEST_F(ServerTest, PostWithContentProviderAbort) {
  6407. auto res = cli_.Post(
  6408. "/post", 42,
  6409. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6410. return false;
  6411. },
  6412. "text/plain");
  6413. ASSERT_TRUE(!res);
  6414. EXPECT_EQ(Error::Canceled, res.error());
  6415. }
  6416. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  6417. auto res = cli_.Put(
  6418. "/put",
  6419. [](size_t /*offset*/, DataSink &sink) {
  6420. sink.os << "PUT";
  6421. sink.done();
  6422. return true;
  6423. },
  6424. "text/plain");
  6425. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6426. EXPECT_EQ(StatusCode::OK_200, res->status);
  6427. EXPECT_EQ("PUT", res->body);
  6428. }
  6429. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  6430. auto res = cli_.Post(
  6431. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6432. "text/plain");
  6433. ASSERT_TRUE(!res);
  6434. EXPECT_EQ(Error::Canceled, res.error());
  6435. }
  6436. TEST_F(ServerTest, PostLoopBack) {
  6437. std::string body;
  6438. auto res = cli_.Post(
  6439. "/post-loopback", 9,
  6440. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6441. EXPECT_EQ(9u, length);
  6442. sink.write("123", 3);
  6443. sink.write("456", 3);
  6444. sink.write("789", 3);
  6445. return true;
  6446. },
  6447. "text/plain",
  6448. [&body](const char *data, size_t data_length) {
  6449. body.append(data, data_length);
  6450. return true;
  6451. });
  6452. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6453. EXPECT_EQ(StatusCode::OK_200, res->status);
  6454. EXPECT_EQ("123456789", body);
  6455. }
  6456. TEST_F(ServerTest, PutLoopBack) {
  6457. std::string body;
  6458. auto res = cli_.Put(
  6459. "/put-loopback", 9,
  6460. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6461. EXPECT_EQ(9u, length);
  6462. sink.write("123", 3);
  6463. sink.write("456", 3);
  6464. sink.write("789", 3);
  6465. return true;
  6466. },
  6467. "text/plain",
  6468. [&body](const char *data, size_t data_length) {
  6469. body.append(data, data_length);
  6470. return true;
  6471. });
  6472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6473. EXPECT_EQ(StatusCode::OK_200, res->status);
  6474. EXPECT_EQ("123456789", body);
  6475. }
  6476. TEST_F(ServerTest, PatchLoopBack) {
  6477. std::string body;
  6478. auto res = cli_.Patch(
  6479. "/patch-loopback", 9,
  6480. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6481. EXPECT_EQ(9u, length);
  6482. sink.write("123", 3);
  6483. sink.write("456", 3);
  6484. sink.write("789", 3);
  6485. return true;
  6486. },
  6487. "text/plain",
  6488. [&body](const char *data, size_t data_length) {
  6489. body.append(data, data_length);
  6490. return true;
  6491. });
  6492. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6493. EXPECT_EQ(StatusCode::OK_200, res->status);
  6494. EXPECT_EQ("123456789", body);
  6495. }
  6496. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  6497. std::string body;
  6498. auto res = cli_.Post(
  6499. "/post-loopback",
  6500. [](size_t /*offset*/, DataSink &sink) {
  6501. sink.write("123", 3);
  6502. sink.write("456", 3);
  6503. sink.write("789", 3);
  6504. sink.done();
  6505. return true;
  6506. },
  6507. "text/plain",
  6508. [&body](const char *data, size_t data_length) {
  6509. body.append(data, data_length);
  6510. return true;
  6511. });
  6512. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6513. EXPECT_EQ(StatusCode::OK_200, res->status);
  6514. EXPECT_EQ("123456789", body);
  6515. }
  6516. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6517. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  6518. cli_.set_compress(true);
  6519. auto res = cli_.Put(
  6520. "/put", 3,
  6521. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6522. sink.os << "PUT";
  6523. return true;
  6524. },
  6525. "text/plain");
  6526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6527. EXPECT_EQ(StatusCode::OK_200, res->status);
  6528. EXPECT_EQ("PUT", res->body);
  6529. }
  6530. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  6531. cli_.set_compress(true);
  6532. auto res = cli_.Post(
  6533. "/post", 42,
  6534. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6535. return false;
  6536. },
  6537. "text/plain");
  6538. ASSERT_TRUE(!res);
  6539. EXPECT_EQ(Error::Canceled, res.error());
  6540. }
  6541. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  6542. cli_.set_compress(true);
  6543. auto res = cli_.Put(
  6544. "/put",
  6545. [](size_t /*offset*/, DataSink &sink) {
  6546. sink.os << "PUT";
  6547. sink.done();
  6548. return true;
  6549. },
  6550. "text/plain");
  6551. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6552. EXPECT_EQ(StatusCode::OK_200, res->status);
  6553. EXPECT_EQ("PUT", res->body);
  6554. }
  6555. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  6556. cli_.set_compress(true);
  6557. auto res = cli_.Post(
  6558. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6559. "text/plain");
  6560. ASSERT_TRUE(!res);
  6561. EXPECT_EQ(Error::Canceled, res.error());
  6562. }
  6563. TEST_F(ServerTest, PutLargeFileWithGzip) {
  6564. cli_.set_compress(true);
  6565. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6566. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6567. EXPECT_EQ(StatusCode::OK_200, res->status);
  6568. EXPECT_EQ(LARGE_DATA, res->body);
  6569. }
  6570. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  6571. #ifdef CPPHTTPLIB_SSL_ENABLED
  6572. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  6573. Client cli(s.c_str());
  6574. cli.enable_server_certificate_verification(false);
  6575. #else
  6576. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  6577. Client cli(s.c_str());
  6578. #endif
  6579. cli.set_compress(true);
  6580. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  6581. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6582. EXPECT_EQ(StatusCode::OK_200, res->status);
  6583. EXPECT_EQ(LARGE_DATA, res->body);
  6584. // The compressed size should be less than a 10th of the original. May vary
  6585. // depending on the zlib library.
  6586. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  6587. static_cast<uint64_t>(10 * 1024 * 1024));
  6588. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6589. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6590. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  6591. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  6592. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  6593. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  6594. #endif
  6595. }
  6596. TEST_F(ServerTest, PutContentWithDeflate) {
  6597. cli_.set_compress(false);
  6598. Headers headers;
  6599. headers.emplace("Content-Encoding", "deflate");
  6600. // PUT in deflate format:
  6601. auto res = cli_.Put("/put", headers,
  6602. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  6603. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6604. EXPECT_EQ(StatusCode::OK_200, res->status);
  6605. EXPECT_EQ("PUT", res->body);
  6606. }
  6607. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  6608. Headers headers;
  6609. headers.emplace("Accept-Encoding", "gzip, deflate");
  6610. auto res = cli_.Get("/streamed-chunked", headers);
  6611. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6612. EXPECT_EQ(StatusCode::OK_200, res->status);
  6613. EXPECT_EQ(std::string("123456789"), res->body);
  6614. }
  6615. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  6616. Headers headers;
  6617. headers.emplace("Accept-Encoding", "gzip, deflate");
  6618. auto res = cli_.Get("/streamed-chunked2", headers);
  6619. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6620. EXPECT_EQ(StatusCode::OK_200, res->status);
  6621. EXPECT_EQ(std::string("123456789"), res->body);
  6622. }
  6623. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  6624. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  6625. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6626. EXPECT_EQ(StatusCode::OK_200, res->status);
  6627. }
  6628. TEST(GzipDecompressor, ChunkedDecompression) {
  6629. std::string data;
  6630. for (size_t i = 0; i < 32 * 1024; ++i) {
  6631. data.push_back(static_cast<char>('a' + i % 26));
  6632. }
  6633. std::string compressed_data;
  6634. {
  6635. httplib::detail::gzip_compressor compressor;
  6636. bool result = compressor.compress(
  6637. data.data(), data.size(),
  6638. /*last=*/true,
  6639. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  6640. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  6641. compressed_data_size);
  6642. return true;
  6643. });
  6644. ASSERT_TRUE(result);
  6645. }
  6646. std::string decompressed_data;
  6647. {
  6648. httplib::detail::gzip_decompressor decompressor;
  6649. // Chunk size is chosen specifically to have a decompressed chunk size equal
  6650. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  6651. size_t chunk_size = 130;
  6652. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  6653. chunk_begin += chunk_size) {
  6654. size_t current_chunk_size =
  6655. std::min(compressed_data.size() - chunk_begin, chunk_size);
  6656. bool result = decompressor.decompress(
  6657. compressed_data.data() + chunk_begin, current_chunk_size,
  6658. [&](const char *decompressed_data_chunk,
  6659. size_t decompressed_data_chunk_size) {
  6660. decompressed_data.insert(decompressed_data.size(),
  6661. decompressed_data_chunk,
  6662. decompressed_data_chunk_size);
  6663. return true;
  6664. });
  6665. ASSERT_TRUE(result);
  6666. }
  6667. }
  6668. ASSERT_EQ(data, decompressed_data);
  6669. }
  6670. TEST(GzipDecompressor, DeflateDecompression) {
  6671. std::string original_text = "Raw deflate without gzip";
  6672. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6673. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6674. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6675. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  6676. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6677. std::string decompressed_data;
  6678. {
  6679. httplib::detail::gzip_decompressor decompressor;
  6680. bool result = decompressor.decompress(
  6681. compressed_data.data(), compressed_data.size(),
  6682. [&](const char *decompressed_data_chunk,
  6683. size_t decompressed_data_chunk_size) {
  6684. decompressed_data.insert(decompressed_data.size(),
  6685. decompressed_data_chunk,
  6686. decompressed_data_chunk_size);
  6687. return true;
  6688. });
  6689. ASSERT_TRUE(result);
  6690. }
  6691. ASSERT_EQ(original_text, decompressed_data);
  6692. }
  6693. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  6694. std::string original_text = "Raw deflate without gzip";
  6695. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6696. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6697. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6698. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  6699. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  6700. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6701. std::string decompressed_data;
  6702. {
  6703. httplib::detail::gzip_decompressor decompressor;
  6704. bool result = decompressor.decompress(
  6705. compressed_data.data(), compressed_data.size(),
  6706. [&](const char *decompressed_data_chunk,
  6707. size_t decompressed_data_chunk_size) {
  6708. decompressed_data.insert(decompressed_data.size(),
  6709. decompressed_data_chunk,
  6710. decompressed_data_chunk_size);
  6711. return true;
  6712. });
  6713. ASSERT_TRUE(result);
  6714. }
  6715. ASSERT_EQ(original_text, decompressed_data);
  6716. }
  6717. #endif
  6718. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6719. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  6720. Headers headers;
  6721. headers.emplace("Accept-Encoding", "br");
  6722. auto res = cli_.Get("/streamed-chunked", headers);
  6723. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6724. EXPECT_EQ(StatusCode::OK_200, res->status);
  6725. EXPECT_EQ(std::string("123456789"), res->body);
  6726. }
  6727. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  6728. Headers headers;
  6729. headers.emplace("Accept-Encoding", "br");
  6730. auto res = cli_.Get("/streamed-chunked2", headers);
  6731. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6732. EXPECT_EQ(StatusCode::OK_200, res->status);
  6733. EXPECT_EQ(std::string("123456789"), res->body);
  6734. }
  6735. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  6736. cli_.set_compress(true);
  6737. auto res = cli_.Put(
  6738. "/put", 3,
  6739. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6740. sink.os << "PUT";
  6741. return true;
  6742. },
  6743. "text/plain");
  6744. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6745. EXPECT_EQ(StatusCode::OK_200, res->status);
  6746. EXPECT_EQ("PUT", res->body);
  6747. }
  6748. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  6749. cli_.set_compress(true);
  6750. auto res = cli_.Put(
  6751. "/put",
  6752. [](size_t /*offset*/, DataSink &sink) {
  6753. sink.os << "PUT";
  6754. sink.done();
  6755. return true;
  6756. },
  6757. "text/plain");
  6758. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6759. EXPECT_EQ(StatusCode::OK_200, res->status);
  6760. EXPECT_EQ("PUT", res->body);
  6761. }
  6762. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  6763. cli_.set_compress(true);
  6764. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6766. EXPECT_EQ(StatusCode::OK_200, res->status);
  6767. EXPECT_EQ(LARGE_DATA, res->body);
  6768. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6769. }
  6770. #endif
  6771. TEST_F(ServerTest, Patch) {
  6772. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  6773. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6774. EXPECT_EQ(StatusCode::OK_200, res->status);
  6775. EXPECT_EQ("PATCH", res->body);
  6776. }
  6777. TEST_F(ServerTest, Delete) {
  6778. auto res = cli_.Delete("/delete");
  6779. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6780. EXPECT_EQ(StatusCode::OK_200, res->status);
  6781. EXPECT_EQ("DELETE", res->body);
  6782. }
  6783. TEST_F(ServerTest, DeleteContentReceiver) {
  6784. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  6785. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6786. EXPECT_EQ(StatusCode::OK_200, res->status);
  6787. EXPECT_EQ("content", res->body);
  6788. }
  6789. TEST_F(ServerTest, Options) {
  6790. auto res = cli_.Options("*");
  6791. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6792. EXPECT_EQ(StatusCode::OK_200, res->status);
  6793. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  6794. EXPECT_TRUE(res->body.empty());
  6795. }
  6796. TEST_F(ServerTest, URL) {
  6797. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  6798. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6799. EXPECT_EQ(StatusCode::OK_200, res->status);
  6800. }
  6801. TEST_F(ServerTest, ArrayParam) {
  6802. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  6803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6804. EXPECT_EQ(StatusCode::OK_200, res->status);
  6805. }
  6806. TEST_F(ServerTest, ArrayParamValues) {
  6807. auto res =
  6808. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  6809. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6810. EXPECT_EQ(StatusCode::OK_200, res->status);
  6811. }
  6812. TEST_F(ServerTest, NoMultipleHeaders) {
  6813. Headers headers = {{"Content-Length", "5"}};
  6814. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  6815. "text/plain");
  6816. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6817. EXPECT_EQ(StatusCode::OK_200, res->status);
  6818. }
  6819. TEST_F(ServerTest, PostContentReceiver) {
  6820. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  6821. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6822. ASSERT_EQ(StatusCode::OK_200, res->status);
  6823. ASSERT_EQ("content", res->body);
  6824. }
  6825. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  6826. UploadFormDataItems items = {
  6827. {"text1", "text default", "", ""},
  6828. {"text2", "aωb", "", ""},
  6829. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6830. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  6831. {"file3", "", "", "application/octet-stream"},
  6832. };
  6833. auto res = cli_.Post("/content_receiver", items);
  6834. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6835. EXPECT_EQ(StatusCode::OK_200, res->status);
  6836. }
  6837. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  6838. UploadFormDataItems items = {
  6839. {"text1", "text default", "", ""},
  6840. {"text2", "aωb", "", ""},
  6841. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6842. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  6843. {"file3", "", "", "application/octet-stream"},
  6844. };
  6845. auto boundary = std::string("+++++");
  6846. std::string body;
  6847. for (const auto &item : items) {
  6848. body += "--" + boundary + "\r\n";
  6849. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  6850. if (!item.filename.empty()) {
  6851. body += "; filename=\"" + item.filename + "\"";
  6852. }
  6853. body += "\r\n";
  6854. if (!item.content_type.empty()) {
  6855. body += "Content-Type: " + item.content_type + "\r\n";
  6856. }
  6857. body += "\r\n";
  6858. body += item.content + "\r\n";
  6859. }
  6860. body += "--" + boundary + "--\r\n";
  6861. std::string content_type = "multipart/form-data; boundary=" + boundary;
  6862. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  6863. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6864. EXPECT_EQ(StatusCode::OK_200, res->status);
  6865. }
  6866. TEST(MultipartFormDataTest, FieldEscaping) {
  6867. Server svr;
  6868. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  6869. const ContentReader &content_reader) {
  6870. ASSERT_TRUE(req.is_multipart_form_data());
  6871. std::vector<FormData> received;
  6872. content_reader(
  6873. [&](const FormData &file) {
  6874. received.push_back(file);
  6875. return true;
  6876. },
  6877. [&](const char *data, size_t data_length) {
  6878. received.back().content.append(data, data_length);
  6879. return true;
  6880. });
  6881. // '"', CR and LF in names and filenames are escaped following the
  6882. // WHATWG HTML standard, so each part still parses as a single part
  6883. // with no injected headers. Content types get CR/LF escaped too,
  6884. // while '"' (legal there, e.g. quoted charset) is preserved.
  6885. ASSERT_EQ(4U, received.size());
  6886. EXPECT_EQ("na%22me", received[0].name);
  6887. EXPECT_EQ("quoted name", received[0].content);
  6888. EXPECT_EQ("file", received[1].name);
  6889. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  6890. received[1].filename);
  6891. EXPECT_EQ("application/octet-stream", received[1].content_type);
  6892. EXPECT_EQ("injected", received[1].content);
  6893. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  6894. EXPECT_EQ("my%22file.txt", received[2].filename);
  6895. EXPECT_EQ("cr lf name", received[2].content);
  6896. EXPECT_EQ("typed", received[3].name);
  6897. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  6898. received[3].content_type);
  6899. EXPECT_EQ("typed content", received[3].content);
  6900. });
  6901. auto port = svr.bind_to_any_port("localhost");
  6902. auto t = std::thread([&]() { svr.listen_after_bind(); });
  6903. auto se = detail::scope_exit([&] {
  6904. svr.stop();
  6905. t.join();
  6906. ASSERT_FALSE(svr.is_running());
  6907. });
  6908. svr.wait_until_ready();
  6909. Client cli("localhost", port);
  6910. UploadFormDataItems items = {
  6911. {"na\"me", "quoted name", "", ""},
  6912. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  6913. "application/octet-stream"},
  6914. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  6915. {"typed", "typed content", "",
  6916. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  6917. };
  6918. auto res = cli.Post("/post", items);
  6919. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6920. EXPECT_EQ(StatusCode::OK_200, res->status);
  6921. }
  6922. TEST(MultipartFormDataTest, PublicWriterAPI) {
  6923. const UploadFormDataItems items = {
  6924. {"name1", "Content 1", "", ""},
  6925. {"name2", "Content 2", "file2.txt", "text/plain"},
  6926. };
  6927. Server svr;
  6928. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  6929. const ContentReader &content_reader) {
  6930. ASSERT_TRUE(req.is_multipart_form_data());
  6931. std::vector<FormData> received;
  6932. content_reader(
  6933. [&](const FormData &file) {
  6934. received.push_back(file);
  6935. return true;
  6936. },
  6937. [&](const char *data, size_t data_length) {
  6938. received.back().content.append(data, data_length);
  6939. return true;
  6940. });
  6941. ASSERT_EQ(2U, received.size());
  6942. EXPECT_EQ("name1", received[0].name);
  6943. EXPECT_EQ("Content 1", received[0].content);
  6944. EXPECT_EQ("name2", received[1].name);
  6945. EXPECT_EQ("Content 2", received[1].content);
  6946. EXPECT_EQ("file2.txt", received[1].filename);
  6947. EXPECT_EQ("text/plain", received[1].content_type);
  6948. });
  6949. auto port = svr.bind_to_any_port("localhost");
  6950. auto t = std::thread([&]() { svr.listen_after_bind(); });
  6951. auto se = detail::scope_exit([&] {
  6952. svr.stop();
  6953. t.join();
  6954. ASSERT_FALSE(svr.is_running());
  6955. });
  6956. svr.wait_until_ready();
  6957. Client cli("localhost", port);
  6958. // Whole-body serialization with a generated boundary
  6959. {
  6960. MultipartFormDataWriter writer;
  6961. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  6962. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  6963. writer.content_type());
  6964. auto body = writer.serialize(items);
  6965. EXPECT_EQ(body.size(), writer.content_length(items));
  6966. auto res = cli.Post("/post", body, writer.content_type());
  6967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6968. EXPECT_EQ(StatusCode::OK_200, res->status);
  6969. }
  6970. // Per-part framing with a custom boundary via a content provider
  6971. {
  6972. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  6973. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  6974. MultipartFormDataWriter writer("custom-boundary_123");
  6975. EXPECT_EQ("custom-boundary_123", writer.boundary());
  6976. std::string body;
  6977. for (const auto &item : items) {
  6978. body += writer.item_begin(item);
  6979. body += item.content;
  6980. body += MultipartFormDataWriter::item_end();
  6981. }
  6982. body += writer.finish();
  6983. EXPECT_EQ(body.size(), writer.content_length(items));
  6984. auto res = cli.Post(
  6985. "/post", body.size(),
  6986. [&](size_t offset, size_t length, DataSink &sink) {
  6987. sink.write(body.data() + offset, length);
  6988. return true;
  6989. },
  6990. writer.content_type());
  6991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6992. EXPECT_EQ(StatusCode::OK_200, res->status);
  6993. }
  6994. }
  6995. TEST_F(ServerTest, PostContentReceiverGzip) {
  6996. cli_.set_compress(true);
  6997. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  6998. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6999. ASSERT_EQ(StatusCode::OK_200, res->status);
  7000. ASSERT_EQ("content", res->body);
  7001. }
  7002. TEST_F(ServerTest, PutContentReceiver) {
  7003. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  7004. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7005. ASSERT_EQ(StatusCode::OK_200, res->status);
  7006. ASSERT_EQ("content", res->body);
  7007. }
  7008. TEST_F(ServerTest, PatchContentReceiver) {
  7009. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  7010. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7011. ASSERT_EQ(StatusCode::OK_200, res->status);
  7012. ASSERT_EQ("content", res->body);
  7013. }
  7014. template <typename ClientType>
  7015. void TestWithHeadersAndContentReceiver(
  7016. ClientType &cli,
  7017. std::function<Result(ClientType &, const std::string &, const Headers &,
  7018. const std::string &, const std::string &,
  7019. ContentReceiver, DownloadProgress)>
  7020. request_func) {
  7021. Headers headers;
  7022. headers.emplace("X-Custom-Header", "test-value");
  7023. std::string received_body;
  7024. auto res = request_func(
  7025. cli, "/content_receiver", headers, "content", "application/json",
  7026. [&](const char *data, size_t data_length) {
  7027. received_body.append(data, data_length);
  7028. return true;
  7029. },
  7030. nullptr);
  7031. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7032. EXPECT_EQ(StatusCode::OK_200, res->status);
  7033. EXPECT_EQ("content", received_body);
  7034. }
  7035. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  7036. #ifdef CPPHTTPLIB_SSL_ENABLED
  7037. using ClientT = SSLClient;
  7038. #else
  7039. using ClientT = Client;
  7040. #endif
  7041. TestWithHeadersAndContentReceiver<ClientT>(
  7042. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7043. const std::string &body, const std::string &content_type,
  7044. ContentReceiver receiver, DownloadProgress progress) {
  7045. return cli.Post(path, headers, body, content_type, receiver, progress);
  7046. });
  7047. }
  7048. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  7049. #ifdef CPPHTTPLIB_SSL_ENABLED
  7050. using ClientT = SSLClient;
  7051. #else
  7052. using ClientT = Client;
  7053. #endif
  7054. TestWithHeadersAndContentReceiver<ClientT>(
  7055. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7056. const std::string &body, const std::string &content_type,
  7057. ContentReceiver receiver, DownloadProgress progress) {
  7058. return cli.Put(path, headers, body, content_type, receiver, progress);
  7059. });
  7060. }
  7061. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  7062. #ifdef CPPHTTPLIB_SSL_ENABLED
  7063. using ClientT = SSLClient;
  7064. #else
  7065. using ClientT = Client;
  7066. #endif
  7067. TestWithHeadersAndContentReceiver<ClientT>(
  7068. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7069. const std::string &body, const std::string &content_type,
  7070. ContentReceiver receiver, DownloadProgress progress) {
  7071. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7072. });
  7073. }
  7074. template <typename ClientType>
  7075. void TestWithHeadersAndContentReceiverWithProgress(
  7076. ClientType &cli,
  7077. std::function<Result(ClientType &, const std::string &, const Headers &,
  7078. const std::string &, const std::string &,
  7079. ContentReceiver, DownloadProgress)>
  7080. request_func) {
  7081. Headers headers;
  7082. headers.emplace("X-Test-Header", "progress-test");
  7083. std::string received_body;
  7084. auto progress_called = false;
  7085. auto res = request_func(
  7086. cli, "/content_receiver", headers, "content", "text/plain",
  7087. [&](const char *data, size_t data_length) {
  7088. received_body.append(data, data_length);
  7089. return true;
  7090. },
  7091. [&](uint64_t /*current*/, uint64_t /*total*/) {
  7092. progress_called = true;
  7093. return true;
  7094. });
  7095. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7096. EXPECT_EQ(StatusCode::OK_200, res->status);
  7097. EXPECT_EQ("content", received_body);
  7098. EXPECT_TRUE(progress_called);
  7099. }
  7100. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  7101. #ifdef CPPHTTPLIB_SSL_ENABLED
  7102. using ClientT = SSLClient;
  7103. #else
  7104. using ClientT = Client;
  7105. #endif
  7106. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7107. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7108. const std::string &body, const std::string &content_type,
  7109. ContentReceiver receiver, DownloadProgress progress) {
  7110. return cli.Post(path, headers, body, content_type, receiver, progress);
  7111. });
  7112. }
  7113. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  7114. #ifdef CPPHTTPLIB_SSL_ENABLED
  7115. using ClientT = SSLClient;
  7116. #else
  7117. using ClientT = Client;
  7118. #endif
  7119. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7120. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7121. const std::string &body, const std::string &content_type,
  7122. ContentReceiver receiver, DownloadProgress progress) {
  7123. return cli.Put(path, headers, body, content_type, receiver, progress);
  7124. });
  7125. }
  7126. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  7127. #ifdef CPPHTTPLIB_SSL_ENABLED
  7128. using ClientT = SSLClient;
  7129. #else
  7130. using ClientT = Client;
  7131. #endif
  7132. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7133. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7134. const std::string &body, const std::string &content_type,
  7135. ContentReceiver receiver, DownloadProgress progress) {
  7136. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7137. });
  7138. }
  7139. template <typename ClientType>
  7140. void TestWithHeadersAndContentReceiverError(
  7141. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  7142. const Headers &, const std::string &,
  7143. const std::string &, ContentReceiver)>
  7144. request_func) {
  7145. Headers headers;
  7146. headers.emplace("X-Error-Test", "true");
  7147. std::string received_body;
  7148. auto receiver_failed = false;
  7149. auto res =
  7150. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  7151. [&](const char *data, size_t data_length) {
  7152. received_body.append(data, data_length);
  7153. receiver_failed = true;
  7154. return false;
  7155. });
  7156. ASSERT_FALSE(res);
  7157. EXPECT_TRUE(receiver_failed);
  7158. }
  7159. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  7160. #ifdef CPPHTTPLIB_SSL_ENABLED
  7161. using ClientT = SSLClient;
  7162. #else
  7163. using ClientT = Client;
  7164. #endif
  7165. TestWithHeadersAndContentReceiverError<ClientT>(
  7166. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7167. const std::string &body, const std::string &content_type,
  7168. ContentReceiver receiver) {
  7169. return cli.Post(path, headers, body, content_type, receiver);
  7170. });
  7171. }
  7172. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  7173. #ifdef CPPHTTPLIB_SSL_ENABLED
  7174. using ClientT = SSLClient;
  7175. #else
  7176. using ClientT = Client;
  7177. #endif
  7178. TestWithHeadersAndContentReceiverError<ClientT>(
  7179. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7180. const std::string &body, const std::string &content_type,
  7181. ContentReceiver receiver) {
  7182. return cli.Put(path, headers, body, content_type, receiver);
  7183. });
  7184. }
  7185. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  7186. #ifdef CPPHTTPLIB_SSL_ENABLED
  7187. using ClientT = SSLClient;
  7188. #else
  7189. using ClientT = Client;
  7190. #endif
  7191. TestWithHeadersAndContentReceiverError<ClientT>(
  7192. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7193. const std::string &body, const std::string &content_type,
  7194. ContentReceiver receiver) {
  7195. return cli.Patch(path, headers, body, content_type, receiver);
  7196. });
  7197. }
  7198. TEST_F(ServerTest, PostQueryStringAndBody) {
  7199. auto res =
  7200. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  7201. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7202. ASSERT_EQ(StatusCode::OK_200, res->status);
  7203. }
  7204. TEST_F(ServerTest, HTTP2Magic) {
  7205. Request req;
  7206. req.method = "PRI";
  7207. req.path = "*";
  7208. req.body = "SM";
  7209. auto res = std::make_shared<Response>();
  7210. auto error = Error::Success;
  7211. auto ret = cli_.send(req, *res, error);
  7212. ASSERT_TRUE(ret);
  7213. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7214. }
  7215. TEST_F(ServerTest, KeepAlive) {
  7216. auto res = cli_.Get("/hi");
  7217. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7218. EXPECT_EQ(StatusCode::OK_200, res->status);
  7219. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7220. EXPECT_EQ("Hello World!", res->body);
  7221. res = cli_.Get("/hi");
  7222. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7223. EXPECT_EQ(StatusCode::OK_200, res->status);
  7224. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7225. EXPECT_EQ("Hello World!", res->body);
  7226. res = cli_.Get("/hi");
  7227. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7228. EXPECT_EQ(StatusCode::OK_200, res->status);
  7229. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7230. EXPECT_EQ("Hello World!", res->body);
  7231. res = cli_.Get("/not-exist");
  7232. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7233. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7234. res = cli_.Post("/empty", "", "text/plain");
  7235. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7236. EXPECT_EQ(StatusCode::OK_200, res->status);
  7237. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7238. EXPECT_EQ("empty", res->body);
  7239. EXPECT_EQ("close", res->get_header_value("Connection"));
  7240. res = cli_.Post(
  7241. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  7242. "text/plain");
  7243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7244. EXPECT_EQ(StatusCode::OK_200, res->status);
  7245. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7246. EXPECT_EQ("empty", res->body);
  7247. cli_.set_keep_alive(false);
  7248. res = cli_.Get("/last-request");
  7249. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7250. EXPECT_EQ(StatusCode::OK_200, res->status);
  7251. EXPECT_EQ("close", res->get_header_value("Connection"));
  7252. }
  7253. TEST_F(ServerTest, TooManyRedirect) {
  7254. cli_.set_follow_location(true);
  7255. auto res = cli_.Get("/redirect/0");
  7256. ASSERT_TRUE(!res);
  7257. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  7258. }
  7259. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  7260. Request req;
  7261. req.method = "FOOBAR";
  7262. req.path = "/hi";
  7263. cli_.set_keep_alive(true);
  7264. auto res = cli_.send(req);
  7265. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7266. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7267. EXPECT_EQ("close", res->get_header_value("Connection"));
  7268. EXPECT_FALSE(cli_.is_socket_open());
  7269. }
  7270. TEST_F(ServerTest, CustomRouteReadsBody) {
  7271. const std::string xml =
  7272. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  7273. Request req;
  7274. req.method = "PROPFIND";
  7275. req.path = "/dav/dir";
  7276. req.set_header("Depth", "1");
  7277. req.body = xml;
  7278. auto res = cli_.send(req);
  7279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7280. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7281. EXPECT_EQ(xml, res->body);
  7282. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  7283. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  7284. }
  7285. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  7286. Request req;
  7287. req.method = "PROPFIND";
  7288. req.path = "/dav/42";
  7289. auto res = cli_.send(req);
  7290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7291. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7292. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  7293. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  7294. }
  7295. TEST_F(ServerTest, CustomRouteRegexPattern) {
  7296. Request req;
  7297. req.method = "PROPFIND";
  7298. req.path = "/dav-re/123";
  7299. auto res = cli_.send(req);
  7300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7301. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7302. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  7303. }
  7304. TEST_F(ServerTest, CustomRouteWithoutBody) {
  7305. Request req;
  7306. req.method = "MKCOL";
  7307. req.path = "/dav-mkcol";
  7308. auto res = cli_.send(req);
  7309. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7310. EXPECT_EQ(StatusCode::Created_201, res->status);
  7311. }
  7312. TEST_F(ServerTest, CustomRouteWithContentReader) {
  7313. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  7314. Request req;
  7315. req.method = "REPORT";
  7316. req.path = "/dav-report";
  7317. req.body = xml;
  7318. auto res = cli_.send(req);
  7319. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7320. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7321. EXPECT_EQ(xml, res->body);
  7322. }
  7323. // A content reader route must fire even when the request carries no body,
  7324. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  7325. // Without that, a body-less PROPFIND-style request would fall through to 404.
  7326. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  7327. Request req;
  7328. req.method = "REPORT";
  7329. req.path = "/dav-report";
  7330. auto res = cli_.send(req);
  7331. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7332. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7333. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  7334. }
  7335. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  7336. Request req;
  7337. req.method = "PROPFIND";
  7338. req.path = "/not-dav";
  7339. auto res = cli_.send(req);
  7340. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7341. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7342. }
  7343. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  7344. Request req;
  7345. req.method = "UNLOCK";
  7346. req.path = "/dav/dir";
  7347. cli_.set_keep_alive(true);
  7348. auto res = cli_.send(req);
  7349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7350. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7351. EXPECT_EQ("close", res->get_header_value("Connection"));
  7352. EXPECT_FALSE(cli_.is_socket_open());
  7353. }
  7354. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  7355. // The mount point serves this path, but only for GET and HEAD.
  7356. auto get_res = cli_.Get("/dir/index.html");
  7357. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  7358. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  7359. Request req;
  7360. req.method = "PROPFIND";
  7361. req.path = "/dir/index.html";
  7362. auto res = cli_.send(req);
  7363. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7364. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7365. }
  7366. TEST_F(ServerTest, CustomRouteKeepAlive) {
  7367. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7368. cli_.set_keep_alive(true);
  7369. for (auto i = 0; i < 2; i++) {
  7370. Request req;
  7371. req.method = "PROPFIND";
  7372. req.path = "/dav/dir";
  7373. req.body = xml;
  7374. auto res = cli_.send(req);
  7375. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7376. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7377. EXPECT_EQ(xml, res->body);
  7378. EXPECT_TRUE(cli_.is_socket_open());
  7379. }
  7380. // A built-in method must still be served on the same connection.
  7381. cli_.set_keep_alive(false);
  7382. auto res = cli_.Get("/hi");
  7383. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7384. EXPECT_EQ(StatusCode::OK_200, res->status);
  7385. EXPECT_EQ("close", res->get_header_value("Connection"));
  7386. }
  7387. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  7388. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7389. Request req;
  7390. req.method = "PROPFIND";
  7391. req.path = "/dav/dir";
  7392. req.set_header("Expect", "100-continue");
  7393. req.body = xml;
  7394. auto res = cli_.send(req);
  7395. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7396. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7397. EXPECT_EQ(xml, res->body);
  7398. }
  7399. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  7400. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7401. TEST_F(ServerTest, Gzip) {
  7402. Headers headers;
  7403. headers.emplace("Accept-Encoding", "gzip, deflate");
  7404. auto res = cli_.Get("/compress", headers);
  7405. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7406. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7407. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7408. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7409. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7410. "7890123456789012345678901234567890",
  7411. res->body);
  7412. EXPECT_EQ(StatusCode::OK_200, res->status);
  7413. }
  7414. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  7415. Headers headers;
  7416. headers.emplace("Accept-Encoding", "gzip, deflate");
  7417. auto res = cli_.Get("/compress-with-charset", headers);
  7418. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7419. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7420. EXPECT_EQ("application/json; charset=utf-8",
  7421. res->get_header_value("Content-Type"));
  7422. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7423. "7890123456789012345678901234567890",
  7424. res->body);
  7425. EXPECT_EQ(StatusCode::OK_200, res->status);
  7426. }
  7427. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  7428. Headers headers;
  7429. headers.emplace("Accept-Encoding", "");
  7430. auto res = cli_.Get("/compress", headers);
  7431. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7432. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7433. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7434. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7435. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7436. "7890123456789012345678901234567890",
  7437. res->body);
  7438. EXPECT_EQ(StatusCode::OK_200, res->status);
  7439. }
  7440. TEST_F(ServerTest, GzipWithContentReceiver) {
  7441. Headers headers;
  7442. headers.emplace("Accept-Encoding", "gzip, deflate");
  7443. std::string body;
  7444. auto res = cli_.Get("/compress", headers,
  7445. [&](const char *data, uint64_t data_length) {
  7446. EXPECT_EQ(100U, data_length);
  7447. body.append(data, data_length);
  7448. return true;
  7449. });
  7450. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7451. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7452. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7453. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7454. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7455. "7890123456789012345678901234567890",
  7456. body);
  7457. EXPECT_EQ(StatusCode::OK_200, res->status);
  7458. }
  7459. TEST_F(ServerTest, GzipWithoutDecompressing) {
  7460. Headers headers;
  7461. headers.emplace("Accept-Encoding", "gzip, deflate");
  7462. cli_.set_decompress(false);
  7463. auto res = cli_.Get("/compress", headers);
  7464. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7465. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7466. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7467. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7468. EXPECT_EQ(33U, res->body.size());
  7469. EXPECT_EQ(StatusCode::OK_200, res->status);
  7470. }
  7471. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  7472. Headers headers;
  7473. headers.emplace("Accept-Encoding", "");
  7474. std::string body;
  7475. auto res = cli_.Get("/compress", headers,
  7476. [&](const char *data, uint64_t data_length) {
  7477. EXPECT_EQ(100U, data_length);
  7478. body.append(data, data_length);
  7479. return true;
  7480. });
  7481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7482. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7483. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7484. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7485. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7486. "7890123456789012345678901234567890",
  7487. body);
  7488. EXPECT_EQ(StatusCode::OK_200, res->status);
  7489. }
  7490. TEST_F(ServerTest, NoGzip) {
  7491. Headers headers;
  7492. headers.emplace("Accept-Encoding", "gzip, deflate");
  7493. auto res = cli_.Get("/nocompress", headers);
  7494. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7495. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7496. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7497. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7498. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7499. "7890123456789012345678901234567890",
  7500. res->body);
  7501. EXPECT_EQ(StatusCode::OK_200, res->status);
  7502. }
  7503. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  7504. Headers headers;
  7505. headers.emplace("Accept-Encoding", "gzip, deflate");
  7506. std::string body;
  7507. auto res = cli_.Get("/nocompress", headers,
  7508. [&](const char *data, uint64_t data_length) {
  7509. EXPECT_EQ(100U, data_length);
  7510. body.append(data, data_length);
  7511. return true;
  7512. });
  7513. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7514. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7515. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7516. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7517. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7518. "7890123456789012345678901234567890",
  7519. body);
  7520. EXPECT_EQ(StatusCode::OK_200, res->status);
  7521. }
  7522. TEST_F(ServerTest, MultipartFormDataGzip) {
  7523. UploadFormDataItems items = {
  7524. {"key1", "test", "", ""},
  7525. {"key2", "--abcdefg123", "", ""},
  7526. };
  7527. cli_.set_compress(true);
  7528. auto res = cli_.Post("/compress-multipart", items);
  7529. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7530. EXPECT_EQ(StatusCode::OK_200, res->status);
  7531. }
  7532. #endif
  7533. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7534. // Static file compression is opt-in, so these run their own server rather than
  7535. // flipping it on for the shared ServerTest fixture, which would silently
  7536. // rewrite what every other static file test is asserting.
  7537. class StaticFileCompressionTest : public ::testing::Test {
  7538. protected:
  7539. void TearDown() override {
  7540. if (t_.joinable()) {
  7541. svr_.stop();
  7542. t_.join();
  7543. }
  7544. }
  7545. int start(const std::function<void(Server &)> &configure = nullptr) {
  7546. // Serves the same tree as a directory of build-time compressed assets
  7547. // would be served: the mount point names the coding the files are already
  7548. // stored in. Registered before "/" so it is the one that matches.
  7549. svr_.set_mount_point("/pre-encoded", "./www",
  7550. {{"Content-Encoding", "gzip"}});
  7551. svr_.set_mount_point("/", "./www");
  7552. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  7553. res.set_file_content("./www/dir/index.html", "text/html");
  7554. });
  7555. svr_.Get("/pre-encoded-file-content",
  7556. [](const Request & /*req*/, Response &res) {
  7557. res.set_header("Content-Encoding", "gzip");
  7558. res.set_file_content("./www/dir/index.html", "text/html");
  7559. });
  7560. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  7561. res.set_content_provider(
  7562. 6, "text/plain",
  7563. [](size_t offset, size_t /*length*/, DataSink &sink) {
  7564. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  7565. return true;
  7566. });
  7567. });
  7568. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  7569. res.set_content_provider(
  7570. 1000, "text/plain",
  7571. [](size_t offset, size_t /*length*/, DataSink &sink) {
  7572. if (offset < 100) {
  7573. std::string data(100, 'A');
  7574. sink.write(data.data(), data.size());
  7575. return true;
  7576. }
  7577. std::this_thread::sleep_for(std::chrono::seconds(2));
  7578. std::string data(900, 'B');
  7579. sink.write(data.data(), data.size());
  7580. return true;
  7581. });
  7582. });
  7583. if (configure) { configure(svr_); }
  7584. auto port = svr_.bind_to_any_port(HOST);
  7585. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  7586. svr_.wait_until_ready();
  7587. return port;
  7588. }
  7589. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  7590. // Every file under ./www except 1MB.txt is smaller than the default
  7591. // 1400-byte floor, so a test that needs a small file compressed has to lower
  7592. // it out of the way.
  7593. static void enable_without_floor(Server &svr) {
  7594. svr.set_static_file_compression(true);
  7595. svr.set_static_file_compression_min_length(0);
  7596. }
  7597. Server svr_;
  7598. std::thread t_;
  7599. };
  7600. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  7601. auto port = start();
  7602. Client cli(HOST, port);
  7603. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7604. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7605. EXPECT_EQ(StatusCode::OK_200, res->status);
  7606. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7607. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  7608. EXPECT_EQ(1048576U, res->body.size());
  7609. }
  7610. TEST_F(StaticFileCompressionTest, MountPoint) {
  7611. auto port = start(enable);
  7612. Client cli(HOST, port);
  7613. cli.set_decompress(false);
  7614. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7615. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7616. EXPECT_EQ(StatusCode::OK_200, res->status);
  7617. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7618. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7619. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  7620. // The response stays self-delimiting: a length, not a chunked body.
  7621. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  7622. EXPECT_EQ(std::to_string(res->body.size()),
  7623. res->get_header_value("Content-Length"));
  7624. EXPECT_LT(res->body.size(), 1048576U);
  7625. EXPECT_FALSE(res->body.empty());
  7626. }
  7627. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  7628. auto port = start(enable);
  7629. Client cli(HOST, port);
  7630. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7632. EXPECT_EQ(StatusCode::OK_200, res->status);
  7633. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7634. EXPECT_EQ(1048576U, res->body.size());
  7635. }
  7636. TEST_F(StaticFileCompressionTest, FileContent) {
  7637. auto port = start(enable_without_floor);
  7638. Client cli(HOST, port);
  7639. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  7640. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7641. EXPECT_EQ(StatusCode::OK_200, res->status);
  7642. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  7643. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7644. EXPECT_EQ(104U, res->body.size());
  7645. }
  7646. // A handler that serves an already-encoded file names the coding itself. The
  7647. // file-backed path decided its coding from Accept-Encoding and the content
  7648. // type alone, so it compressed the stored bytes a second time and appended a
  7649. // second Content-Encoding field line.
  7650. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  7651. auto port = start(enable_without_floor);
  7652. Client cli(HOST, port);
  7653. cli.set_decompress(false);
  7654. auto res = cli.Get("/pre-encoded-file-content",
  7655. Headers{{"Accept-Encoding", "gzip"}});
  7656. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7657. EXPECT_EQ(StatusCode::OK_200, res->status);
  7658. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  7659. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7660. // Vary belongs to a coding the server chose, and it chose none here.
  7661. EXPECT_FALSE(res->has_header("Vary"));
  7662. // The file travels exactly as it is stored on disk.
  7663. EXPECT_EQ(104U, res->body.size());
  7664. }
  7665. // The 1MB file clears the default floor, so this one runs the configuration a
  7666. // deployment would actually have.
  7667. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  7668. auto port = start(enable);
  7669. Client cli(HOST, port);
  7670. cli.set_decompress(false);
  7671. auto res =
  7672. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7674. EXPECT_EQ(StatusCode::OK_200, res->status);
  7675. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  7676. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7677. EXPECT_FALSE(res->has_header("Vary"));
  7678. EXPECT_EQ(1048576U, res->body.size());
  7679. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  7680. }
  7681. TEST_F(StaticFileCompressionTest, Head) {
  7682. auto port = start(enable);
  7683. Client cli(HOST, port);
  7684. cli.set_decompress(false);
  7685. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7686. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  7687. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7688. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7689. EXPECT_EQ(StatusCode::OK_200, res->status);
  7690. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7691. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  7692. // HEAD still reports the size a GET would return.
  7693. EXPECT_EQ(get->get_header_value("Content-Length"),
  7694. res->get_header_value("Content-Length"));
  7695. EXPECT_TRUE(res->body.empty());
  7696. }
  7697. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  7698. auto port = start(enable);
  7699. Client cli(HOST, port);
  7700. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  7701. {"Accept-Encoding", "gzip"}});
  7702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7703. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7704. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7705. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7706. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  7707. EXPECT_EQ("cd", res->body);
  7708. }
  7709. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  7710. auto port = start(enable);
  7711. Client cli(HOST, port);
  7712. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  7713. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7714. EXPECT_EQ(StatusCode::OK_200, res->status);
  7715. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7716. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7717. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  7718. }
  7719. TEST_F(StaticFileCompressionTest, EmptyFile) {
  7720. auto port = start(enable);
  7721. Client cli(HOST, port);
  7722. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  7723. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7724. EXPECT_EQ(StatusCode::OK_200, res->status);
  7725. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7726. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7727. EXPECT_TRUE(res->body.empty());
  7728. }
  7729. TEST_F(StaticFileCompressionTest, MinLength) {
  7730. auto port = start(enable);
  7731. Client cli(HOST, port);
  7732. // 104 bytes, well under the default floor. Compressing it would add the
  7733. // gzip header and trailer to a body that already fits in one packet.
  7734. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  7735. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7736. EXPECT_EQ(StatusCode::OK_200, res->status);
  7737. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7738. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  7739. }
  7740. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  7741. auto port = start([](Server &svr) {
  7742. svr.set_static_file_compression(true);
  7743. svr.set_static_file_compression_min_length(1);
  7744. });
  7745. Client cli(HOST, port);
  7746. cli.set_decompress(false);
  7747. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  7748. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7749. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7750. // A 9-byte file comes back larger than it went in, because gzip's header and
  7751. // trailer outweigh anything deflate can save. That is the end of the range
  7752. // the floor exists to keep out.
  7753. EXPECT_GT(res->body.size(), 9U);
  7754. }
  7755. TEST_F(StaticFileCompressionTest, MaxLength) {
  7756. auto port = start([](Server &svr) {
  7757. svr.set_static_file_compression(true);
  7758. svr.set_static_file_compression_min_length(0);
  7759. svr.set_static_file_compression_max_length(1024);
  7760. });
  7761. Client cli(HOST, port);
  7762. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  7763. // defines `small` as a macro on Windows.
  7764. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7765. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  7766. EXPECT_FALSE(over->has_header("Content-Encoding"));
  7767. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  7768. // Under it: compressed.
  7769. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  7770. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  7771. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  7772. }
  7773. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  7774. auto port = start(enable_without_floor);
  7775. Client cli(HOST, port);
  7776. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  7777. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  7778. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  7779. auto identity_etag = identity->get_header_value("ETag");
  7780. ASSERT_FALSE(identity_etag.empty());
  7781. auto gzipped =
  7782. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  7783. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  7784. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  7785. auto gzip_etag = gzipped->get_header_value("ETag");
  7786. ASSERT_FALSE(gzip_etag.empty());
  7787. // Two representations, two validators.
  7788. EXPECT_NE(identity_etag, gzip_etag);
  7789. // Each one revalidates against the request that would produce it...
  7790. auto fresh =
  7791. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  7792. {"If-None-Match", gzip_etag}});
  7793. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  7794. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  7795. auto fresh_identity =
  7796. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  7797. {"If-None-Match", identity_etag}});
  7798. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  7799. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  7800. // ...and not against the other representation.
  7801. auto crossed =
  7802. cli.Get("/dir/index.html",
  7803. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  7804. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  7805. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  7806. }
  7807. // The opt-in covers responses the server reads off disk itself. A caller's own
  7808. // known-length provider keeps its Content-Length and, more importantly, keeps
  7809. // delivering incrementally: routing it through a compressor would hold every
  7810. // write back until zlib's window filled.
  7811. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  7812. auto port = start(enable);
  7813. Client cli(HOST, port);
  7814. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  7815. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7816. EXPECT_EQ(StatusCode::OK_200, res->status);
  7817. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7818. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7819. EXPECT_EQ("aaabbb", res->body);
  7820. }
  7821. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  7822. auto port = start(enable);
  7823. Client cli(HOST, port);
  7824. cli.set_read_timeout(1, 0);
  7825. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  7826. Headers{{"Accept-Encoding", "gzip"}});
  7827. ASSERT_TRUE(handle.is_valid());
  7828. // The provider writes 100 bytes and then stalls for longer than the read
  7829. // timeout. Those first bytes have to arrive anyway: run the response through
  7830. // a compressor and zlib holds them until its window fills, so the read would
  7831. // come back empty instead.
  7832. char buf[256];
  7833. auto n = handle.read(buf, sizeof(buf));
  7834. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  7835. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  7836. }
  7837. #endif
  7838. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7839. TEST_F(ServerTest, Brotli) {
  7840. Headers headers;
  7841. headers.emplace("Accept-Encoding", "br");
  7842. auto res = cli_.Get("/compress", headers);
  7843. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7844. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  7845. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7846. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  7847. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7848. "7890123456789012345678901234567890",
  7849. res->body);
  7850. EXPECT_EQ(StatusCode::OK_200, res->status);
  7851. }
  7852. #endif
  7853. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  7854. TEST_F(ServerTest, Zstd) {
  7855. Headers headers;
  7856. headers.emplace("Accept-Encoding", "zstd");
  7857. auto res = cli_.Get("/compress", headers);
  7858. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7859. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  7860. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7861. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  7862. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7863. "7890123456789012345678901234567890",
  7864. res->body);
  7865. EXPECT_EQ(StatusCode::OK_200, res->status);
  7866. }
  7867. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  7868. Headers headers;
  7869. headers.emplace("Accept-Encoding", "");
  7870. auto res = cli_.Get("/compress", headers);
  7871. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7872. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7873. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7874. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7875. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7876. "7890123456789012345678901234567890",
  7877. res->body);
  7878. EXPECT_EQ(StatusCode::OK_200, res->status);
  7879. }
  7880. TEST_F(ServerTest, ZstdWithContentReceiver) {
  7881. Headers headers;
  7882. headers.emplace("Accept-Encoding", "zstd");
  7883. std::string body;
  7884. auto res = cli_.Get("/compress", headers,
  7885. [&](const char *data, uint64_t data_length) {
  7886. EXPECT_EQ(100U, data_length);
  7887. body.append(data, data_length);
  7888. return true;
  7889. });
  7890. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7891. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  7892. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7893. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  7894. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7895. "7890123456789012345678901234567890",
  7896. body);
  7897. EXPECT_EQ(StatusCode::OK_200, res->status);
  7898. }
  7899. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  7900. Headers headers;
  7901. headers.emplace("Accept-Encoding", "zstd");
  7902. cli_.set_decompress(false);
  7903. auto res = cli_.Get("/compress", headers);
  7904. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  7905. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  7906. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  7907. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  7908. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7909. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  7910. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7911. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  7912. EXPECT_EQ(StatusCode::OK_200, res->status);
  7913. ASSERT_EQ(26U, res->body.size());
  7914. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  7915. 0);
  7916. }
  7917. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  7918. Headers headers;
  7919. headers.emplace("Accept-Encoding", "");
  7920. std::string body;
  7921. auto res = cli_.Get("/compress", headers,
  7922. [&](const char *data, uint64_t data_length) {
  7923. EXPECT_EQ(100U, data_length);
  7924. body.append(data, data_length);
  7925. return true;
  7926. });
  7927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7928. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7929. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7930. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7931. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7932. "7890123456789012345678901234567890",
  7933. body);
  7934. EXPECT_EQ(StatusCode::OK_200, res->status);
  7935. }
  7936. TEST_F(ServerTest, NoZstd) {
  7937. Headers headers;
  7938. headers.emplace("Accept-Encoding", "zstd");
  7939. auto res = cli_.Get("/nocompress", headers);
  7940. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7941. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7942. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7943. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7944. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7945. "7890123456789012345678901234567890",
  7946. res->body);
  7947. EXPECT_EQ(StatusCode::OK_200, res->status);
  7948. }
  7949. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  7950. Headers headers;
  7951. headers.emplace("Accept-Encoding", "zstd");
  7952. std::string body;
  7953. auto res = cli_.Get("/nocompress", headers,
  7954. [&](const char *data, uint64_t data_length) {
  7955. EXPECT_EQ(100U, data_length);
  7956. body.append(data, data_length);
  7957. return true;
  7958. });
  7959. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7960. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7961. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7962. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7963. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7964. "7890123456789012345678901234567890",
  7965. body);
  7966. EXPECT_EQ(StatusCode::OK_200, res->status);
  7967. }
  7968. // TODO: How to enable zstd ??
  7969. TEST_F(ServerTest, MultipartFormDataZstd) {
  7970. UploadFormDataItems items = {
  7971. {"key1", "test", "", ""},
  7972. {"key2", "--abcdefg123", "", ""},
  7973. };
  7974. Headers headers;
  7975. headers.emplace("Accept-Encoding", "zstd");
  7976. cli_.set_compress(true);
  7977. auto res = cli_.Post("/compress-multipart", headers, items);
  7978. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7979. EXPECT_EQ(StatusCode::OK_200, res->status);
  7980. }
  7981. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  7982. Headers headers;
  7983. headers.emplace("Accept-Encoding", "zstd");
  7984. cli_.set_compress(true);
  7985. auto res = cli_.Put(
  7986. "/put", headers, 3,
  7987. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7988. sink.os << "PUT";
  7989. return true;
  7990. },
  7991. "text/plain");
  7992. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7993. EXPECT_EQ(StatusCode::OK_200, res->status);
  7994. EXPECT_EQ("PUT", res->body);
  7995. }
  7996. // Pre-compression logging tests
  7997. TEST_F(ServerTest, PreCompressionLogging) {
  7998. // Test data for compression (matches the actual /compress endpoint content)
  7999. const std::string test_content =
  8000. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8001. "3456789012345678901234567890";
  8002. // Variables to capture logging data
  8003. std::string pre_compression_body;
  8004. std::string pre_compression_content_type;
  8005. std::string pre_compression_content_encoding;
  8006. std::string post_compression_body;
  8007. std::string post_compression_content_type;
  8008. std::string post_compression_content_encoding;
  8009. // Set up pre-compression logger
  8010. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  8011. const Response &res) {
  8012. pre_compression_body = res.body;
  8013. pre_compression_content_type = res.get_header_value("Content-Type");
  8014. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  8015. });
  8016. // Set up post-compression logger
  8017. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8018. post_compression_body = res.body;
  8019. post_compression_content_type = res.get_header_value("Content-Type");
  8020. post_compression_content_encoding =
  8021. res.get_header_value("Content-Encoding");
  8022. });
  8023. // Test with gzip compression
  8024. Headers headers;
  8025. headers.emplace("Accept-Encoding", "gzip");
  8026. auto res = cli_.Get("/compress", headers);
  8027. // Verify response was compressed
  8028. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8029. EXPECT_EQ(StatusCode::OK_200, res->status);
  8030. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8031. // Verify pre-compression logger captured uncompressed content
  8032. EXPECT_EQ(test_content, pre_compression_body);
  8033. EXPECT_EQ("text/plain", pre_compression_content_type);
  8034. EXPECT_TRUE(pre_compression_content_encoding
  8035. .empty()); // No encoding header before compression
  8036. // Verify post-compression logger captured compressed content
  8037. EXPECT_NE(test_content,
  8038. post_compression_body); // Should be different after compression
  8039. EXPECT_EQ("text/plain", post_compression_content_type);
  8040. EXPECT_EQ("gzip", post_compression_content_encoding);
  8041. // Verify compressed content is smaller
  8042. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8043. }
  8044. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  8045. const std::string test_content =
  8046. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8047. "3456789012345678901234567890";
  8048. std::string pre_compression_body;
  8049. std::string post_compression_body;
  8050. svr_.set_pre_compression_logger(
  8051. [&](const Request & /*req*/, const Response &res) {
  8052. pre_compression_body = res.body;
  8053. });
  8054. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8055. post_compression_body = res.body;
  8056. });
  8057. Headers headers;
  8058. headers.emplace("Accept-Encoding", "br");
  8059. auto res = cli_.Get("/compress", headers);
  8060. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8061. EXPECT_EQ(StatusCode::OK_200, res->status);
  8062. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8063. // Verify pre-compression content is uncompressed
  8064. EXPECT_EQ(test_content, pre_compression_body);
  8065. // Verify post-compression content is compressed
  8066. EXPECT_NE(test_content, post_compression_body);
  8067. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8068. }
  8069. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  8070. const std::string test_content =
  8071. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8072. "3456789012345678901234567890";
  8073. std::string pre_compression_body;
  8074. std::string post_compression_body;
  8075. svr_.set_pre_compression_logger(
  8076. [&](const Request & /*req*/, const Response &res) {
  8077. pre_compression_body = res.body;
  8078. });
  8079. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8080. post_compression_body = res.body;
  8081. });
  8082. // Request without compression (use /nocompress endpoint)
  8083. Headers headers;
  8084. auto res = cli_.Get("/nocompress", headers);
  8085. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8086. EXPECT_EQ(StatusCode::OK_200, res->status);
  8087. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8088. // Pre-compression logger should not be called when no compression is applied
  8089. EXPECT_TRUE(
  8090. pre_compression_body.empty()); // Pre-compression logger not called
  8091. EXPECT_EQ(
  8092. test_content,
  8093. post_compression_body); // Post-compression logger captures final content
  8094. }
  8095. TEST_F(ServerTest, LoggerSeesContentLength) {
  8096. size_t logged_content_length = 0;
  8097. std::string logged_content_length_header;
  8098. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8099. logged_content_length = res.content_length_;
  8100. logged_content_length_header = res.get_header_value("Content-Length");
  8101. });
  8102. auto res = cli_.Get("/nocompress");
  8103. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8104. EXPECT_EQ(StatusCode::OK_200, res->status);
  8105. EXPECT_EQ(res->body.size(), logged_content_length);
  8106. EXPECT_EQ(std::to_string(logged_content_length),
  8107. logged_content_length_header);
  8108. }
  8109. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  8110. const std::string test_content =
  8111. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8112. "3456789012345678901234567890";
  8113. std::string pre_compression_body;
  8114. bool pre_logger_called = false;
  8115. // Set only pre-compression logger
  8116. svr_.set_pre_compression_logger(
  8117. [&](const Request & /*req*/, const Response &res) {
  8118. pre_compression_body = res.body;
  8119. pre_logger_called = true;
  8120. });
  8121. Headers headers;
  8122. headers.emplace("Accept-Encoding", "gzip");
  8123. auto res = cli_.Get("/compress", headers);
  8124. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8125. EXPECT_EQ(StatusCode::OK_200, res->status);
  8126. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8127. // Verify pre-compression logger was called
  8128. EXPECT_TRUE(pre_logger_called);
  8129. EXPECT_EQ(test_content, pre_compression_body);
  8130. }
  8131. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  8132. {
  8133. // Test with Expect: 100-continue header - success case
  8134. // Server returns 100 Continue, client sends body, server returns 200 OK
  8135. Request req;
  8136. req.method = "POST";
  8137. req.path = "/post-large";
  8138. req.set_header("Expect", "100-continue");
  8139. req.body = LARGE_DATA;
  8140. Response res;
  8141. auto error = Error::Success;
  8142. cli_.set_keep_alive(true);
  8143. auto ret = cli_.send(req, res, error);
  8144. EXPECT_TRUE(ret);
  8145. EXPECT_EQ(StatusCode::OK_200, res.status);
  8146. EXPECT_EQ(LARGE_DATA, res.body);
  8147. }
  8148. {
  8149. // Test with Expect: 100-continue header - error case
  8150. // Client should not send the body when server returns an error
  8151. Request req;
  8152. req.method = "POST";
  8153. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  8154. req.set_header("Expect", "100-continue");
  8155. req.body = LARGE_DATA;
  8156. Response res;
  8157. auto error = Error::Success;
  8158. auto start = std::chrono::high_resolution_clock::now();
  8159. cli_.set_keep_alive(true);
  8160. auto ret = cli_.send(req, res, error);
  8161. auto end = std::chrono::high_resolution_clock::now();
  8162. auto elapsed =
  8163. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8164. .count();
  8165. // With Expect: 100-continue, request completes successfully but with error
  8166. EXPECT_TRUE(ret);
  8167. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  8168. EXPECT_EQ("close", res.get_header_value("Connection"));
  8169. EXPECT_FALSE(cli_.is_socket_open());
  8170. EXPECT_LE(elapsed, 2000);
  8171. }
  8172. {
  8173. // Send an extra GET request to ensure error recovery without hanging
  8174. Request req;
  8175. req.method = "GET";
  8176. req.path = "/hi";
  8177. auto start = std::chrono::high_resolution_clock::now();
  8178. auto res = cli_.send(req);
  8179. auto end = std::chrono::high_resolution_clock::now();
  8180. auto elapsed =
  8181. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8182. .count();
  8183. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8184. EXPECT_EQ(StatusCode::OK_200, res->status);
  8185. EXPECT_EQ("Hello World!", res->body);
  8186. EXPECT_LE(elapsed, 500);
  8187. }
  8188. }
  8189. TEST(ZstdDecompressor, ChunkedDecompression) {
  8190. std::string data;
  8191. for (size_t i = 0; i < 32 * 1024; ++i) {
  8192. data.push_back(static_cast<char>('a' + i % 26));
  8193. }
  8194. std::string compressed_data;
  8195. {
  8196. httplib::detail::zstd_compressor compressor;
  8197. bool result = compressor.compress(
  8198. data.data(), data.size(),
  8199. /*last=*/true,
  8200. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  8201. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  8202. compressed_data_size);
  8203. return true;
  8204. });
  8205. ASSERT_TRUE(result);
  8206. }
  8207. std::string decompressed_data;
  8208. {
  8209. httplib::detail::zstd_decompressor decompressor;
  8210. // Chunk size is chosen specifically to have a decompressed chunk size equal
  8211. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  8212. size_t chunk_size = 130;
  8213. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  8214. chunk_begin += chunk_size) {
  8215. size_t current_chunk_size =
  8216. std::min(compressed_data.size() - chunk_begin, chunk_size);
  8217. bool result = decompressor.decompress(
  8218. compressed_data.data() + chunk_begin, current_chunk_size,
  8219. [&](const char *decompressed_data_chunk,
  8220. size_t decompressed_data_chunk_size) {
  8221. decompressed_data.insert(decompressed_data.size(),
  8222. decompressed_data_chunk,
  8223. decompressed_data_chunk_size);
  8224. return true;
  8225. });
  8226. ASSERT_TRUE(result);
  8227. }
  8228. }
  8229. ASSERT_EQ(data, decompressed_data);
  8230. }
  8231. TEST(ZstdDecompressor, Decompress) {
  8232. std::string original_text = "Compressed with ZSTD";
  8233. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  8234. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  8235. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  8236. 0x20, 0x5a, 0x53, 0x54, 0x44};
  8237. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8238. std::string decompressed_data;
  8239. {
  8240. httplib::detail::zstd_decompressor decompressor;
  8241. bool result = decompressor.decompress(
  8242. compressed_data.data(), compressed_data.size(),
  8243. [&](const char *decompressed_data_chunk,
  8244. size_t decompressed_data_chunk_size) {
  8245. decompressed_data.insert(decompressed_data.size(),
  8246. decompressed_data_chunk,
  8247. decompressed_data_chunk_size);
  8248. return true;
  8249. });
  8250. ASSERT_TRUE(result);
  8251. }
  8252. ASSERT_EQ(original_text, decompressed_data);
  8253. }
  8254. #endif
  8255. // Sends a raw request to a server listening at HOST:PORT, writing it in
  8256. // separate chunks so that the server sees each part in its own read(). Used to
  8257. // place a read boundary at a specific offset of a request body.
  8258. static bool send_request_in_parts(time_t read_timeout_sec,
  8259. const std::vector<std::string> &parts,
  8260. std::string *resp = nullptr,
  8261. int port = PORT) {
  8262. auto error = Error::Success;
  8263. auto client_sock = detail::create_client_socket(
  8264. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  8265. /*connection_timeout_sec=*/5, 0,
  8266. /*read_timeout_sec=*/5, 0,
  8267. /*write_timeout_sec=*/5, 0, std::string(), error);
  8268. if (client_sock == INVALID_SOCKET) { return false; }
  8269. auto ret = detail::process_client_socket(
  8270. client_sock, read_timeout_sec, 0, 0, 0, 0,
  8271. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  8272. for (size_t i = 0; i < parts.size(); i++) {
  8273. const auto &part = parts[i];
  8274. if (part.size() !=
  8275. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  8276. return false;
  8277. }
  8278. if (i + 1 < parts.size()) {
  8279. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8280. }
  8281. }
  8282. char buf[512];
  8283. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  8284. while (line_reader.getline()) {
  8285. if (resp) { *resp += line_reader.ptr(); }
  8286. }
  8287. return true;
  8288. });
  8289. detail::close_socket(client_sock);
  8290. return ret;
  8291. }
  8292. // Sends a raw request to a server listening at HOST:PORT.
  8293. static bool send_request(time_t read_timeout_sec, const std::string &req,
  8294. std::string *resp = nullptr, int port = PORT) {
  8295. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  8296. }
  8297. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  8298. Server svr;
  8299. std::string header_value;
  8300. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  8301. header_value = req.get_header_value("foo");
  8302. res.set_content("ok", "text/plain");
  8303. });
  8304. thread t = thread([&] { svr.listen(HOST, PORT); });
  8305. auto se = detail::scope_exit([&] {
  8306. svr.stop();
  8307. t.join();
  8308. ASSERT_FALSE(svr.is_running());
  8309. });
  8310. svr.wait_until_ready();
  8311. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  8312. // like characters are not treated the same - use vertical tab and escape.
  8313. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  8314. "foo: \t \v bar \x1B\t \r\n"
  8315. "Connection: close\r\n"
  8316. "\r\n";
  8317. std::string res;
  8318. ASSERT_TRUE(send_request(5, req, &res));
  8319. EXPECT_EQ(header_value, "");
  8320. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  8321. }
  8322. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  8323. Server svr;
  8324. std::string received;
  8325. svr.Get("/order", [&](const Request &req, Response &res) {
  8326. received = entries_to_string(req.headers);
  8327. res.set_content("ok", "text/plain");
  8328. });
  8329. auto port = svr.bind_to_any_port(HOST);
  8330. thread t = thread([&] { svr.listen_after_bind(); });
  8331. auto se = detail::scope_exit([&] {
  8332. svr.stop();
  8333. t.join();
  8334. ASSERT_FALSE(svr.is_running());
  8335. });
  8336. svr.wait_until_ready();
  8337. const std::string req = "GET /order HTTP/1.1\r\n"
  8338. "X-First: 1\r\n"
  8339. "X-Dup: a\r\n"
  8340. "X-Second: 2\r\n"
  8341. "X-Dup: b\r\n"
  8342. "Connection: close\r\n"
  8343. "\r\n";
  8344. std::string res;
  8345. ASSERT_TRUE(send_request(5, req, &res, port));
  8346. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8347. EXPECT_EQ("X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ", received);
  8348. }
  8349. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  8350. Server svr;
  8351. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  8352. res.set_header("Set-Cookie", "first=1");
  8353. res.set_header("X-Between", "y");
  8354. res.set_header("Set-Cookie", "second=2");
  8355. res.set_content("ok", "text/plain");
  8356. });
  8357. auto port = svr.bind_to_any_port(HOST);
  8358. thread t = thread([&] { svr.listen_after_bind(); });
  8359. auto se = detail::scope_exit([&] {
  8360. svr.stop();
  8361. t.join();
  8362. ASSERT_FALSE(svr.is_running());
  8363. });
  8364. svr.wait_until_ready();
  8365. Client cli(HOST, port);
  8366. auto res = cli.Get("/cookies");
  8367. ASSERT_TRUE(res);
  8368. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  8369. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  8370. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  8371. }
  8372. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  8373. Server svr;
  8374. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  8375. auto i = new int(0);
  8376. res.set_header("Trailer", "X-Safe, X-Reflected");
  8377. res.set_chunked_content_provider(
  8378. "text/plain",
  8379. [i](size_t /*offset*/, DataSink &sink) {
  8380. if (*i == 0) {
  8381. sink.os << "body";
  8382. } else {
  8383. Headers trailer;
  8384. // A valid trailer that must survive.
  8385. trailer.emplace("X-Safe", "safe");
  8386. // Attacker-controlled value carrying CR/LF (response splitting).
  8387. trailer.emplace("X-Reflected",
  8388. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8389. // Attacker-controlled name carrying CR/LF.
  8390. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8391. sink.done_with_trailer(trailer);
  8392. }
  8393. (*i)++;
  8394. return true;
  8395. },
  8396. [i](bool /*success*/) { delete i; });
  8397. });
  8398. thread t = thread([&] { svr.listen(HOST, PORT); });
  8399. auto se = detail::scope_exit([&] {
  8400. svr.stop();
  8401. t.join();
  8402. ASSERT_FALSE(svr.is_running());
  8403. });
  8404. svr.wait_until_ready();
  8405. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  8406. "Host: " + HOST +
  8407. "\r\n"
  8408. "Connection: close\r\n"
  8409. "\r\n";
  8410. std::string res;
  8411. ASSERT_TRUE(send_request(5, req, &res));
  8412. // The injected fields must not appear anywhere in the raw response.
  8413. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8414. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8415. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8416. // Invalid trailers are dropped entirely, matching set_header().
  8417. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8418. // The valid trailer still passes through.
  8419. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8420. }
  8421. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  8422. Server svr;
  8423. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  8424. // res.headers is a public field an application can populate directly,
  8425. // bypassing set_header()'s validation (e.g. reflecting a request value).
  8426. // A valid header that must survive.
  8427. res.headers.emplace("X-Safe", "safe");
  8428. // Attacker-controlled value carrying CR/LF (response splitting).
  8429. res.headers.emplace("X-Reflected",
  8430. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8431. // Attacker-controlled name carrying CR/LF.
  8432. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8433. res.set_content("body", "text/plain");
  8434. });
  8435. thread t = thread([&] { svr.listen(HOST, PORT); });
  8436. auto se = detail::scope_exit([&] {
  8437. svr.stop();
  8438. t.join();
  8439. ASSERT_FALSE(svr.is_running());
  8440. });
  8441. svr.wait_until_ready();
  8442. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  8443. "Host: " + HOST +
  8444. "\r\n"
  8445. "Connection: close\r\n"
  8446. "\r\n";
  8447. std::string res;
  8448. ASSERT_TRUE(send_request(5, req, &res));
  8449. // The injected fields must not appear anywhere in the raw response.
  8450. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8451. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8452. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8453. // Invalid headers are dropped entirely, matching set_header().
  8454. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8455. // The valid header still passes through.
  8456. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8457. }
  8458. // Forward declaration: in split builds split.py strips `inline` and moves the
  8459. // definition into httplib.cc, so detail::write_request_line is not visible from
  8460. // the public httplib.h. Re-declaring it here lets the tests link against the
  8461. // symbol in both header-only and split builds.
  8462. namespace httplib {
  8463. namespace detail {
  8464. ssize_t write_request_line(Stream &strm, const std::string &method,
  8465. const std::string &path);
  8466. } // namespace detail
  8467. } // namespace httplib
  8468. TEST(RequestLineInjectionTest, RejectsCRLFInTarget) {
  8469. // A well-formed target is written verbatim.
  8470. {
  8471. detail::BufferStream strm;
  8472. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  8473. EXPECT_GT(n, 0);
  8474. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  8475. }
  8476. // A target carrying CR/LF must be rejected before anything reaches the wire,
  8477. // otherwise it splits the request line and injects a header or a whole
  8478. // request. This is what a decoded redirect Location ("%0D%0A") turns into
  8479. // when path encoding is disabled.
  8480. const std::string evil_targets[] = {
  8481. "/a\r\nInjected: pwned",
  8482. "/a\rInjected",
  8483. "/a\nInjected",
  8484. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  8485. };
  8486. for (const auto &evil : evil_targets) {
  8487. detail::BufferStream strm;
  8488. auto n = detail::write_request_line(strm, "GET", evil);
  8489. EXPECT_LT(n, 0);
  8490. EXPECT_TRUE(strm.get_buffer().empty());
  8491. }
  8492. }
  8493. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  8494. // End-to-end counterpart to RejectsCRLFInTarget. With path encoding disabled
  8495. // the client transmits the target verbatim, so a CR/LF-bearing target -- what
  8496. // a redirect Location "%0D%0A" decodes to -- reaches write_request. The
  8497. // client must fail cleanly with Error::Write instead of putting a
  8498. // request-line-less, header-injecting request on the wire.
  8499. Server svr;
  8500. svr.Get("/a", [](const Request &, Response &res) {
  8501. res.set_content("ok", "text/plain");
  8502. });
  8503. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8504. auto se = detail::scope_exit([&] {
  8505. svr.stop();
  8506. thread.join();
  8507. ASSERT_FALSE(svr.is_running());
  8508. });
  8509. svr.wait_until_ready();
  8510. {
  8511. Client cli(HOST, PORT);
  8512. cli.set_path_encode(false);
  8513. // The request is rejected before anything is written, so the connection
  8514. // stays silent and the subsequent response read would otherwise block for
  8515. // the full default read timeout. Shorten it -- the assertion is on the
  8516. // error, not the timeout.
  8517. cli.set_read_timeout(1, 0);
  8518. auto res = cli.Get("/a\r\nInjected: pwned");
  8519. EXPECT_FALSE(res);
  8520. EXPECT_EQ(Error::Write, res.error());
  8521. }
  8522. }
  8523. // Sends a raw request and verifies that there isn't a crash or exception.
  8524. static void test_raw_request(const std::string &req,
  8525. std::string *out = nullptr) {
  8526. Server svr;
  8527. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  8528. res.set_content("ok", "text/plain");
  8529. });
  8530. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  8531. res.set_content("ok", "text/plain");
  8532. });
  8533. svr.Get("/header_field_value_check",
  8534. [&](const Request & /*req*/, Response &res) {
  8535. res.set_content("ok", "text/plain");
  8536. });
  8537. svr.CustomRoute("PROPFIND", "/dav",
  8538. [&](const Request & /*req*/, Response &res) {
  8539. res.status = StatusCode::MultiStatus_207;
  8540. });
  8541. // Server read timeout must be longer than the client read timeout for the
  8542. // bug to reproduce, probably to force the server to process a request
  8543. // without a trailing blank line.
  8544. const time_t client_read_timeout_sec = 1;
  8545. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  8546. bool listen_thread_ok = false;
  8547. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  8548. auto se = detail::scope_exit([&] {
  8549. svr.stop();
  8550. t.join();
  8551. ASSERT_FALSE(svr.is_running());
  8552. EXPECT_TRUE(listen_thread_ok);
  8553. });
  8554. svr.wait_until_ready();
  8555. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  8556. }
  8557. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  8558. // A certain header line causes an exception if the header property is parsed
  8559. // naively with a single regex. This occurs with libc++ but not libstdc++.
  8560. test_raw_request(
  8561. "GET /hi HTTP/1.1\r\n"
  8562. " : "
  8563. " "
  8564. " ");
  8565. }
  8566. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  8567. // A certain header line causes an exception if the header property *name* is
  8568. // parsed with a regular expression starting with "(.+?):" - this is a non-
  8569. // greedy matcher and requires backtracking when there are a lot of ":"
  8570. // characters.
  8571. // This occurs with libc++ but not libstdc++.
  8572. test_raw_request(
  8573. "GET /hi HTTP/1.1\r\n"
  8574. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  8575. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  8576. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  8577. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  8578. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  8579. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  8580. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  8581. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  8582. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  8583. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  8584. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  8585. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  8586. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  8587. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  8588. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  8589. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  8590. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  8591. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  8592. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  8593. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  8594. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  8595. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  8596. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  8597. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  8598. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  8599. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  8600. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  8601. "&&&%%%");
  8602. }
  8603. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  8604. // Make sure this doesn't crash the server.
  8605. // In a previous version of the header line regex, the "\r" rendered the line
  8606. // unparsable and the regex engine repeatedly backtracked, trying to look for
  8607. // a new position where the leading white space ended and the field value
  8608. // began.
  8609. // The crash occurs with libc++ but not libstdc++.
  8610. test_raw_request("GET /hi HTTP/1.1\r\n"
  8611. "a:" +
  8612. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  8613. "\r\n"
  8614. "\r\n");
  8615. }
  8616. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  8617. std::string out;
  8618. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  8619. "Content-Type: text/plain\r\n"
  8620. "Transfer-Encoding: chunked\r\n"
  8621. "\r\n"
  8622. "nothex\r\n",
  8623. &out);
  8624. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8625. }
  8626. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  8627. std::string out;
  8628. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  8629. "Content-Type: text/plain\r\n"
  8630. "Transfer-Encoding: chunked\r\n"
  8631. "\r\n"
  8632. "3\r\n"
  8633. "xyz\r\n"
  8634. "NaN\r\n",
  8635. &out);
  8636. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8637. }
  8638. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  8639. std::string out;
  8640. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  8641. "Content-Type: text/plain\r\n"
  8642. "Transfer-Encoding: chunked\r\n"
  8643. "\r\n"
  8644. // Length is too large for 64 bits.
  8645. "1ffffffffffffffff\r\n"
  8646. "xyz\r\n",
  8647. &out);
  8648. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8649. }
  8650. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  8651. test_raw_request("GET /hi HTTP/1.1\r\n"
  8652. "Content-Type: text/plain\r\n\r");
  8653. }
  8654. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  8655. std::string out;
  8656. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  8657. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8658. }
  8659. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  8660. Server svr;
  8661. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  8662. EXPECT_TRUE(!req.remote_addr.empty());
  8663. });
  8664. thread t = thread([&] { svr.listen(HOST, PORT); });
  8665. auto se = detail::scope_exit([&] {
  8666. svr.stop();
  8667. t.join();
  8668. ASSERT_FALSE(svr.is_running());
  8669. });
  8670. svr.wait_until_ready();
  8671. // Send an invalid request line to trigger Bad Request
  8672. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  8673. std::string out;
  8674. ASSERT_TRUE(send_request(5, bad_req, &out));
  8675. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8676. }
  8677. // A custom method with neither Content-Length nor Transfer-Encoding must be
  8678. // answered right away rather than blocking on a read that waits for EOF.
  8679. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  8680. std::string out;
  8681. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  8682. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  8683. }
  8684. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  8685. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  8686. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  8687. for (const auto *method : methods) {
  8688. Server svr;
  8689. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  8690. EXPECT_FALSE(svr.is_valid()) << method;
  8691. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  8692. }
  8693. }
  8694. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  8695. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  8696. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  8697. for (const auto *method : methods) {
  8698. Server svr;
  8699. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  8700. EXPECT_FALSE(svr.is_valid()) << method;
  8701. }
  8702. }
  8703. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  8704. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  8705. "COPY", "MOVE", "LOCK",
  8706. "UNLOCK", "REPORT", "SUBSCRIBE"};
  8707. Server svr;
  8708. for (const auto *method : methods) {
  8709. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  8710. }
  8711. EXPECT_TRUE(svr.is_valid());
  8712. }
  8713. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  8714. Server svr;
  8715. svr.CustomRoute("POST", "/x",
  8716. [](const Request &, Response &, const ContentReader &) {});
  8717. EXPECT_FALSE(svr.is_valid());
  8718. }
  8719. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  8720. Server svr;
  8721. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  8722. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  8723. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  8724. EXPECT_FALSE(svr.is_valid());
  8725. }
  8726. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  8727. Server svr;
  8728. auto captured = Error::Success;
  8729. svr.set_error_logger(
  8730. [&](const Error &err, const Request * /*req*/) { captured = err; });
  8731. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  8732. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  8733. }
  8734. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  8735. std::string out;
  8736. std::string request(
  8737. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  8738. test_raw_request(request, &out);
  8739. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8740. }
  8741. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  8742. std::string out;
  8743. std::string request(
  8744. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  8745. test_raw_request(request, &out);
  8746. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8747. }
  8748. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  8749. std::string out;
  8750. std::string request(
  8751. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  8752. test_raw_request(request, &out);
  8753. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8754. }
  8755. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  8756. std::string out;
  8757. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  8758. "Test: \r\n\r\n",
  8759. &out);
  8760. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  8761. }
  8762. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  8763. Server svr;
  8764. std::string x_custom;
  8765. std::string cookie;
  8766. std::string xff;
  8767. std::string x_unicode;
  8768. std::string x_iis;
  8769. svr.Get("/check", [&](const Request &req, Response &res) {
  8770. x_custom = req.get_header_value("X-Custom");
  8771. cookie = req.get_header_value("Cookie");
  8772. xff = req.get_header_value("X-Forwarded-For");
  8773. x_unicode = req.get_header_value("X-Unicode");
  8774. x_iis = req.get_header_value("X-IIS");
  8775. res.set_content("ok", "text/plain");
  8776. });
  8777. thread t = thread([&] { svr.listen(HOST, PORT); });
  8778. auto se = detail::scope_exit([&] {
  8779. svr.stop();
  8780. t.join();
  8781. ASSERT_FALSE(svr.is_running());
  8782. });
  8783. svr.wait_until_ready();
  8784. const std::string req = "GET /check HTTP/1.1\r\n"
  8785. "Host: localhost\r\n"
  8786. "X-Custom: a%0D%0AInjected: b\r\n"
  8787. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  8788. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  8789. "X-Unicode: %E3%81%82\r\n"
  8790. "X-IIS: %u00E9\r\n"
  8791. "Connection: close\r\n"
  8792. "\r\n";
  8793. std::string res;
  8794. ASSERT_TRUE(send_request(5, req, &res));
  8795. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8796. // Every value must be returned verbatim (wire form), with no decoding.
  8797. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  8798. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  8799. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  8800. EXPECT_EQ("%E3%81%82", x_unicode);
  8801. EXPECT_EQ("%u00E9", x_iis);
  8802. }
  8803. // Applications that previously relied on automatic percent-decoding can
  8804. // reproduce the old behavior by explicitly calling decode_path_component()
  8805. // or, for RFC 3986 conformance, decode_uri_component().
  8806. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  8807. Server svr;
  8808. std::string decoded;
  8809. svr.Get("/check", [&](const Request &req, Response &res) {
  8810. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  8811. res.set_content("ok", "text/plain");
  8812. });
  8813. thread t = thread([&] { svr.listen(HOST, PORT); });
  8814. auto se = detail::scope_exit([&] {
  8815. svr.stop();
  8816. t.join();
  8817. ASSERT_FALSE(svr.is_running());
  8818. });
  8819. svr.wait_until_ready();
  8820. const std::string req = "GET /check HTTP/1.1\r\n"
  8821. "Host: localhost\r\n"
  8822. "X-Custom: hello%20world\r\n"
  8823. "Connection: close\r\n"
  8824. "\r\n";
  8825. std::string res;
  8826. ASSERT_TRUE(send_request(5, req, &res));
  8827. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8828. EXPECT_EQ("hello world", decoded);
  8829. }
  8830. // Regression test for #2033. Browsers send Referer values that include
  8831. // percent-encoded characters such as %0A inside the URL. Decoding the
  8832. // header value would either trip the post-decode CR/LF/NUL guard (the
  8833. // original bug, returning 400) or, after that guard was relaxed, silently
  8834. // store a literal LF — both unacceptable. The wire form must round-trip.
  8835. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  8836. Server svr;
  8837. std::string referer;
  8838. svr.Get("/check", [&](const Request &req, Response &res) {
  8839. referer = req.get_header_value("Referer");
  8840. res.set_content("ok", "text/plain");
  8841. });
  8842. thread t = thread([&] { svr.listen(HOST, PORT); });
  8843. auto se = detail::scope_exit([&] {
  8844. svr.stop();
  8845. t.join();
  8846. ASSERT_FALSE(svr.is_running());
  8847. });
  8848. svr.wait_until_ready();
  8849. const std::string req = "GET /check HTTP/1.1\r\n"
  8850. "Host: localhost\r\n"
  8851. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  8852. "Connection: close\r\n"
  8853. "\r\n";
  8854. std::string res;
  8855. ASSERT_TRUE(send_request(5, req, &res));
  8856. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8857. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  8858. }
  8859. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  8860. Server svr;
  8861. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  8862. res.set_header("Cache-Control", "no-cache");
  8863. res.set_chunked_content_provider(
  8864. "text/event-stream", [](size_t offset, DataSink &sink) {
  8865. std::string s = "data:";
  8866. s += std::to_string(offset);
  8867. s += "\n\n";
  8868. auto ret = sink.write(s.data(), s.size());
  8869. EXPECT_TRUE(ret);
  8870. std::this_thread::sleep_for(std::chrono::seconds(1));
  8871. return true;
  8872. });
  8873. });
  8874. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8875. svr.wait_until_ready();
  8876. Client client(HOST, PORT);
  8877. const Headers headers = {{"Accept", "text/event-stream"}};
  8878. auto get_thread = std::thread([&client, &headers]() {
  8879. auto res = client.Get(
  8880. "/events", headers,
  8881. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  8882. });
  8883. auto se = detail::scope_exit([&] {
  8884. svr.stop();
  8885. get_thread.join();
  8886. listen_thread.join();
  8887. ASSERT_FALSE(svr.is_running());
  8888. });
  8889. // Give GET time to get a few messages.
  8890. std::this_thread::sleep_for(std::chrono::seconds(2));
  8891. }
  8892. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  8893. httplib::Server svr;
  8894. svr.Post("/hi",
  8895. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  8896. res.status = StatusCode::OK_200;
  8897. });
  8898. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8899. svr.wait_until_ready();
  8900. Client cli(HOST, PORT);
  8901. auto res = cli.Post("/hi", "data", "text/plain");
  8902. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8903. EXPECT_EQ(StatusCode::OK_200, res->status);
  8904. svr.stop();
  8905. thread.join();
  8906. ASSERT_FALSE(svr.is_running());
  8907. res = cli.Post("/hi", "data", "text/plain");
  8908. ASSERT_FALSE(res);
  8909. }
  8910. TEST(ServerStopTest, ListenFailure) {
  8911. Server svr;
  8912. auto t = thread([&]() {
  8913. auto ret = svr.listen("????", PORT);
  8914. EXPECT_FALSE(ret);
  8915. });
  8916. svr.wait_until_ready();
  8917. svr.stop();
  8918. t.join();
  8919. }
  8920. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8921. TEST(ServerStopTest, Decommision) {
  8922. Server svr;
  8923. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  8924. for (int i = 0; i < 4; i++) {
  8925. auto is_even = !(i % 2);
  8926. std::thread t{[&] {
  8927. try {
  8928. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8929. if (is_even) {
  8930. throw std::runtime_error("Some thing that happens to go wrong.");
  8931. }
  8932. svr.listen(HOST, PORT);
  8933. } catch (...) { svr.decommission(); }
  8934. }};
  8935. svr.wait_until_ready();
  8936. // Server is up
  8937. {
  8938. Client cli(HOST, PORT);
  8939. auto res = cli.Get("/hi");
  8940. if (is_even) {
  8941. EXPECT_FALSE(res);
  8942. } else {
  8943. EXPECT_TRUE(res);
  8944. EXPECT_EQ("hi...", res->body);
  8945. }
  8946. }
  8947. svr.stop();
  8948. t.join();
  8949. // Server is down...
  8950. {
  8951. Client cli(HOST, PORT);
  8952. auto res = cli.Get("/hi");
  8953. EXPECT_FALSE(res);
  8954. }
  8955. }
  8956. }
  8957. #endif
  8958. // Helper function for string body upload progress tests
  8959. template <typename SetupHandler, typename ClientCall>
  8960. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  8961. ClientCall &&client_call,
  8962. const string &body) {
  8963. Server svr;
  8964. setup_handler(svr);
  8965. thread t = thread([&]() { svr.listen(HOST, PORT); });
  8966. auto se = detail::scope_exit([&] {
  8967. svr.stop();
  8968. t.join();
  8969. });
  8970. svr.wait_until_ready();
  8971. Client cli(HOST, PORT);
  8972. vector<uint64_t> progress_values;
  8973. bool progress_called = false;
  8974. auto res =
  8975. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  8976. progress_values.push_back(current);
  8977. progress_called = true;
  8978. return true;
  8979. });
  8980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8981. EXPECT_EQ(200, res->status);
  8982. EXPECT_TRUE(progress_called);
  8983. }
  8984. TEST(UploadProgressTest, PostStringBodyBasic) {
  8985. TestStringBodyUploadProgress(
  8986. [](Server &svr) {
  8987. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  8988. res.set_content("received", "text/plain");
  8989. });
  8990. },
  8991. [](Client &cli, const string &body, UploadProgress progress_callback) {
  8992. return cli.Post("/test", body, "text/plain", progress_callback);
  8993. },
  8994. "test data for upload progress");
  8995. }
  8996. TEST(UploadProgressTest, PutStringBodyBasic) {
  8997. TestStringBodyUploadProgress(
  8998. [](Server &svr) {
  8999. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  9000. res.set_content("put received", "text/plain");
  9001. });
  9002. },
  9003. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9004. return cli.Put("/test", body, "text/plain", progress_callback);
  9005. },
  9006. "put test data for upload progress");
  9007. }
  9008. TEST(UploadProgressTest, PatchStringBodyBasic) {
  9009. TestStringBodyUploadProgress(
  9010. [](Server &svr) {
  9011. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  9012. res.set_content("patch received", "text/plain");
  9013. });
  9014. },
  9015. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9016. return cli.Patch("/test", body, "text/plain", progress_callback);
  9017. },
  9018. "patch test data for upload progress");
  9019. }
  9020. // Helper function for content provider upload progress tests
  9021. template <typename SetupHandler, typename ClientCall>
  9022. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  9023. ClientCall &&client_call) {
  9024. Server svr;
  9025. setup_handler(svr);
  9026. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9027. auto se = detail::scope_exit([&] {
  9028. svr.stop();
  9029. t.join();
  9030. });
  9031. svr.wait_until_ready();
  9032. Client cli(HOST, PORT);
  9033. vector<uint64_t> progress_values;
  9034. auto res =
  9035. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9036. progress_values.push_back(current);
  9037. return true;
  9038. });
  9039. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9040. EXPECT_EQ(200, res->status);
  9041. EXPECT_FALSE(progress_values.empty());
  9042. }
  9043. TEST(UploadProgressTest, PostContentProviderProgress) {
  9044. TestContentProviderUploadProgress(
  9045. [](Server &svr) {
  9046. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9047. res.set_content("provider received", "text/plain");
  9048. });
  9049. },
  9050. [](Client &cli, UploadProgress progress_callback) {
  9051. return cli.Post(
  9052. "/test", 10,
  9053. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  9054. sink.os << "test data";
  9055. return true;
  9056. },
  9057. "text/plain", progress_callback);
  9058. });
  9059. }
  9060. // Helper function for multipart upload progress tests
  9061. template <typename SetupHandler, typename ClientCall>
  9062. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  9063. ClientCall &&client_call,
  9064. const string &endpoint) {
  9065. Server svr;
  9066. setup_handler(svr);
  9067. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9068. auto se = detail::scope_exit([&] {
  9069. svr.stop();
  9070. t.join();
  9071. });
  9072. svr.wait_until_ready();
  9073. Client cli(HOST, PORT);
  9074. vector<uint64_t> progress_values;
  9075. UploadFormDataItems items = {
  9076. {"field1", "value1", "", ""},
  9077. {"field2", "longer value for progress tracking test", "", ""},
  9078. {"file1", "file content data for upload progress", "test.txt",
  9079. "text/plain"}};
  9080. auto res = client_call(cli, endpoint, items,
  9081. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9082. progress_values.push_back(current);
  9083. return true;
  9084. });
  9085. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9086. EXPECT_EQ(200, res->status);
  9087. EXPECT_FALSE(progress_values.empty());
  9088. }
  9089. TEST(UploadProgressTest, PostMultipartProgress) {
  9090. TestMultipartUploadProgress(
  9091. [](Server &svr) {
  9092. svr.Post("/multipart", [](const Request &req, Response &res) {
  9093. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  9094. res.set_content("multipart received", "text/plain");
  9095. });
  9096. },
  9097. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  9098. UploadProgress progress_callback) {
  9099. return cli.Post(endpoint, items, progress_callback);
  9100. },
  9101. "/multipart");
  9102. }
  9103. // Helper function for basic download progress tests
  9104. template <typename SetupHandler, typename ClientCall>
  9105. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  9106. ClientCall &&client_call, const string &endpoint,
  9107. size_t expected_content_size) {
  9108. Server svr;
  9109. setup_handler(svr);
  9110. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9111. auto se = detail::scope_exit([&] {
  9112. svr.stop();
  9113. t.join();
  9114. });
  9115. svr.wait_until_ready();
  9116. Client cli(HOST, PORT);
  9117. vector<uint64_t> progress_values;
  9118. auto res = client_call(cli, endpoint,
  9119. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9120. progress_values.push_back(current);
  9121. return true;
  9122. });
  9123. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9124. EXPECT_EQ(200, res->status);
  9125. EXPECT_FALSE(progress_values.empty());
  9126. EXPECT_EQ(expected_content_size, res->body.size());
  9127. }
  9128. TEST(DownloadProgressTest, GetBasic) {
  9129. TestBasicDownloadProgress(
  9130. [](Server &svr) {
  9131. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  9132. string content(1000, 'D');
  9133. res.set_content(content, "text/plain");
  9134. });
  9135. },
  9136. [](Client &cli, const string &endpoint,
  9137. DownloadProgress progress_callback) {
  9138. return cli.Get(endpoint, progress_callback);
  9139. },
  9140. "/download", 1000u);
  9141. }
  9142. // Helper function for content receiver download progress tests
  9143. template <typename SetupHandler, typename ClientCall>
  9144. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  9145. ClientCall &&client_call,
  9146. const string &endpoint,
  9147. size_t expected_content_size) {
  9148. Server svr;
  9149. setup_handler(svr);
  9150. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9151. auto se = detail::scope_exit([&] {
  9152. svr.stop();
  9153. t.join();
  9154. });
  9155. svr.wait_until_ready();
  9156. Client cli(HOST, PORT);
  9157. vector<uint64_t> progress_values;
  9158. string received_body;
  9159. auto res = client_call(
  9160. cli, endpoint,
  9161. [&](const char *data, size_t data_length) -> bool {
  9162. received_body.append(data, data_length);
  9163. return true;
  9164. },
  9165. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9166. progress_values.push_back(current);
  9167. return true;
  9168. });
  9169. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9170. EXPECT_EQ(200, res->status);
  9171. EXPECT_FALSE(progress_values.empty());
  9172. EXPECT_EQ(expected_content_size, received_body.size());
  9173. EXPECT_TRUE(res->body.empty());
  9174. }
  9175. TEST(DownloadProgressTest, GetWithContentReceiver) {
  9176. TestContentReceiverDownloadProgress(
  9177. [](Server &svr) {
  9178. svr.Get("/download-receiver",
  9179. [](const Request & /*req*/, Response &res) {
  9180. string content(2000, 'R');
  9181. res.set_content(content, "text/plain");
  9182. });
  9183. },
  9184. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  9185. DownloadProgress progress_callback) {
  9186. return cli.Get(endpoint, content_receiver, progress_callback);
  9187. },
  9188. "/download-receiver", 2000u);
  9189. }
  9190. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  9191. // A provider reaching a pass with nothing to hand over - an empty buffer
  9192. // popped off a queue, say - must not be taken to mean the body is finished.
  9193. // It used to end the loop with the terminating chunk unwritten while the
  9194. // server still considered the response complete, so the peer waited for an
  9195. // end that never arrived.
  9196. Server svr;
  9197. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9198. auto step = std::make_shared<int>(0);
  9199. res.set_chunked_content_provider("text/plain",
  9200. [step](size_t /*offset*/, DataSink &sink) {
  9201. switch ((*step)++) {
  9202. case 0: sink.write("", 0); break;
  9203. case 1: sink.write("hello", 5); break;
  9204. default: sink.done(); break;
  9205. }
  9206. return true;
  9207. });
  9208. });
  9209. auto port = svr.bind_to_any_port(HOST);
  9210. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9211. auto listen_se = detail::scope_exit([&] {
  9212. svr.stop();
  9213. listen_thread.join();
  9214. ASSERT_FALSE(svr.is_running());
  9215. });
  9216. svr.wait_until_ready();
  9217. Client cli(HOST, port);
  9218. // Without the fix the body is never terminated, so bound the wait rather
  9219. // than letting the test hang on the default read timeout.
  9220. cli.set_read_timeout(5, 0);
  9221. auto res = cli.Get("/stream");
  9222. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9223. EXPECT_EQ(StatusCode::OK_200, res->status);
  9224. EXPECT_EQ("hello", res->body);
  9225. }
  9226. TEST(StreamingTest, NoContentLengthStreaming) {
  9227. Server svr;
  9228. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9229. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  9230. if (offset < 6) {
  9231. sink.os << (offset < 3 ? "a" : "b");
  9232. } else {
  9233. sink.done();
  9234. }
  9235. return true;
  9236. });
  9237. });
  9238. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9239. auto listen_se = detail::scope_exit([&] {
  9240. svr.stop();
  9241. listen_thread.join();
  9242. ASSERT_FALSE(svr.is_running());
  9243. });
  9244. svr.wait_until_ready();
  9245. Client client(HOST, PORT);
  9246. auto get_thread = std::thread([&client]() {
  9247. std::string s;
  9248. auto res =
  9249. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  9250. s += std::string(data, len);
  9251. return true;
  9252. });
  9253. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9254. EXPECT_EQ(StatusCode::OK_200, res->status);
  9255. EXPECT_EQ("aaabbb", s);
  9256. });
  9257. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  9258. // Give GET time to get a few messages.
  9259. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  9260. }
  9261. TEST(MountTest, Unmount) {
  9262. Server svr;
  9263. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9264. auto se = detail::scope_exit([&] {
  9265. svr.stop();
  9266. listen_thread.join();
  9267. ASSERT_FALSE(svr.is_running());
  9268. });
  9269. svr.wait_until_ready();
  9270. Client cli("localhost", PORT);
  9271. svr.set_mount_point("/mount2", "./www2");
  9272. auto res = cli.Get("/");
  9273. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9274. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9275. res = cli.Get("/mount2/dir/test.html");
  9276. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9277. EXPECT_EQ(StatusCode::OK_200, res->status);
  9278. svr.set_mount_point("/", "./www");
  9279. res = cli.Get("/dir/");
  9280. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9281. EXPECT_EQ(StatusCode::OK_200, res->status);
  9282. svr.remove_mount_point("/");
  9283. res = cli.Get("/dir/");
  9284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9285. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9286. svr.remove_mount_point("/mount2");
  9287. res = cli.Get("/mount2/dir/test.html");
  9288. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9289. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9290. }
  9291. TEST(MountTest, PathSegmentBoundary) {
  9292. Server svr;
  9293. svr.set_mount_point("/mount2", "./www2");
  9294. svr.set_mount_point("/", "./www");
  9295. auto port = svr.bind_to_any_port(HOST);
  9296. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9297. auto se = detail::scope_exit([&] {
  9298. svr.stop();
  9299. listen_thread.join();
  9300. ASSERT_FALSE(svr.is_running());
  9301. });
  9302. svr.wait_until_ready();
  9303. Client cli(HOST, port);
  9304. auto res = cli.Get("/mount2/dir/test.html");
  9305. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9306. EXPECT_EQ(StatusCode::OK_200, res->status);
  9307. // "/mount2" must not match part-way through a path segment.
  9308. res = cli.Get("/mount2dir/test.html");
  9309. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9310. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9311. // A mount point ending in '/' keeps matching every path below it.
  9312. res = cli.Get("/dir/test.html");
  9313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9314. EXPECT_EQ(StatusCode::OK_200, res->status);
  9315. }
  9316. TEST(MountTest, Redicect) {
  9317. Server svr;
  9318. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9319. auto se = detail::scope_exit([&] {
  9320. svr.stop();
  9321. listen_thread.join();
  9322. ASSERT_FALSE(svr.is_running());
  9323. });
  9324. svr.set_mount_point("/", "./www");
  9325. svr.wait_until_ready();
  9326. Client cli("localhost", PORT);
  9327. auto res = cli.Get("/dir/");
  9328. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9329. EXPECT_EQ(StatusCode::OK_200, res->status);
  9330. res = cli.Get("/dir");
  9331. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9332. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9333. res = cli.Get("/file");
  9334. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9335. EXPECT_EQ(StatusCode::OK_200, res->status);
  9336. res = cli.Get("/file/");
  9337. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9338. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9339. cli.set_follow_location(true);
  9340. res = cli.Get("/dir");
  9341. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9342. EXPECT_EQ(StatusCode::OK_200, res->status);
  9343. }
  9344. TEST(MountTest, MultibytesPathName) {
  9345. Server svr;
  9346. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9347. auto se = detail::scope_exit([&] {
  9348. svr.stop();
  9349. listen_thread.join();
  9350. ASSERT_FALSE(svr.is_running());
  9351. });
  9352. svr.set_mount_point("/", "./www");
  9353. svr.wait_until_ready();
  9354. Client cli("localhost", PORT);
  9355. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  9356. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9357. EXPECT_EQ(StatusCode::OK_200, res->status);
  9358. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  9359. }
  9360. #ifdef _WIN32
  9361. // Issue #2435: mmap::open() must succeed even when another handle holds
  9362. // the file open for writing (e.g. an active log file).
  9363. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  9364. const char *path = "mmap_concurrent_writer_test.txt";
  9365. const char *content = "hello";
  9366. {
  9367. std::ofstream f(path, std::ios::binary);
  9368. f.write(content, static_cast<std::streamsize>(strlen(content)));
  9369. }
  9370. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  9371. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  9372. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  9373. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  9374. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  9375. detail::mmap m(path);
  9376. ASSERT_TRUE(m.is_open());
  9377. EXPECT_EQ(strlen(content), m.size());
  9378. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  9379. }
  9380. #endif
  9381. #ifndef _WIN32
  9382. // A failed ::mmap() must not be reported as an open mapping, otherwise data()
  9383. // hands the caller the MAP_FAILED sentinel. A directory is the easiest way to
  9384. // reach it, since ::open() and fstat() succeed for one but ::mmap() doesn't.
  9385. TEST(MmapTest, FailedMappingIsNotOpen) {
  9386. const char *path = "./mmap_failed_mapping_test_dir";
  9387. ASSERT_EQ(0, ::mkdir(path, 0755));
  9388. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  9389. detail::mmap m(path);
  9390. EXPECT_FALSE(m.is_open());
  9391. EXPECT_EQ(0U, m.size());
  9392. EXPECT_NE(static_cast<const void *>(m.data()),
  9393. static_cast<const void *>(MAP_FAILED));
  9394. }
  9395. #endif
  9396. TEST(KeepAliveTest, ReadTimeout) {
  9397. Server svr;
  9398. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  9399. std::this_thread::sleep_for(std::chrono::seconds(2));
  9400. res.set_content("a", "text/plain");
  9401. });
  9402. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  9403. res.set_content("b", "text/plain");
  9404. });
  9405. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9406. auto se = detail::scope_exit([&] {
  9407. svr.stop();
  9408. listen_thread.join();
  9409. ASSERT_FALSE(svr.is_running());
  9410. });
  9411. svr.wait_until_ready();
  9412. Client cli("localhost", PORT);
  9413. cli.set_keep_alive(true);
  9414. cli.set_read_timeout(std::chrono::seconds(1));
  9415. auto resa = cli.Get("/a");
  9416. ASSERT_FALSE(resa);
  9417. EXPECT_EQ(Error::Read, resa.error());
  9418. auto resb = cli.Get("/b");
  9419. ASSERT_TRUE(resb);
  9420. EXPECT_EQ(StatusCode::OK_200, resb->status);
  9421. EXPECT_EQ("b", resb->body);
  9422. }
  9423. TEST(KeepAliveTest, MaxCount) {
  9424. size_t keep_alive_max_count = 3;
  9425. Server svr;
  9426. svr.set_keep_alive_max_count(keep_alive_max_count);
  9427. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9428. res.set_content("Hello World!", "text/plain");
  9429. });
  9430. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9431. auto se = detail::scope_exit([&] {
  9432. svr.stop();
  9433. listen_thread.join();
  9434. ASSERT_FALSE(svr.is_running());
  9435. });
  9436. svr.wait_until_ready();
  9437. Client cli(HOST, PORT);
  9438. cli.set_keep_alive(true);
  9439. for (size_t i = 0; i < 5; i++) {
  9440. auto result = cli.Get("/hi");
  9441. ASSERT_TRUE(result);
  9442. EXPECT_EQ(StatusCode::OK_200, result->status);
  9443. if (i == keep_alive_max_count - 1) {
  9444. EXPECT_EQ("close", result->get_header_value("Connection"));
  9445. } else {
  9446. EXPECT_FALSE(result->has_header("Connection"));
  9447. }
  9448. }
  9449. }
  9450. TEST(KeepAliveTest, Issue1041) {
  9451. Server svr;
  9452. svr.set_keep_alive_timeout(3);
  9453. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9454. res.set_content("Hello World!", "text/plain");
  9455. });
  9456. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9457. auto se = detail::scope_exit([&] {
  9458. svr.stop();
  9459. listen_thread.join();
  9460. ASSERT_FALSE(svr.is_running());
  9461. });
  9462. svr.wait_until_ready();
  9463. Client cli(HOST, PORT);
  9464. cli.set_keep_alive(true);
  9465. auto result = cli.Get("/hi");
  9466. ASSERT_TRUE(result);
  9467. EXPECT_EQ(StatusCode::OK_200, result->status);
  9468. std::this_thread::sleep_for(std::chrono::seconds(5));
  9469. result = cli.Get("/hi");
  9470. ASSERT_TRUE(result);
  9471. EXPECT_EQ(StatusCode::OK_200, result->status);
  9472. }
  9473. TEST(KeepAliveTest, Issue1959) {
  9474. Server svr;
  9475. svr.set_keep_alive_timeout(5);
  9476. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  9477. res.set_content("a", "text/plain");
  9478. });
  9479. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9480. auto se = detail::scope_exit([&] {
  9481. if (!svr.is_running()) return;
  9482. svr.stop();
  9483. listen_thread.join();
  9484. ASSERT_FALSE(svr.is_running());
  9485. });
  9486. svr.wait_until_ready();
  9487. Client cli("localhost", PORT);
  9488. cli.set_keep_alive(true);
  9489. using namespace std::chrono;
  9490. auto start = steady_clock::now();
  9491. cli.Get("/a");
  9492. svr.stop();
  9493. listen_thread.join();
  9494. auto end = steady_clock::now();
  9495. auto elapsed = duration_cast<milliseconds>(end - start).count();
  9496. EXPECT_LT(elapsed, 5000);
  9497. }
  9498. #ifdef CPPHTTPLIB_SSL_ENABLED
  9499. TEST(KeepAliveTest, SSLClientReconnection) {
  9500. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9501. ASSERT_TRUE(svr.is_valid());
  9502. svr.set_keep_alive_timeout(1);
  9503. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9504. res.set_content("Hello World!", "text/plain");
  9505. });
  9506. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9507. auto se = detail::scope_exit([&] {
  9508. svr.stop();
  9509. listen_thread.join();
  9510. ASSERT_FALSE(svr.is_running());
  9511. });
  9512. svr.wait_until_ready();
  9513. SSLClient cli(HOST, PORT);
  9514. cli.enable_server_certificate_verification(false);
  9515. cli.set_keep_alive(true);
  9516. auto result = cli.Get("/hi");
  9517. ASSERT_TRUE(result);
  9518. EXPECT_EQ(StatusCode::OK_200, result->status);
  9519. result = cli.Get("/hi");
  9520. ASSERT_TRUE(result);
  9521. EXPECT_EQ(StatusCode::OK_200, result->status);
  9522. std::this_thread::sleep_for(std::chrono::seconds(2));
  9523. // Recoonect
  9524. result = cli.Get("/hi");
  9525. ASSERT_TRUE(result);
  9526. EXPECT_EQ(StatusCode::OK_200, result->status);
  9527. result = cli.Get("/hi");
  9528. ASSERT_TRUE(result);
  9529. EXPECT_EQ(StatusCode::OK_200, result->status);
  9530. }
  9531. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  9532. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9533. ASSERT_TRUE(svr.is_valid());
  9534. svr.set_keep_alive_timeout(1);
  9535. std::string content = "reconnect";
  9536. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  9537. res.set_content("Hello World!", "text/plain");
  9538. });
  9539. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9540. auto se = detail::scope_exit([&] {
  9541. svr.stop();
  9542. listen_thread.join();
  9543. ASSERT_FALSE(svr.is_running());
  9544. });
  9545. svr.wait_until_ready();
  9546. SSLClient cli(HOST, PORT);
  9547. cli.enable_server_certificate_verification(false);
  9548. cli.set_keep_alive(true);
  9549. auto result = cli.Post(
  9550. "/hi", content.size(),
  9551. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9552. sink.write(content.c_str(), content.size());
  9553. return true;
  9554. },
  9555. "text/plain");
  9556. ASSERT_TRUE(result);
  9557. EXPECT_EQ(200, result->status);
  9558. std::this_thread::sleep_for(std::chrono::seconds(2));
  9559. // Recoonect
  9560. result = cli.Post(
  9561. "/hi", content.size(),
  9562. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9563. sink.write(content.c_str(), content.size());
  9564. return true;
  9565. },
  9566. "text/plain");
  9567. ASSERT_TRUE(result);
  9568. EXPECT_EQ(200, result->status);
  9569. result = cli.Post(
  9570. "/hi", content.size(),
  9571. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9572. sink.write(content.c_str(), content.size());
  9573. return true;
  9574. },
  9575. "text/plain");
  9576. ASSERT_TRUE(result);
  9577. EXPECT_EQ(200, result->status);
  9578. }
  9579. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  9580. using namespace httplib::tls;
  9581. {
  9582. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9583. ASSERT_TRUE(svr.is_valid());
  9584. svr.Get("/sni", [&](const Request &req, Response &res) {
  9585. std::string expected = req.sni();
  9586. EXPECT_EQ(expected, req.get_param_value("expected"));
  9587. res.set_content("ok", "text/plain");
  9588. });
  9589. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9590. auto se = detail::scope_exit([&] {
  9591. svr.stop();
  9592. listen_thread.join();
  9593. ASSERT_FALSE(svr.is_running());
  9594. });
  9595. svr.wait_until_ready();
  9596. {
  9597. SSLClient cli("localhost", PORT);
  9598. cli.enable_server_certificate_verification(false);
  9599. auto res = cli.Get("/sni?expected=localhost");
  9600. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9601. }
  9602. {
  9603. SSLClient cli("::1", PORT);
  9604. cli.enable_server_certificate_verification(false);
  9605. auto res = cli.Get("/sni?expected=");
  9606. // NOTE: This may fail if the server is listening on IPv4 only
  9607. // (e.g., when localhost resolves to 127.0.0.1 only)
  9608. if (res) {
  9609. EXPECT_EQ(StatusCode::OK_200, res->status);
  9610. } else {
  9611. EXPECT_EQ(Error::Connection, res.error());
  9612. }
  9613. }
  9614. }
  9615. }
  9616. #endif
  9617. TEST(ClientProblemDetectionTest, ContentProvider) {
  9618. Server svr;
  9619. size_t content_length = 1024 * 1024;
  9620. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9621. res.set_content_provider(
  9622. content_length, "text/plain",
  9623. [&](size_t offset, size_t length, DataSink &sink) {
  9624. auto out_len = std::min(length, static_cast<size_t>(1024));
  9625. std::string out(out_len, '@');
  9626. sink.write(out.data(), out_len);
  9627. return offset < 4096;
  9628. },
  9629. [](bool success) { ASSERT_FALSE(success); });
  9630. });
  9631. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  9632. res.set_content_provider(
  9633. 0, "text/plain",
  9634. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  9635. EXPECT_TRUE(false);
  9636. return true;
  9637. },
  9638. [](bool success) { ASSERT_FALSE(success); });
  9639. });
  9640. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9641. auto se = detail::scope_exit([&] {
  9642. svr.stop();
  9643. listen_thread.join();
  9644. ASSERT_FALSE(svr.is_running());
  9645. });
  9646. svr.wait_until_ready();
  9647. Client cli("localhost", PORT);
  9648. {
  9649. auto res = cli.Get("/hi", [&](const char * /*data*/,
  9650. size_t /*data_length*/) { return false; });
  9651. ASSERT_FALSE(res);
  9652. }
  9653. {
  9654. auto res = cli.Get("/empty", [&](const char * /*data*/,
  9655. size_t /*data_length*/) { return false; });
  9656. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9657. }
  9658. }
  9659. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  9660. // A provider that reports success without writing anything and without
  9661. // calling done() used to be handed the same offset and length again on every
  9662. // pass, so it spun for as long as the peer stayed connected.
  9663. Server svr;
  9664. svr.Post("/", [](const Request & /*req*/, Response &res) {
  9665. res.set_content("ok", "text/plain");
  9666. });
  9667. auto port = svr.bind_to_any_port(HOST);
  9668. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  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. std::atomic<int> call_count{0};
  9676. Client cli(HOST, port);
  9677. auto res = cli.Post(
  9678. "/", 1024,
  9679. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  9680. // Give up after enough passes to show the spin, so that losing the
  9681. // check below fails this test instead of hanging it.
  9682. return ++call_count < 100;
  9683. },
  9684. "text/plain");
  9685. ASSERT_FALSE(res);
  9686. EXPECT_EQ(Error::Write, res.error());
  9687. EXPECT_EQ(1, call_count.load());
  9688. }
  9689. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  9690. // A writer only has to assign `write`. The other three used to be left as
  9691. // empty std::functions, so a provider calling one threw
  9692. // std::bad_function_call out of the thread running it and took the whole
  9693. // process down.
  9694. DataSink sink;
  9695. std::string written;
  9696. sink.write = [&](const char *data, size_t data_len) {
  9697. written.append(data, data_len);
  9698. return true;
  9699. };
  9700. EXPECT_TRUE(sink.is_writable());
  9701. sink.done();
  9702. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  9703. EXPECT_TRUE(written.empty());
  9704. }
  9705. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  9706. // A sink that cannot carry trailers still has to finish.
  9707. DataSink sink;
  9708. auto done_count = 0;
  9709. sink.done = [&]() { done_count++; };
  9710. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  9711. EXPECT_EQ(1, done_count);
  9712. }
  9713. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  9714. Server svr;
  9715. const std::string body(4096, 'x');
  9716. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  9717. res.set_content_provider(body.size(), "text/plain",
  9718. [&](size_t offset, size_t length, DataSink &sink) {
  9719. sink.write(body.data() + offset, length);
  9720. sink.done();
  9721. return true;
  9722. });
  9723. });
  9724. auto port = svr.bind_to_any_port(HOST);
  9725. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9726. auto se = detail::scope_exit([&] {
  9727. svr.stop();
  9728. listen_thread.join();
  9729. ASSERT_FALSE(svr.is_running());
  9730. });
  9731. svr.wait_until_ready();
  9732. Client cli(HOST, port);
  9733. auto res = cli.Get("/");
  9734. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9735. EXPECT_EQ(StatusCode::OK_200, res->status);
  9736. EXPECT_EQ(body, res->body);
  9737. }
  9738. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  9739. Server svr;
  9740. svr.Get("/", [](const Request & /*req*/, Response &res) {
  9741. res.set_content_provider(
  9742. 1024, "text/plain",
  9743. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9744. sink.write("hello", 5);
  9745. sink.done(); // short of the 1024 bytes the response promised
  9746. return true;
  9747. });
  9748. });
  9749. auto port = svr.bind_to_any_port(HOST);
  9750. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9751. auto se = detail::scope_exit([&] {
  9752. svr.stop();
  9753. listen_thread.join();
  9754. ASSERT_FALSE(svr.is_running());
  9755. });
  9756. svr.wait_until_ready();
  9757. Client cli(HOST, port);
  9758. cli.set_read_timeout(5, 0);
  9759. // The response is short of its Content-Length, so the client cannot read a
  9760. // complete body. What matters is that this returns at all: a no-op done()
  9761. // would leave the writer looping over a provider that never makes progress.
  9762. auto res = cli.Get("/");
  9763. EXPECT_FALSE(res);
  9764. }
  9765. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9766. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  9767. // The compressed path builds the whole body before connecting, so this
  9768. // fails client-side and never reaches a server.
  9769. Client cli(HOST, PORT);
  9770. cli.set_compress(true);
  9771. auto res = cli.Post(
  9772. "/", 1024,
  9773. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9774. sink.write("hello", 5);
  9775. sink.done(); // short of the 1024 bytes the request announced
  9776. return true;
  9777. },
  9778. "text/plain");
  9779. ASSERT_FALSE(res);
  9780. EXPECT_EQ(Error::Write, res.error());
  9781. }
  9782. #endif
  9783. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  9784. Server svr;
  9785. svr.set_error_handler([](Request const &, Response &res) -> void {
  9786. res.set_chunked_content_provider(
  9787. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  9788. sink.os << "hello";
  9789. sink.os << "world";
  9790. sink.done();
  9791. return true;
  9792. });
  9793. });
  9794. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9795. auto se = detail::scope_exit([&] {
  9796. svr.stop();
  9797. listen_thread.join();
  9798. ASSERT_FALSE(svr.is_running());
  9799. });
  9800. svr.wait_until_ready();
  9801. Client cli("localhost", PORT);
  9802. auto res = cli.Get("/");
  9803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9804. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9805. EXPECT_EQ("helloworld", res->body);
  9806. }
  9807. TEST(LongPollingTest, ClientCloseDetection) {
  9808. Server svr;
  9809. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  9810. res.set_chunked_content_provider(
  9811. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  9812. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  9813. sink.os << "hello";
  9814. auto count = 10;
  9815. while (count > 0 && sink.is_writable()) {
  9816. this_thread::sleep_for(chrono::milliseconds(10));
  9817. count--;
  9818. }
  9819. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  9820. return true;
  9821. });
  9822. });
  9823. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9824. auto se = detail::scope_exit([&] {
  9825. svr.stop();
  9826. listen_thread.join();
  9827. ASSERT_FALSE(svr.is_running());
  9828. });
  9829. svr.wait_until_ready();
  9830. Client cli("localhost", PORT);
  9831. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  9832. EXPECT_EQ("hello", string(data, data_length));
  9833. return false; // close the socket immediately.
  9834. });
  9835. ASSERT_FALSE(res);
  9836. }
  9837. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  9838. Server svr;
  9839. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  9840. res.set_chunked_content_provider(
  9841. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  9842. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  9843. sink.os << "hello";
  9844. EXPECT_TRUE(sink.os.good());
  9845. // Wait for the client to close the connection
  9846. auto count = 10;
  9847. while (count > 0 && sink.is_writable()) {
  9848. this_thread::sleep_for(chrono::milliseconds(10));
  9849. count--;
  9850. }
  9851. // After client disconnect, write repeatedly until the socket
  9852. // write actually fails (small writes may be absorbed by the
  9853. // kernel buffer)
  9854. std::string chunk(1024, 'x');
  9855. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  9856. sink.os << chunk;
  9857. }
  9858. EXPECT_TRUE(sink.os.fail());
  9859. return true;
  9860. });
  9861. });
  9862. auto port = svr.bind_to_any_port("localhost");
  9863. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9864. auto se = detail::scope_exit([&] {
  9865. svr.stop();
  9866. listen_thread.join();
  9867. ASSERT_FALSE(svr.is_running());
  9868. });
  9869. svr.wait_until_ready();
  9870. Client cli("localhost", port);
  9871. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  9872. EXPECT_EQ("hello", string(data, data_length));
  9873. return false; // close the socket immediately.
  9874. });
  9875. ASSERT_FALSE(res);
  9876. }
  9877. TEST(GetWithParametersTest, GetWithParameters) {
  9878. Server svr;
  9879. svr.Get("/", [&](const Request &req, Response &) {
  9880. EXPECT_EQ("world", req.get_param_value("hello"));
  9881. EXPECT_EQ("world2", req.get_param_value("hello2"));
  9882. EXPECT_EQ("world3", req.get_param_value("hello3"));
  9883. });
  9884. svr.Get("/params", [&](const Request &req, Response &) {
  9885. EXPECT_EQ("world", req.get_param_value("hello"));
  9886. EXPECT_EQ("world2", req.get_param_value("hello2"));
  9887. EXPECT_EQ("world3", req.get_param_value("hello3"));
  9888. });
  9889. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  9890. EXPECT_EQ("resource-id", req.matches[1]);
  9891. EXPECT_EQ("foo", req.get_param_value("param1"));
  9892. EXPECT_EQ("bar", req.get_param_value("param2"));
  9893. });
  9894. svr.Get("/users/:id", [&](const Request &req, Response &) {
  9895. EXPECT_EQ("user-id", req.path_params.at("id"));
  9896. EXPECT_EQ("foo", req.get_param_value("param1"));
  9897. EXPECT_EQ("bar", req.get_param_value("param2"));
  9898. });
  9899. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  9900. auto se = detail::scope_exit([&] {
  9901. svr.stop();
  9902. listen_thread.join();
  9903. ASSERT_FALSE(svr.is_running());
  9904. });
  9905. svr.wait_until_ready();
  9906. {
  9907. Client cli(HOST, PORT);
  9908. Params params;
  9909. params.emplace("hello", "world");
  9910. params.emplace("hello2", "world2");
  9911. params.emplace("hello3", "world3");
  9912. auto res = cli.Get("/", params, Headers{});
  9913. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9914. EXPECT_EQ(StatusCode::OK_200, res->status);
  9915. }
  9916. {
  9917. Client cli(HOST, PORT);
  9918. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  9919. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9920. EXPECT_EQ(StatusCode::OK_200, res->status);
  9921. }
  9922. {
  9923. Client cli(HOST, PORT);
  9924. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  9925. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9926. EXPECT_EQ(StatusCode::OK_200, res->status);
  9927. }
  9928. {
  9929. Client cli(HOST, PORT);
  9930. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  9931. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9932. EXPECT_EQ(StatusCode::OK_200, res->status);
  9933. }
  9934. }
  9935. TEST(GetWithParametersTest, GetWithParameters2) {
  9936. Server svr;
  9937. svr.Get("/", [&](const Request &req, Response &res) {
  9938. auto text = req.get_param_value("hello");
  9939. res.set_content(text, "text/plain");
  9940. });
  9941. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9942. auto se = detail::scope_exit([&] {
  9943. svr.stop();
  9944. listen_thread.join();
  9945. ASSERT_FALSE(svr.is_running());
  9946. });
  9947. svr.wait_until_ready();
  9948. Client cli("localhost", PORT);
  9949. Params params;
  9950. params.emplace("hello", "world");
  9951. std::string body;
  9952. auto res = cli.Get("/", params, Headers{},
  9953. [&](const char *data, size_t data_length) {
  9954. body.append(data, data_length);
  9955. return true;
  9956. });
  9957. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9958. EXPECT_EQ(StatusCode::OK_200, res->status);
  9959. EXPECT_EQ("world", body);
  9960. }
  9961. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  9962. Server svr;
  9963. svr.Get("/search", [&](const Request &req, Response &res) {
  9964. auto q = req.get_param_value("q");
  9965. res.set_content(q, "text/plain");
  9966. });
  9967. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9968. auto se = detail::scope_exit([&] {
  9969. svr.stop();
  9970. listen_thread.join();
  9971. ASSERT_FALSE(svr.is_running());
  9972. });
  9973. svr.wait_until_ready();
  9974. Client cli("localhost", PORT);
  9975. // Verify that Get(path, params) works without requiring Headers argument
  9976. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  9977. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9978. EXPECT_EQ(StatusCode::OK_200, res->status);
  9979. EXPECT_EQ("cpp-httplib", res->body);
  9980. }
  9981. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  9982. auto host = "httpbingo.org";
  9983. auto path = std::string{"/range/32"};
  9984. #ifdef CPPHTTPLIB_SSL_ENABLED
  9985. SSLClient cli(host);
  9986. #else
  9987. Client cli(host);
  9988. #endif
  9989. cli.set_default_headers({make_range_header({{1, 10}})});
  9990. cli.set_connection_timeout(5);
  9991. {
  9992. auto res = cli.Get(path);
  9993. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9994. EXPECT_EQ("bcdefghijk", res->body);
  9995. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  9996. }
  9997. {
  9998. auto res = cli.Get(path);
  9999. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10000. EXPECT_EQ("bcdefghijk", res->body);
  10001. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10002. }
  10003. }
  10004. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  10005. Server svr;
  10006. svr.set_default_headers({{"Hello", "World"}});
  10007. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  10008. res.set_content("ok", "text/plain");
  10009. });
  10010. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10011. auto se = detail::scope_exit([&] {
  10012. svr.stop();
  10013. listen_thread.join();
  10014. ASSERT_FALSE(svr.is_running());
  10015. });
  10016. svr.wait_until_ready();
  10017. Client cli("localhost", PORT);
  10018. auto res = cli.Get("/");
  10019. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10020. EXPECT_EQ(StatusCode::OK_200, res->status);
  10021. EXPECT_EQ("ok", res->body);
  10022. EXPECT_EQ("World", res->get_header_value("Hello"));
  10023. }
  10024. #ifdef CPPHTTPLIB_SSL_ENABLED
  10025. TEST(KeepAliveTest, ReadTimeoutSSL) {
  10026. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10027. ASSERT_TRUE(svr.is_valid());
  10028. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10029. std::this_thread::sleep_for(std::chrono::seconds(2));
  10030. res.set_content("a", "text/plain");
  10031. });
  10032. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10033. res.set_content("b", "text/plain");
  10034. });
  10035. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10036. auto se = detail::scope_exit([&] {
  10037. svr.stop();
  10038. listen_thread.join();
  10039. ASSERT_FALSE(svr.is_running());
  10040. });
  10041. svr.wait_until_ready();
  10042. SSLClient cli("localhost", PORT);
  10043. cli.enable_server_certificate_verification(false);
  10044. cli.set_keep_alive(true);
  10045. cli.set_read_timeout(std::chrono::seconds(1));
  10046. auto resa = cli.Get("/a");
  10047. ASSERT_TRUE(!resa);
  10048. EXPECT_EQ(Error::Read, resa.error());
  10049. auto resb = cli.Get("/b");
  10050. ASSERT_TRUE(resb);
  10051. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10052. EXPECT_EQ("b", resb->body);
  10053. }
  10054. #endif
  10055. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  10056. protected:
  10057. ServerTestWithAI_PASSIVE()
  10058. : cli_(HOST, PORT)
  10059. #ifdef CPPHTTPLIB_SSL_ENABLED
  10060. ,
  10061. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10062. #endif
  10063. {
  10064. #ifdef CPPHTTPLIB_SSL_ENABLED
  10065. cli_.enable_server_certificate_verification(false);
  10066. #endif
  10067. }
  10068. virtual void SetUp() {
  10069. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10070. res.set_content("Hello World!", "text/plain");
  10071. });
  10072. t_ = thread(
  10073. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  10074. svr_.wait_until_ready();
  10075. }
  10076. virtual void TearDown() {
  10077. svr_.stop();
  10078. t_.join();
  10079. }
  10080. #ifdef CPPHTTPLIB_SSL_ENABLED
  10081. SSLClient cli_;
  10082. SSLServer svr_;
  10083. #else
  10084. Client cli_;
  10085. Server svr_;
  10086. #endif
  10087. thread t_;
  10088. };
  10089. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  10090. auto res = cli_.Get("/hi");
  10091. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10092. EXPECT_EQ(StatusCode::OK_200, res->status);
  10093. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  10094. EXPECT_EQ("Hello World!", res->body);
  10095. }
  10096. class ServerUpDownTest : public ::testing::Test {
  10097. protected:
  10098. ServerUpDownTest() : cli_(HOST, PORT) {}
  10099. virtual void SetUp() {
  10100. t_ = thread([&]() {
  10101. svr_.bind_to_any_port(HOST);
  10102. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  10103. ASSERT_TRUE(svr_.listen_after_bind());
  10104. });
  10105. svr_.wait_until_ready();
  10106. }
  10107. virtual void TearDown() {
  10108. svr_.stop();
  10109. t_.join();
  10110. }
  10111. Client cli_;
  10112. Server svr_;
  10113. thread t_;
  10114. };
  10115. TEST_F(ServerUpDownTest, QuickStartStop) {
  10116. // Should not crash, especially when run with
  10117. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  10118. }
  10119. class PayloadMaxLengthTest : public ::testing::Test {
  10120. protected:
  10121. PayloadMaxLengthTest()
  10122. : cli_(HOST, PORT)
  10123. #ifdef CPPHTTPLIB_SSL_ENABLED
  10124. ,
  10125. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10126. #endif
  10127. {
  10128. #ifdef CPPHTTPLIB_SSL_ENABLED
  10129. cli_.enable_server_certificate_verification(false);
  10130. #endif
  10131. }
  10132. virtual void SetUp() {
  10133. svr_.set_payload_max_length(8);
  10134. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  10135. res.set_content("test", "text/plain");
  10136. });
  10137. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  10138. svr_.wait_until_ready();
  10139. }
  10140. virtual void TearDown() {
  10141. svr_.stop();
  10142. t_.join();
  10143. }
  10144. #ifdef CPPHTTPLIB_SSL_ENABLED
  10145. SSLClient cli_;
  10146. SSLServer svr_;
  10147. #else
  10148. Client cli_;
  10149. Server svr_;
  10150. #endif
  10151. thread t_;
  10152. };
  10153. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  10154. auto res = cli_.Post("/test", "123456789", "text/plain");
  10155. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10156. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10157. res = cli_.Post("/test", "12345678", "text/plain");
  10158. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10159. EXPECT_EQ(StatusCode::OK_200, res->status);
  10160. }
  10161. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  10162. // Test chunked encoding with payload exceeding the 8-byte limit
  10163. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  10164. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  10165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10166. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10167. }
  10168. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  10169. // Test chunked encoding with payload within the 8-byte limit
  10170. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  10171. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  10172. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10173. EXPECT_EQ(StatusCode::OK_200, res->status);
  10174. }
  10175. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  10176. // Test using send_request to send chunked data exceeding payload limit
  10177. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  10178. "Host: " +
  10179. std::string(HOST) + ":" + std::to_string(PORT) +
  10180. "\r\n"
  10181. "Transfer-Encoding: chunked\r\n"
  10182. "Connection: close\r\n"
  10183. "\r\n"
  10184. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  10185. "0123456789\r\n"
  10186. "0\r\n" // End chunk
  10187. "\r\n";
  10188. std::string response;
  10189. bool result = send_request(1, chunked_request, &response);
  10190. if (!result) {
  10191. // If send_request fails, it might be because the server closed the
  10192. // connection due to payload limit enforcement, which is acceptable
  10193. SUCCEED()
  10194. << "Server rejected oversized chunked request (connection closed)";
  10195. } else {
  10196. // If we got a response, check if it's an error response or connection was
  10197. // closed early Short response length indicates connection was closed due to
  10198. // payload limit
  10199. if (response.length() <= 10) {
  10200. SUCCEED() << "Server closed connection for oversized chunked request";
  10201. } else {
  10202. // Check for error status codes
  10203. EXPECT_TRUE(response.find("413") != std::string::npos ||
  10204. response.find("Payload Too Large") != std::string::npos ||
  10205. response.find("400") != std::string::npos);
  10206. }
  10207. }
  10208. }
  10209. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  10210. // Test request without Content-Length header exceeding payload limit
  10211. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10212. "Host: " +
  10213. std::string(HOST) + ":" +
  10214. std::to_string(PORT) +
  10215. "\r\n"
  10216. "Connection: close\r\n"
  10217. "\r\n";
  10218. // Add payload exceeding the 8-byte limit
  10219. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  10220. request_without_content_length += large_payload;
  10221. std::string response;
  10222. bool result = send_request(1, request_without_content_length, &response);
  10223. if (!result) {
  10224. // If send_request fails, server likely closed connection due to payload
  10225. // limit
  10226. SUCCEED() << "Server rejected oversized request without Content-Length "
  10227. "(connection closed)";
  10228. } else {
  10229. // Check if server responded with error or closed connection early
  10230. if (response.length() <= 10) {
  10231. SUCCEED() << "Server closed connection for oversized request without "
  10232. "Content-Length";
  10233. } else {
  10234. // Check for error status codes
  10235. EXPECT_TRUE(response.find("413") != std::string::npos ||
  10236. response.find("Payload Too Large") != std::string::npos ||
  10237. response.find("400") != std::string::npos);
  10238. }
  10239. }
  10240. }
  10241. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  10242. // Test request without Content-Length header within payload limit
  10243. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10244. "Host: " +
  10245. std::string(HOST) + ":" +
  10246. std::to_string(PORT) +
  10247. "\r\n"
  10248. "Connection: close\r\n"
  10249. "\r\n";
  10250. // Add payload within the 8-byte limit
  10251. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  10252. request_without_content_length += small_payload;
  10253. std::string response;
  10254. bool result = send_request(1, request_without_content_length, &response);
  10255. // For requests without Content-Length, the server may have different behavior
  10256. // The key is that it should not reject due to payload limit for small
  10257. // payloads
  10258. if (result) {
  10259. // Check for any HTTP response (success or error, but not connection closed)
  10260. if (response.length() > 10) {
  10261. SUCCEED()
  10262. << "Server processed request without Content-Length within limit";
  10263. } else {
  10264. // Short response might indicate connection closed, which is acceptable
  10265. SUCCEED() << "Server closed connection for request without "
  10266. "Content-Length (acceptable behavior)";
  10267. }
  10268. } else {
  10269. // Connection failure might be due to protocol requirements
  10270. SUCCEED() << "Connection issue with request without Content-Length "
  10271. "(environment-specific)";
  10272. }
  10273. }
  10274. class LargePayloadMaxLengthTest : public ::testing::Test {
  10275. protected:
  10276. LargePayloadMaxLengthTest()
  10277. : cli_(HOST, PORT)
  10278. #ifdef CPPHTTPLIB_SSL_ENABLED
  10279. ,
  10280. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10281. #endif
  10282. {
  10283. #ifdef CPPHTTPLIB_SSL_ENABLED
  10284. cli_.enable_server_certificate_verification(false);
  10285. #endif
  10286. }
  10287. virtual void SetUp() {
  10288. // Set 10MB payload limit
  10289. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  10290. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  10291. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  10292. res.set_content("Large payload test", "text/plain");
  10293. });
  10294. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  10295. svr_.wait_until_ready();
  10296. }
  10297. virtual void TearDown() {
  10298. svr_.stop();
  10299. t_.join();
  10300. }
  10301. #ifdef CPPHTTPLIB_SSL_ENABLED
  10302. SSLClient cli_;
  10303. SSLServer svr_;
  10304. #else
  10305. Client cli_;
  10306. Server svr_;
  10307. #endif
  10308. thread t_;
  10309. };
  10310. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  10311. // Test chunked encoding with payload within 10MB limit
  10312. std::string medium_payload(5 * 1024 * 1024,
  10313. 'A'); // 5MB payload, within 10MB limit
  10314. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  10315. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10316. EXPECT_EQ(StatusCode::OK_200, res->status);
  10317. }
  10318. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  10319. // Test chunked encoding with payload exceeding 10MB limit
  10320. std::string large_payload(12 * 1024 * 1024,
  10321. 'B'); // 12MB payload, exceeds 10MB limit
  10322. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  10323. // Server may either return 413 or close the connection
  10324. if (res) {
  10325. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10326. } else {
  10327. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  10328. }
  10329. }
  10330. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  10331. // Test request without Content-Length header within 10MB limit
  10332. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10333. "Host: " +
  10334. std::string(HOST) + ":" +
  10335. std::to_string(PORT) +
  10336. "\r\n"
  10337. "Connection: close\r\n"
  10338. "\r\n";
  10339. // Add 1MB payload (within 10MB limit)
  10340. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  10341. request_without_content_length += medium_payload;
  10342. std::string response;
  10343. bool result = send_request(5, request_without_content_length, &response);
  10344. if (result) {
  10345. // Should get a proper HTTP response for payloads within limit
  10346. if (response.length() > 10) {
  10347. SUCCEED() << "Server processed 1MB request without Content-Length within "
  10348. "10MB limit";
  10349. } else {
  10350. SUCCEED() << "Server closed connection (acceptable behavior for no "
  10351. "Content-Length)";
  10352. }
  10353. } else {
  10354. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  10355. }
  10356. }
  10357. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  10358. // Test request without Content-Length header exceeding 10MB limit
  10359. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10360. "Host: " +
  10361. std::string(HOST) + ":" +
  10362. std::to_string(PORT) +
  10363. "\r\n"
  10364. "Connection: close\r\n"
  10365. "\r\n";
  10366. // Add 12MB payload (exceeds 10MB limit)
  10367. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  10368. request_without_content_length += large_payload;
  10369. std::string response;
  10370. bool result = send_request(10, request_without_content_length, &response);
  10371. if (!result) {
  10372. // Server should close connection due to payload limit
  10373. SUCCEED() << "Server rejected 12MB request without Content-Length "
  10374. "(connection closed)";
  10375. } else {
  10376. // Check for error response
  10377. if (response.length() <= 10) {
  10378. SUCCEED()
  10379. << "Server closed connection for 12MB request exceeding 10MB limit";
  10380. } else {
  10381. EXPECT_TRUE(response.find("413") != std::string::npos ||
  10382. response.find("Payload Too Large") != std::string::npos ||
  10383. response.find("400") != std::string::npos);
  10384. }
  10385. }
  10386. }
  10387. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10388. // `payload_max_length` is not enforced on decompressed body in ContentReader
  10389. // path.
  10390. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  10391. Server svr;
  10392. const size_t LIMIT = 64 * 1024; // 64KB
  10393. svr.set_payload_max_length(LIMIT);
  10394. size_t total = 0;
  10395. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  10396. const ContentReader &content_reader) {
  10397. content_reader([&](const char * /*data*/, size_t len) {
  10398. total += len;
  10399. return true;
  10400. });
  10401. res.status = 200;
  10402. res.set_content("stream_ok", "text/plain");
  10403. });
  10404. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10405. auto se = detail::scope_exit([&] {
  10406. svr.stop();
  10407. thread.join();
  10408. ASSERT_FALSE(svr.is_running());
  10409. });
  10410. svr.wait_until_ready();
  10411. // Prepare 256KB raw data and gzip-compress it
  10412. std::string raw(256 * 1024, 'A');
  10413. std::string gz;
  10414. {
  10415. z_stream zs{};
  10416. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  10417. Z_DEFAULT_STRATEGY);
  10418. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  10419. zs.avail_in = static_cast<uInt>(raw.size());
  10420. char outbuf[4096];
  10421. int ret;
  10422. do {
  10423. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  10424. zs.avail_out = sizeof(outbuf);
  10425. ret = deflate(&zs, Z_FINISH);
  10426. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  10427. } while (ret != Z_STREAM_END);
  10428. deflateEnd(&zs);
  10429. }
  10430. Client cli(HOST, PORT);
  10431. cli.set_connection_timeout(std::chrono::seconds(5));
  10432. Headers headers = {{"Content-Encoding", "gzip"}};
  10433. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  10434. "application/octet-stream");
  10435. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10436. // Server must reject oversized decompressed payloads with 413.
  10437. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10438. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  10439. EXPECT_LE(total, LIMIT);
  10440. }
  10441. #ifndef CPPHTTPLIB_SSL_ENABLED
  10442. // For a request with neither Content-Length nor Transfer-Encoding, the
  10443. // non-SSL raw-socket fallback in read_content_core() used to hand the
  10444. // compressed wire bytes straight to the ContentReader without ever routing
  10445. // them through the decompressor, so payload_max_length_ only bounded the
  10446. // compressed size on the wire, not the decompressed size.
  10447. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  10448. Server svr;
  10449. const size_t LIMIT = 64 * 1024; // 64KB
  10450. svr.set_payload_max_length(LIMIT);
  10451. size_t total = 0;
  10452. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  10453. const ContentReader &content_reader) {
  10454. content_reader([&](const char * /*data*/, size_t len) {
  10455. total += len;
  10456. return true;
  10457. });
  10458. res.status = 200;
  10459. res.set_content("stream_ok", "text/plain");
  10460. });
  10461. auto port = svr.bind_to_any_port(HOST);
  10462. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  10463. auto se = detail::scope_exit([&] {
  10464. svr.stop();
  10465. thread.join();
  10466. ASSERT_FALSE(svr.is_running());
  10467. });
  10468. svr.wait_until_ready();
  10469. // Prepare 256KB raw data and gzip-compress it, same payload as the
  10470. // StreamingGzipDecompression test above.
  10471. std::string raw(256 * 1024, 'A');
  10472. std::string gz;
  10473. {
  10474. httplib::detail::gzip_compressor compressor;
  10475. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  10476. [&](const char *chunk, size_t len) {
  10477. gz.append(chunk, len);
  10478. return true;
  10479. });
  10480. ASSERT_TRUE(result);
  10481. }
  10482. // Send the gzip body over raw TCP with neither Content-Length nor
  10483. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  10484. // kicks in.
  10485. std::string req = "POST /stream HTTP/1.1\r\n"
  10486. "Host: " +
  10487. std::string(HOST) + ":" + std::to_string(port) +
  10488. "\r\n"
  10489. "Content-Encoding: gzip\r\n"
  10490. "Connection: close\r\n"
  10491. "\r\n" +
  10492. gz;
  10493. std::string response;
  10494. ASSERT_TRUE(send_request(5, req, &response, port));
  10495. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  10496. EXPECT_LE(total, LIMIT);
  10497. }
  10498. #endif
  10499. #endif
  10500. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  10501. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  10502. // the payload must be passed through untouched instead of being rejected.
  10503. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  10504. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  10505. Server svr;
  10506. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  10507. res.set_content(body, "image/jpeg");
  10508. res.set_header("Content-Encoding", "UTF-8");
  10509. });
  10510. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  10511. res.set_content(body, "image/jpeg");
  10512. res.set_header("Content-Encoding", "identity");
  10513. });
  10514. svr.Post("/echo", [](const Request &req, Response &res) {
  10515. res.set_content(req.body, "image/jpeg");
  10516. });
  10517. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10518. auto se = detail::scope_exit([&] {
  10519. svr.stop();
  10520. t.join();
  10521. ASSERT_FALSE(svr.is_running());
  10522. });
  10523. svr.wait_until_ready();
  10524. Client cli(HOST, PORT);
  10525. {
  10526. auto res = cli.Get("/image");
  10527. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10528. EXPECT_EQ(StatusCode::OK_200, res->status);
  10529. EXPECT_EQ(body, res->body);
  10530. }
  10531. {
  10532. auto res = cli.Get("/identity");
  10533. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10534. EXPECT_EQ(StatusCode::OK_200, res->status);
  10535. EXPECT_EQ(body, res->body);
  10536. }
  10537. {
  10538. // The same applies to a request body reaching the server.
  10539. Headers headers = {{"Content-Encoding", "UTF-8"}};
  10540. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  10541. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10542. EXPECT_EQ(StatusCode::OK_200, res->status);
  10543. EXPECT_EQ(body, res->body);
  10544. }
  10545. }
  10546. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  10547. // gzip-encoded response even when the build has no zlib support.
  10548. static const char GZIPPED_HELLO_WORLD[] = {
  10549. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  10550. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  10551. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  10552. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  10553. // A content coding is a whole token, not something the field value merely
  10554. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  10555. // as "fibre" look like Brotli, and turned a multi-coding value like
  10556. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  10557. // it was never meant to see.
  10558. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  10559. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  10560. Server svr;
  10561. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  10562. res.set_content(body, "image/jpeg");
  10563. res.set_header("Content-Encoding", "fibre");
  10564. });
  10565. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  10566. res.set_content(body, "image/jpeg");
  10567. res.set_header("Content-Encoding", "gzip, br");
  10568. });
  10569. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  10570. res.set_content(body, "image/jpeg");
  10571. res.set_header("Content-Encoding", "x-zstd-ish");
  10572. });
  10573. auto port = svr.bind_to_any_port(HOST);
  10574. thread t = thread([&]() { svr.listen_after_bind(); });
  10575. auto se = detail::scope_exit([&] {
  10576. svr.stop();
  10577. t.join();
  10578. ASSERT_FALSE(svr.is_running());
  10579. });
  10580. svr.wait_until_ready();
  10581. Client cli(HOST, port);
  10582. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  10583. auto res = cli.Get(path);
  10584. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  10585. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  10586. // Not a coding we recognize, so the payload comes back untouched
  10587. EXPECT_EQ(body, res->body) << path;
  10588. }
  10589. }
  10590. // A content coding cpp-httplib recognizes but was not built with must be
  10591. // reported as such. Handing the still-compressed payload back to the caller
  10592. // would silently corrupt it.
  10593. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  10594. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  10595. Server svr;
  10596. // "image/jpeg" keeps the server from applying a content coding of its own,
  10597. // so the hand-crafted Content-Encoding below survives.
  10598. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  10599. res.set_content(gzipped, "image/jpeg");
  10600. res.set_header("Content-Encoding", "gzip");
  10601. });
  10602. // Content codings are case-insensitive (RFC 9110 8.4.1).
  10603. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  10604. res.set_content(gzipped, "image/jpeg");
  10605. res.set_header("Content-Encoding", "GZIP");
  10606. });
  10607. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10608. auto se = detail::scope_exit([&] {
  10609. svr.stop();
  10610. t.join();
  10611. ASSERT_FALSE(svr.is_running());
  10612. });
  10613. svr.wait_until_ready();
  10614. Client cli(HOST, PORT);
  10615. {
  10616. auto res = cli.Get("/gzipped");
  10617. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10618. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10619. EXPECT_EQ("Hello World!", res->body);
  10620. #else
  10621. ASSERT_FALSE(res);
  10622. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  10623. #endif
  10624. }
  10625. {
  10626. // open_stream() must behave the same way.
  10627. auto handle = cli.open_stream("GET", "/gzipped");
  10628. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10629. ASSERT_TRUE(handle.is_valid());
  10630. std::string received;
  10631. char buf[256];
  10632. ssize_t n;
  10633. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  10634. received.append(buf, static_cast<size_t>(n));
  10635. }
  10636. EXPECT_EQ("Hello World!", received);
  10637. #else
  10638. EXPECT_FALSE(handle.is_valid());
  10639. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  10640. #endif
  10641. }
  10642. {
  10643. // A differently-cased coding must not be mistaken for an unknown one, or
  10644. // the body would be handed back still compressed.
  10645. auto res = cli.Get("/gzipped-uppercase");
  10646. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10647. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10648. EXPECT_EQ("Hello World!", res->body);
  10649. #else
  10650. ASSERT_FALSE(res);
  10651. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  10652. #endif
  10653. }
  10654. }
  10655. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10656. // A handler serving pre-compressed content (e.g. build-time gzipped static
  10657. // assets) sets Content-Encoding itself. The server used to pick a coding from
  10658. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  10659. // body a second time and appending a second Content-Encoding field line, so
  10660. // clients that decode one coding per listed value handed back raw gzip bytes.
  10661. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  10662. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  10663. Server svr;
  10664. // text/plain is a compressible type, so only the pre-set Content-Encoding
  10665. // keeps the server from applying a coding of its own.
  10666. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  10667. res.set_content(gzipped, "text/plain");
  10668. res.set_header("Content-Encoding", "gzip");
  10669. });
  10670. auto port = svr.bind_to_any_port(HOST);
  10671. thread t = thread([&]() { svr.listen_after_bind(); });
  10672. auto se = detail::scope_exit([&] {
  10673. svr.stop();
  10674. t.join();
  10675. ASSERT_FALSE(svr.is_running());
  10676. });
  10677. svr.wait_until_ready();
  10678. Client cli(HOST, port);
  10679. Headers headers = {{"Accept-Encoding", "gzip"}};
  10680. auto res = cli.Get("/pre-gzipped", headers);
  10681. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10682. EXPECT_EQ(StatusCode::OK_200, res->status);
  10683. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  10684. EXPECT_EQ("Hello World!", res->body);
  10685. }
  10686. // A chunked provider settles its coding where the headers are written and
  10687. // reuses it at write time. Both ends of that have to hold: a handler's own
  10688. // Content-Encoding suppresses the coding, and a response without one is still
  10689. // compressed as it always was.
  10690. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  10691. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  10692. const std::string plain = "Hello World! Hello World! Hello World!";
  10693. Server svr;
  10694. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  10695. res.set_header("Content-Encoding", "gzip");
  10696. res.set_chunked_content_provider(
  10697. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  10698. sink.write(gzipped.data(), gzipped.size());
  10699. sink.done();
  10700. return true;
  10701. });
  10702. });
  10703. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  10704. res.set_chunked_content_provider(
  10705. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  10706. sink.write(plain.data(), plain.size());
  10707. sink.done();
  10708. return true;
  10709. });
  10710. });
  10711. auto port = svr.bind_to_any_port(HOST);
  10712. thread t = thread([&]() { svr.listen_after_bind(); });
  10713. auto se = detail::scope_exit([&] {
  10714. svr.stop();
  10715. t.join();
  10716. ASSERT_FALSE(svr.is_running());
  10717. });
  10718. svr.wait_until_ready();
  10719. Client cli(HOST, port);
  10720. Headers headers = {{"Accept-Encoding", "gzip"}};
  10721. {
  10722. auto res = cli.Get("/pre-gzipped", headers);
  10723. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10724. EXPECT_EQ(StatusCode::OK_200, res->status);
  10725. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  10726. EXPECT_EQ("Hello World!", res->body);
  10727. }
  10728. {
  10729. auto res = cli.Get("/negotiated", headers);
  10730. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10731. EXPECT_EQ(StatusCode::OK_200, res->status);
  10732. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  10733. EXPECT_EQ(plain, res->body);
  10734. }
  10735. }
  10736. #endif
  10737. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  10738. // the same message as the comma-joined one, so both have to be read the same
  10739. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  10740. // single gzip coding, and a body the sender says was encoded twice was handed
  10741. // back after one pass, still compressed but presented as decoded.
  10742. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  10743. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  10744. Server svr;
  10745. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  10746. res.set_content(body, "image/jpeg");
  10747. res.headers.emplace("Content-Encoding", "gzip");
  10748. res.headers.emplace("Content-Encoding", "gzip");
  10749. });
  10750. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  10751. res.set_content(body, "image/jpeg");
  10752. res.set_header("Content-Encoding", "gzip, gzip");
  10753. });
  10754. auto port = svr.bind_to_any_port(HOST);
  10755. thread t = thread([&]() { svr.listen_after_bind(); });
  10756. auto se = detail::scope_exit([&] {
  10757. svr.stop();
  10758. t.join();
  10759. ASSERT_FALSE(svr.is_running());
  10760. });
  10761. svr.wait_until_ready();
  10762. Client cli(HOST, port);
  10763. // Two codings is not something cpp-httplib decodes, so both representations
  10764. // take the pass-through path rather than one of them being gunzipped once.
  10765. for (const char *path : {"/split", "/joined"}) {
  10766. auto res = cli.Get(path);
  10767. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  10768. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  10769. EXPECT_EQ(body, res->body) << path;
  10770. }
  10771. }
  10772. // Regression test for DoS vulnerability: a malicious server sending a response
  10773. // without Content-Length header must not cause unbounded memory consumption on
  10774. // the client side. The client should stop reading after a reasonable limit,
  10775. // similar to the server-side set_payload_max_length protection.
  10776. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  10777. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  10778. #ifndef _WIN32
  10779. signal(SIGPIPE, SIG_IGN);
  10780. #endif
  10781. auto server_thread = std::thread([] {
  10782. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  10783. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10784. default_socket_options(srv);
  10785. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  10786. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  10787. sockaddr_in addr{};
  10788. addr.sin_family = AF_INET;
  10789. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  10790. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10791. int opt = 1;
  10792. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  10793. #ifdef _WIN32
  10794. reinterpret_cast<const char *>(&opt),
  10795. #else
  10796. &opt,
  10797. #endif
  10798. sizeof(opt));
  10799. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10800. ::listen(srv, 1);
  10801. sockaddr_in cli_addr{};
  10802. socklen_t cli_len = sizeof(cli_addr);
  10803. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10804. if (cli != INVALID_SOCKET) {
  10805. char buf[4096];
  10806. ::recv(cli, buf, sizeof(buf), 0);
  10807. // Malicious response: no Content-Length, no chunked encoding
  10808. std::string response_header = "HTTP/1.1 200 OK\r\n"
  10809. "Connection: close\r\n"
  10810. "\r\n";
  10811. ::send(cli,
  10812. #ifdef _WIN32
  10813. static_cast<const char *>(response_header.c_str()),
  10814. static_cast<int>(response_header.size()),
  10815. #else
  10816. response_header.c_str(), response_header.size(),
  10817. #endif
  10818. 0);
  10819. // Send 10MB of data
  10820. std::string chunk(64 * 1024, 'A');
  10821. size_t total_sent = 0;
  10822. while (total_sent < MALICIOUS_DATA_SIZE) {
  10823. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  10824. auto sent = ::send(cli,
  10825. #ifdef _WIN32
  10826. static_cast<const char *>(chunk.c_str()),
  10827. static_cast<int>(to_send),
  10828. #else
  10829. chunk.c_str(), to_send,
  10830. #endif
  10831. 0);
  10832. if (sent <= 0) break;
  10833. total_sent += static_cast<size_t>(sent);
  10834. }
  10835. detail::close_socket(cli);
  10836. }
  10837. detail::close_socket(srv);
  10838. });
  10839. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10840. size_t total_read = 0;
  10841. {
  10842. Client cli("127.0.0.1", PORT + 2);
  10843. cli.set_read_timeout(5, 0);
  10844. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  10845. auto stream = cli.open_stream("GET", "/malicious");
  10846. ASSERT_TRUE(stream.is_valid());
  10847. char buffer[64 * 1024];
  10848. ssize_t n;
  10849. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  10850. total_read += static_cast<size_t>(n);
  10851. }
  10852. } // StreamHandle and Client destroyed here, closing the socket
  10853. server_thread.join();
  10854. // With set_payload_max_length, the client must stop reading before consuming
  10855. // all 10MB. The read loop should be cut off at or near the configured limit.
  10856. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  10857. << "Client read " << total_read << " bytes, exceeding the configured "
  10858. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  10859. }
  10860. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  10861. // the entire response body without truncation.
  10862. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  10863. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  10864. #ifndef _WIN32
  10865. signal(SIGPIPE, SIG_IGN);
  10866. #endif
  10867. auto server_thread = std::thread([] {
  10868. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10869. default_socket_options(srv);
  10870. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  10871. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  10872. sockaddr_in addr{};
  10873. addr.sin_family = AF_INET;
  10874. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  10875. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10876. int opt = 1;
  10877. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  10878. #ifdef _WIN32
  10879. reinterpret_cast<const char *>(&opt),
  10880. #else
  10881. &opt,
  10882. #endif
  10883. sizeof(opt));
  10884. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10885. ::listen(srv, 1);
  10886. sockaddr_in cli_addr{};
  10887. socklen_t cli_len = sizeof(cli_addr);
  10888. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10889. if (cli != INVALID_SOCKET) {
  10890. char buf[4096];
  10891. ::recv(cli, buf, sizeof(buf), 0);
  10892. std::string response_header = "HTTP/1.1 200 OK\r\n"
  10893. "Connection: close\r\n"
  10894. "\r\n";
  10895. ::send(cli,
  10896. #ifdef _WIN32
  10897. static_cast<const char *>(response_header.c_str()),
  10898. static_cast<int>(response_header.size()),
  10899. #else
  10900. response_header.c_str(), response_header.size(),
  10901. #endif
  10902. 0);
  10903. std::string chunk(64 * 1024, 'A');
  10904. size_t total_sent = 0;
  10905. while (total_sent < DATA_SIZE) {
  10906. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  10907. auto sent = ::send(cli,
  10908. #ifdef _WIN32
  10909. static_cast<const char *>(chunk.c_str()),
  10910. static_cast<int>(to_send),
  10911. #else
  10912. chunk.c_str(), to_send,
  10913. #endif
  10914. 0);
  10915. if (sent <= 0) break;
  10916. total_sent += static_cast<size_t>(sent);
  10917. }
  10918. #ifdef _WIN32
  10919. ::shutdown(cli, SD_SEND);
  10920. #else
  10921. ::shutdown(cli, SHUT_WR);
  10922. #endif
  10923. // Drain until the client closes its end, ensuring all data is delivered
  10924. char drain[1024];
  10925. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  10926. detail::close_socket(cli);
  10927. }
  10928. detail::close_socket(srv);
  10929. });
  10930. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10931. size_t total_read = 0;
  10932. {
  10933. Client cli("127.0.0.1", PORT + 2);
  10934. cli.set_read_timeout(5, 0);
  10935. cli.set_payload_max_length(0); // 0 means no limit
  10936. auto stream = cli.open_stream("GET", "/data");
  10937. ASSERT_TRUE(stream.is_valid());
  10938. char buffer[64 * 1024];
  10939. ssize_t n;
  10940. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  10941. total_read += static_cast<size_t>(n);
  10942. }
  10943. }
  10944. server_thread.join();
  10945. EXPECT_EQ(total_read, DATA_SIZE)
  10946. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  10947. << " bytes without truncation, but only read " << total_read << " bytes.";
  10948. }
  10949. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  10950. // enormous Content-Length must not cause the client to pre-allocate a huge
  10951. // response body buffer. The reservation is capped at payload_max_length_, and
  10952. // the read itself fails when the body exceeds the limit.
  10953. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  10954. #ifndef _WIN32
  10955. signal(SIGPIPE, SIG_IGN);
  10956. #endif
  10957. auto server_thread = std::thread([] {
  10958. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10959. default_socket_options(srv);
  10960. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  10961. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  10962. sockaddr_in addr{};
  10963. addr.sin_family = AF_INET;
  10964. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  10965. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10966. int opt = 1;
  10967. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  10968. #ifdef _WIN32
  10969. reinterpret_cast<const char *>(&opt),
  10970. #else
  10971. &opt,
  10972. #endif
  10973. sizeof(opt));
  10974. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10975. ::listen(srv, 1);
  10976. sockaddr_in cli_addr{};
  10977. socklen_t cli_len = sizeof(cli_addr);
  10978. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10979. if (cli != INVALID_SOCKET) {
  10980. char buf[4096];
  10981. ::recv(cli, buf, sizeof(buf), 0);
  10982. // Malicious response: claim a 20GB body but send only a tiny payload.
  10983. std::string response = "HTTP/1.1 200 OK\r\n"
  10984. "Content-Length: 20000000000\r\n"
  10985. "\r\n"
  10986. "abc";
  10987. ::send(cli,
  10988. #ifdef _WIN32
  10989. static_cast<const char *>(response.c_str()),
  10990. static_cast<int>(response.size()),
  10991. #else
  10992. response.c_str(), response.size(),
  10993. #endif
  10994. 0);
  10995. detail::close_socket(cli);
  10996. }
  10997. detail::close_socket(srv);
  10998. });
  10999. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11000. {
  11001. Client cli("127.0.0.1", PORT + 2);
  11002. cli.set_read_timeout(5, 0);
  11003. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  11004. // result in a 20GB pre-allocation. The Get() call is expected to fail
  11005. // (server claims more bytes than payload_max_length permits), but it must
  11006. // not exhaust memory before getting there.
  11007. auto res = cli.Get("/malicious");
  11008. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  11009. }
  11010. server_thread.join();
  11011. }
  11012. // Verify that content_receiver bypasses the default payload_max_length,
  11013. // allowing streaming downloads larger than 100MB without requiring an explicit
  11014. // set_payload_max_length call.
  11015. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  11016. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11017. #ifndef _WIN32
  11018. signal(SIGPIPE, SIG_IGN);
  11019. #endif
  11020. auto server_thread = std::thread([] {
  11021. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11022. default_socket_options(srv);
  11023. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11024. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11025. sockaddr_in addr{};
  11026. addr.sin_family = AF_INET;
  11027. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11028. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11029. int opt = 1;
  11030. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11031. #ifdef _WIN32
  11032. reinterpret_cast<const char *>(&opt),
  11033. #else
  11034. &opt,
  11035. #endif
  11036. sizeof(opt));
  11037. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11038. ::listen(srv, 1);
  11039. sockaddr_in cli_addr{};
  11040. socklen_t cli_len = sizeof(cli_addr);
  11041. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11042. if (cli != INVALID_SOCKET) {
  11043. char buf[4096];
  11044. ::recv(cli, buf, sizeof(buf), 0);
  11045. // Response with Content-Length larger than default 100MB limit
  11046. auto content_length = std::to_string(DATA_SIZE);
  11047. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11048. "Content-Length: " +
  11049. content_length +
  11050. "\r\n"
  11051. "Connection: close\r\n"
  11052. "\r\n";
  11053. ::send(cli,
  11054. #ifdef _WIN32
  11055. static_cast<const char *>(response_header.c_str()),
  11056. static_cast<int>(response_header.size()),
  11057. #else
  11058. response_header.c_str(), response_header.size(),
  11059. #endif
  11060. 0);
  11061. std::string chunk(64 * 1024, 'A');
  11062. size_t total_sent = 0;
  11063. while (total_sent < DATA_SIZE) {
  11064. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11065. auto sent = ::send(cli,
  11066. #ifdef _WIN32
  11067. static_cast<const char *>(chunk.c_str()),
  11068. static_cast<int>(to_send),
  11069. #else
  11070. chunk.c_str(), to_send,
  11071. #endif
  11072. 0);
  11073. if (sent <= 0) break;
  11074. total_sent += static_cast<size_t>(sent);
  11075. }
  11076. detail::close_socket(cli);
  11077. }
  11078. detail::close_socket(srv);
  11079. });
  11080. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11081. size_t total_received = 0;
  11082. {
  11083. Client cli("127.0.0.1", PORT + 2);
  11084. cli.set_read_timeout(10, 0);
  11085. // Do NOT call set_payload_max_length — use the default 100MB limit
  11086. auto res =
  11087. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11088. total_received += data_length;
  11089. return true;
  11090. });
  11091. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11092. EXPECT_EQ(StatusCode::OK_200, res->status);
  11093. }
  11094. server_thread.join();
  11095. EXPECT_EQ(total_received, DATA_SIZE)
  11096. << "With content_receiver, the client should read all " << DATA_SIZE
  11097. << " bytes despite the default 100MB payload_max_length, but only read "
  11098. << total_received << " bytes.";
  11099. }
  11100. // Verify that an explicit set_payload_max_length smaller than the response is
  11101. // enforced even when a content_receiver is used.
  11102. TEST(ClientVulnerabilityTest,
  11103. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  11104. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11105. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  11106. #ifndef _WIN32
  11107. signal(SIGPIPE, SIG_IGN);
  11108. #endif
  11109. auto server_thread = std::thread([] {
  11110. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11111. default_socket_options(srv);
  11112. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11113. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11114. sockaddr_in addr{};
  11115. addr.sin_family = AF_INET;
  11116. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11117. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11118. int opt = 1;
  11119. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11120. #ifdef _WIN32
  11121. reinterpret_cast<const char *>(&opt),
  11122. #else
  11123. &opt,
  11124. #endif
  11125. sizeof(opt));
  11126. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11127. ::listen(srv, 1);
  11128. sockaddr_in cli_addr{};
  11129. socklen_t cli_len = sizeof(cli_addr);
  11130. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11131. if (cli != INVALID_SOCKET) {
  11132. char buf[4096];
  11133. ::recv(cli, buf, sizeof(buf), 0);
  11134. auto content_length = std::to_string(DATA_SIZE);
  11135. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11136. "Content-Length: " +
  11137. content_length +
  11138. "\r\n"
  11139. "Connection: close\r\n"
  11140. "\r\n";
  11141. ::send(cli,
  11142. #ifdef _WIN32
  11143. static_cast<const char *>(response_header.c_str()),
  11144. static_cast<int>(response_header.size()),
  11145. #else
  11146. response_header.c_str(), response_header.size(),
  11147. #endif
  11148. 0);
  11149. std::string chunk(64 * 1024, 'A');
  11150. size_t total_sent = 0;
  11151. while (total_sent < DATA_SIZE) {
  11152. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11153. auto sent = ::send(cli,
  11154. #ifdef _WIN32
  11155. static_cast<const char *>(chunk.c_str()),
  11156. static_cast<int>(to_send),
  11157. #else
  11158. chunk.c_str(), to_send,
  11159. #endif
  11160. 0);
  11161. if (sent <= 0) break;
  11162. total_sent += static_cast<size_t>(sent);
  11163. }
  11164. detail::close_socket(cli);
  11165. }
  11166. detail::close_socket(srv);
  11167. });
  11168. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11169. size_t total_received = 0;
  11170. {
  11171. Client cli("127.0.0.1", PORT + 2);
  11172. cli.set_read_timeout(10, 0);
  11173. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  11174. auto res =
  11175. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11176. total_received += data_length;
  11177. return true;
  11178. });
  11179. // Should fail because 200MB exceeds the explicit 150MB limit
  11180. EXPECT_FALSE(res);
  11181. }
  11182. server_thread.join();
  11183. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  11184. << "Client with content_receiver should respect the explicit "
  11185. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  11186. << total_received << " bytes.";
  11187. }
  11188. // Verify that an explicit set_payload_max_length larger than the response
  11189. // allows the content_receiver to read all data successfully.
  11190. TEST(ClientVulnerabilityTest,
  11191. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  11192. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11193. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  11194. #ifndef _WIN32
  11195. signal(SIGPIPE, SIG_IGN);
  11196. #endif
  11197. auto server_thread = std::thread([] {
  11198. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11199. default_socket_options(srv);
  11200. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11201. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11202. sockaddr_in addr{};
  11203. addr.sin_family = AF_INET;
  11204. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11205. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11206. int opt = 1;
  11207. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11208. #ifdef _WIN32
  11209. reinterpret_cast<const char *>(&opt),
  11210. #else
  11211. &opt,
  11212. #endif
  11213. sizeof(opt));
  11214. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11215. ::listen(srv, 1);
  11216. sockaddr_in cli_addr{};
  11217. socklen_t cli_len = sizeof(cli_addr);
  11218. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11219. if (cli != INVALID_SOCKET) {
  11220. char buf[4096];
  11221. ::recv(cli, buf, sizeof(buf), 0);
  11222. auto content_length = std::to_string(DATA_SIZE);
  11223. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11224. "Content-Length: " +
  11225. content_length +
  11226. "\r\n"
  11227. "Connection: close\r\n"
  11228. "\r\n";
  11229. ::send(cli,
  11230. #ifdef _WIN32
  11231. static_cast<const char *>(response_header.c_str()),
  11232. static_cast<int>(response_header.size()),
  11233. #else
  11234. response_header.c_str(), response_header.size(),
  11235. #endif
  11236. 0);
  11237. std::string chunk(64 * 1024, 'A');
  11238. size_t total_sent = 0;
  11239. while (total_sent < DATA_SIZE) {
  11240. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11241. auto sent = ::send(cli,
  11242. #ifdef _WIN32
  11243. static_cast<const char *>(chunk.c_str()),
  11244. static_cast<int>(to_send),
  11245. #else
  11246. chunk.c_str(), to_send,
  11247. #endif
  11248. 0);
  11249. if (sent <= 0) break;
  11250. total_sent += static_cast<size_t>(sent);
  11251. }
  11252. #ifdef _WIN32
  11253. ::shutdown(cli, SD_SEND);
  11254. #else
  11255. ::shutdown(cli, SHUT_WR);
  11256. #endif
  11257. char drain[1024];
  11258. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  11259. detail::close_socket(cli);
  11260. }
  11261. detail::close_socket(srv);
  11262. });
  11263. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11264. size_t total_received = 0;
  11265. {
  11266. Client cli("127.0.0.1", PORT + 2);
  11267. cli.set_read_timeout(10, 0);
  11268. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  11269. auto res =
  11270. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11271. total_received += data_length;
  11272. return true;
  11273. });
  11274. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11275. EXPECT_EQ(StatusCode::OK_200, res->status);
  11276. }
  11277. server_thread.join();
  11278. EXPECT_EQ(total_received, DATA_SIZE)
  11279. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  11280. << " bytes (larger than " << DATA_SIZE
  11281. << " bytes response), content_receiver should read all data, but only "
  11282. "read "
  11283. << total_received << " bytes.";
  11284. }
  11285. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  11286. // Regression test for "zip bomb" attack on the client side: a malicious server
  11287. // sends a small gzip-compressed response that decompresses to a huge payload.
  11288. // The client must enforce payload_max_length on the decompressed size.
  11289. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  11290. constexpr size_t DECOMPRESSED_SIZE =
  11291. 10 * 1024 * 1024; // 10MB after decompression
  11292. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  11293. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  11294. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  11295. std::string compressed;
  11296. {
  11297. httplib::detail::gzip_compressor compressor;
  11298. bool ok =
  11299. compressor.compress(uncompressed.data(), uncompressed.size(),
  11300. /*last=*/true, [&](const char *buf, size_t len) {
  11301. compressed.append(buf, len);
  11302. return true;
  11303. });
  11304. ASSERT_TRUE(ok);
  11305. }
  11306. // Sanity: compressed data should be much smaller than the decompressed size
  11307. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  11308. #ifndef _WIN32
  11309. signal(SIGPIPE, SIG_IGN);
  11310. #endif
  11311. // Set up the listening socket in the main thread so the server is guaranteed
  11312. // to be ready before the client connects (eliminates race condition).
  11313. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11314. default_socket_options(srv);
  11315. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11316. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11317. sockaddr_in addr{};
  11318. addr.sin_family = AF_INET;
  11319. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  11320. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11321. int opt = 1;
  11322. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11323. #ifdef _WIN32
  11324. reinterpret_cast<const char *>(&opt),
  11325. #else
  11326. &opt,
  11327. #endif
  11328. sizeof(opt));
  11329. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  11330. ASSERT_EQ(0, ::listen(srv, 1));
  11331. auto server_thread = std::thread([&compressed, srv] {
  11332. sockaddr_in cli_addr{};
  11333. socklen_t cli_len = sizeof(cli_addr);
  11334. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11335. if (cli != INVALID_SOCKET) {
  11336. // Read the full HTTP request (until \r\n\r\n)
  11337. char buf[4096];
  11338. size_t total = 0;
  11339. while (total < sizeof(buf)) {
  11340. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  11341. if (n <= 0) break;
  11342. total += static_cast<size_t>(n);
  11343. // Check for end of headers
  11344. if (total >= 4) {
  11345. std::string req(buf, total);
  11346. if (req.find("\r\n\r\n") != std::string::npos) break;
  11347. }
  11348. }
  11349. // Malicious response: gzip-compressed body, no Content-Length
  11350. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11351. "Content-Encoding: gzip\r\n"
  11352. "Connection: close\r\n"
  11353. "\r\n";
  11354. ::send(cli,
  11355. #ifdef _WIN32
  11356. static_cast<const char *>(response_header.c_str()),
  11357. static_cast<int>(response_header.size()),
  11358. #else
  11359. response_header.c_str(), response_header.size(),
  11360. #endif
  11361. 0);
  11362. // Send the compressed payload (small on the wire, huge when decompressed)
  11363. size_t total_sent = 0;
  11364. while (total_sent < compressed.size()) {
  11365. auto to_send = std::min(compressed.size() - total_sent,
  11366. static_cast<size_t>(64 * 1024));
  11367. auto sent =
  11368. ::send(cli,
  11369. #ifdef _WIN32
  11370. static_cast<const char *>(compressed.c_str() + total_sent),
  11371. static_cast<int>(to_send),
  11372. #else
  11373. compressed.c_str() + total_sent, to_send,
  11374. #endif
  11375. 0);
  11376. if (sent <= 0) break;
  11377. total_sent += static_cast<size_t>(sent);
  11378. }
  11379. detail::close_socket(cli);
  11380. }
  11381. });
  11382. auto se = detail::scope_exit([&] {
  11383. detail::close_socket(srv);
  11384. server_thread.join();
  11385. });
  11386. size_t total_decompressed = 0;
  11387. {
  11388. Client cli("127.0.0.1", PORT + 3);
  11389. cli.set_read_timeout(5, 0);
  11390. cli.set_decompress(true);
  11391. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  11392. auto stream = cli.open_stream("GET", "/zipbomb");
  11393. ASSERT_TRUE(stream.is_valid());
  11394. char buffer[64 * 1024];
  11395. ssize_t n;
  11396. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11397. total_decompressed += static_cast<size_t>(n);
  11398. }
  11399. }
  11400. // The decompressed size must be capped by payload_max_length. Without
  11401. // protection, the client would decompress the full 10MB from a tiny
  11402. // compressed payload, enabling a zip bomb DoS attack.
  11403. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  11404. << "Client decompressed " << total_decompressed
  11405. << " bytes from a gzip response. The decompressed size should be "
  11406. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  11407. }
  11408. #endif
  11409. TEST(HostAndPortPropertiesTest, NoSSL) {
  11410. httplib::Client cli("www.google.com", 1234);
  11411. ASSERT_EQ("www.google.com", cli.host());
  11412. ASSERT_EQ(1234, cli.port());
  11413. }
  11414. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  11415. httplib::Client cli("www.google.com:1234");
  11416. ASSERT_EQ("www.google.com", cli.host());
  11417. ASSERT_EQ(1234, cli.port());
  11418. }
  11419. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  11420. // Port number that overflows int — should not crash, client becomes invalid
  11421. httplib::Client cli("http://www.google.com:99999999999999999999");
  11422. ASSERT_FALSE(cli.is_valid());
  11423. }
  11424. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  11425. // Port 99999 exceeds valid range (1-65535) — should not crash
  11426. httplib::Client cli("http://www.google.com:99999");
  11427. ASSERT_FALSE(cli.is_valid());
  11428. }
  11429. #ifdef CPPHTTPLIB_SSL_ENABLED
  11430. TEST(HostAndPortPropertiesTest, SSL) {
  11431. httplib::SSLClient cli("www.google.com");
  11432. ASSERT_EQ("www.google.com", cli.host());
  11433. ASSERT_EQ(443, cli.port());
  11434. }
  11435. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  11436. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  11437. std::string cert;
  11438. read_file(CA_CERT_FILE, cert);
  11439. httplib::SSLClient httplib_client("www.google.com");
  11440. // Load CA store first time
  11441. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  11442. // Load CA store second time (update)
  11443. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  11444. // Verify client is still valid and can make connections
  11445. httplib_client.enable_server_certificate_verification(true);
  11446. auto res = httplib_client.Get("/");
  11447. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11448. // Google may return 200 or 301 depending on various factors
  11449. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  11450. res->status == StatusCode::MovedPermanently_301);
  11451. }
  11452. TEST(SSLClientTest, ServerNameIndication_Online) {
  11453. auto host = "httpbingo.org";
  11454. auto path = std::string{"/get"};
  11455. SSLClient cli(host, 443);
  11456. auto res = cli.Get(path);
  11457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11458. ASSERT_EQ(StatusCode::OK_200, res->status);
  11459. }
  11460. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  11461. // Use a site that will cause SSL verification failure due to self-signed cert
  11462. SSLClient cli("self-signed.badssl.com", 443);
  11463. cli.enable_server_certificate_verification(true);
  11464. auto res = cli.Get("/");
  11465. ASSERT_TRUE(!res);
  11466. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11467. // Verify backend error is captured for SSLServerVerification
  11468. // This occurs when certificate verification fails
  11469. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  11470. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  11471. EXPECT_NE(0UL, res.ssl_backend_error());
  11472. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11473. // For OpenSSL, ssl_error is 0 for verification errors
  11474. EXPECT_EQ(0, res.ssl_error());
  11475. #if !defined(_WIN32) || \
  11476. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  11477. // On non-Windows or when Windows Schannel is disabled, the error comes
  11478. // from OpenSSL's verification
  11479. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  11480. res.ssl_backend_error());
  11481. #endif
  11482. #endif
  11483. }
  11484. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  11485. // Use a site where hostname doesn't match the certificate
  11486. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  11487. SSLClient cli("wrong.host.badssl.com", 443);
  11488. cli.enable_server_certificate_verification(true);
  11489. cli.enable_server_hostname_verification(true);
  11490. auto res = cli.Get("/");
  11491. ASSERT_TRUE(!res);
  11492. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  11493. // Verify backend error is captured for hostname verification failure
  11494. EXPECT_NE(0UL, res.ssl_backend_error());
  11495. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11496. // For OpenSSL, ssl_error is 0 for verification errors
  11497. EXPECT_EQ(0, res.ssl_error());
  11498. #if !defined(_WIN32) || \
  11499. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  11500. // On non-Windows or when Windows Schannel is disabled, the error comes
  11501. // from OpenSSL's hostname verification
  11502. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  11503. res.ssl_backend_error());
  11504. #endif
  11505. #endif
  11506. }
  11507. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  11508. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  11509. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  11510. SSLClient cli("www.google.com", 443);
  11511. cli.enable_server_certificate_verification(true);
  11512. auto res = cli.Get("/");
  11513. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  11514. }
  11515. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  11516. SSLClient cli("www.google.com", 443);
  11517. cli.enable_server_certificate_verification(true);
  11518. cli.enable_windows_certificate_verification(false);
  11519. auto res = cli.Get("/");
  11520. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  11521. }
  11522. #endif
  11523. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  11524. Client cli("https://google.com");
  11525. auto res = cli.Get("/");
  11526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11527. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11528. }
  11529. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  11530. SSLClient cli("google.com");
  11531. cli.set_ca_cert_path(CA_CERT_FILE);
  11532. auto res = cli.Get("/");
  11533. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11534. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11535. }
  11536. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  11537. SSLClient cli("google.com");
  11538. cli.enable_server_certificate_verification(true);
  11539. cli.set_ca_cert_path("hello");
  11540. auto res = cli.Get("/");
  11541. ASSERT_TRUE(!res);
  11542. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  11543. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  11544. // should be set
  11545. EXPECT_EQ(0, res.ssl_error());
  11546. // Verify backend error is captured for SSLLoadingCerts
  11547. // This error occurs when loading CA certificates fails
  11548. EXPECT_NE(0UL, res.ssl_backend_error());
  11549. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11550. // OpenSSL specific error codes:
  11551. // > openssl errstr 0x80000002
  11552. // error:80000002:system library::No such file or directory
  11553. // > openssl errstr 0xA000126
  11554. // error:0A000126:SSL routines::unexpected eof while reading
  11555. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  11556. res.ssl_backend_error() == 0xA000126);
  11557. #endif
  11558. }
  11559. TEST(SSLClientTest, ServerCertificateVerification4) {
  11560. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11561. ASSERT_TRUE(svr.is_valid());
  11562. svr.Get("/test", [&](const Request &, Response &res) {
  11563. res.set_content("test", "text/plain");
  11564. svr.stop();
  11565. ASSERT_TRUE(true);
  11566. });
  11567. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11568. auto se = detail::scope_exit([&] {
  11569. t.join();
  11570. ASSERT_FALSE(svr.is_running());
  11571. });
  11572. svr.wait_until_ready();
  11573. SSLClient cli("127.0.0.1", PORT);
  11574. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  11575. cli.enable_server_certificate_verification(true);
  11576. cli.set_connection_timeout(30);
  11577. auto res = cli.Get("/test");
  11578. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11579. ASSERT_EQ(StatusCode::OK_200, res->status);
  11580. }
  11581. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  11582. std::string cert;
  11583. read_file(CA_CERT_FILE, cert);
  11584. SSLClient cli("google.com");
  11585. cli.load_ca_cert_store(cert.data(), cert.size());
  11586. const auto res = cli.Get("/");
  11587. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11588. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11589. }
  11590. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  11591. // clang-format off
  11592. static constexpr char cert[] =
  11593. "GlobalSign Root CA\n"
  11594. "==================\n"
  11595. "-----BEGIN CERTIFICATE-----\n"
  11596. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  11597. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  11598. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  11599. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  11600. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  11601. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  11602. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  11603. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  11604. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  11605. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  11606. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  11607. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  11608. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  11609. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  11610. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  11611. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  11612. "-----END CERTIFICATE-----\n";
  11613. // clang-format on
  11614. SSLClient cli("google.com");
  11615. cli.load_ca_cert_store(cert, sizeof(cert));
  11616. const auto res = cli.Get("/");
  11617. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11618. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11619. }
  11620. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  11621. SSLClient cli("www.youtube.com");
  11622. cli.set_ca_cert_path(CA_CERT_FILE);
  11623. cli.enable_server_certificate_verification(true);
  11624. cli.set_follow_location(true);
  11625. auto res = cli.Get("/");
  11626. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11627. ASSERT_EQ(StatusCode::OK_200, res->status);
  11628. }
  11629. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  11630. SSLClient cli("wWw.YouTube.Com");
  11631. cli.set_ca_cert_path(CA_CERT_FILE);
  11632. cli.enable_server_certificate_verification(true);
  11633. cli.enable_server_hostname_verification(true);
  11634. cli.set_follow_location(true);
  11635. auto res = cli.Get("/");
  11636. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11637. ASSERT_EQ(StatusCode::OK_200, res->status);
  11638. }
  11639. TEST(SSLClientTest, HostNameMatchCase_Online) {
  11640. SSLClient cli("gOoGlE.COm");
  11641. cli.enable_server_certificate_verification(true);
  11642. cli.enable_server_hostname_verification(true);
  11643. cli.set_follow_location(true);
  11644. auto res = cli.Get("/");
  11645. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11646. ASSERT_EQ(StatusCode::OK_200, res->status);
  11647. }
  11648. TEST(SSLClientTest, Issue2004_Online) {
  11649. Client client("https://google.com");
  11650. client.set_follow_location(true);
  11651. auto res = client.Get("/");
  11652. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11653. ASSERT_EQ(StatusCode::OK_200, res->status);
  11654. auto body = res->body;
  11655. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  11656. }
  11657. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  11658. // Create SSLClient with invalid cert/key to make is_valid() return false
  11659. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  11660. "nonexistent_key.pem");
  11661. // is_valid() should be false due to cert loading failure
  11662. ASSERT_FALSE(cli.is_valid());
  11663. auto res = cli.Get("/");
  11664. ASSERT_FALSE(res);
  11665. EXPECT_EQ(Error::SSLConnection, res.error());
  11666. }
  11667. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  11668. // Test for Issue #2251: SSL error not properly reported when client cert
  11669. // and key paths are swapped or mismatched
  11670. // This simulates the scenario where user accidentally swaps the cert and key
  11671. // files
  11672. // Using client cert file as private key and vice versa (completely wrong)
  11673. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  11674. // Should fail validation due to cert/key mismatch
  11675. ASSERT_FALSE(cli.is_valid());
  11676. // Attempt to make a request should fail with proper error
  11677. auto res = cli.Get("/");
  11678. ASSERT_FALSE(res);
  11679. EXPECT_EQ(Error::SSLConnection, res.error());
  11680. // SSL error should be recorded in the Result object (this is the key fix for
  11681. // Issue #2251)
  11682. auto backend_error = res.ssl_backend_error();
  11683. EXPECT_NE(0u, backend_error);
  11684. }
  11685. // Tests cert/key mismatch detection at the TLS context level
  11686. TEST(TlsApiTest, ClientCertKeyMismatch) {
  11687. // Test that using mismatched cert/key causes connection failure.
  11688. // We verify this at the SSLClient level rather than through internal
  11689. // TLS API functions.
  11690. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  11691. cli.enable_server_certificate_verification(false);
  11692. cli.set_connection_timeout(2);
  11693. // The mismatch should cause a connection or handshake error
  11694. auto res = cli.Get("/test");
  11695. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  11696. // Either way, the request should fail
  11697. EXPECT_FALSE(res);
  11698. }
  11699. #endif
  11700. #if 0
  11701. TEST(SSLClientTest, SetInterfaceWithINET6) {
  11702. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  11703. ASSERT_TRUE(cli != nullptr);
  11704. cli->set_address_family(AF_INET6);
  11705. cli->set_interface("en0");
  11706. auto res = cli->Get("/get");
  11707. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11708. ASSERT_EQ(StatusCode::OK_200, res->status);
  11709. }
  11710. #endif
  11711. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  11712. #ifdef CPPHTTPLIB_SSL_ENABLED
  11713. void ClientCertPresent(
  11714. const std::string &client_cert_file,
  11715. const std::string &client_private_key_file,
  11716. const std::string &client_encrypted_private_key_pass = std::string()) {
  11717. using namespace httplib::tls;
  11718. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  11719. CLIENT_CA_CERT_DIR);
  11720. ASSERT_TRUE(svr.is_valid());
  11721. svr.Get("/test", [&](const Request &req, Response &res) {
  11722. res.set_content("test", "text/plain");
  11723. auto cert = req.peer_cert();
  11724. ASSERT_TRUE(static_cast<bool>(cert));
  11725. std::string common_name = cert.subject_cn();
  11726. EXPECT_EQ("Common Name", common_name);
  11727. });
  11728. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11729. auto se = detail::scope_exit([&] {
  11730. svr.stop();
  11731. t.join();
  11732. ASSERT_FALSE(svr.is_running());
  11733. });
  11734. svr.wait_until_ready();
  11735. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  11736. client_encrypted_private_key_pass);
  11737. cli.enable_server_certificate_verification(false);
  11738. cli.set_connection_timeout(30);
  11739. auto res = cli.Get("/test");
  11740. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11741. ASSERT_EQ(StatusCode::OK_200, res->status);
  11742. }
  11743. TEST(SSLClientServerTest, ClientCertPresent) {
  11744. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11745. }
  11746. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  11747. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  11748. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  11749. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  11750. }
  11751. // PEM memory-based constructor tests (works with all TLS backends)
  11752. void PemMemoryClientCertPresent(
  11753. const std::string &client_cert_file,
  11754. const std::string &client_private_key_file,
  11755. const std::string &client_encrypted_private_key_pass = std::string()) {
  11756. // Read PEM files into memory
  11757. std::string server_cert_pem, server_key_pem;
  11758. std::string client_ca_pem;
  11759. std::string client_cert_pem, client_key_pem;
  11760. read_file(SERVER_CERT_FILE, server_cert_pem);
  11761. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  11762. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  11763. read_file(client_cert_file, client_cert_pem);
  11764. read_file(client_private_key_file, client_key_pem);
  11765. // Create server with PEM memory
  11766. SSLServer::PemMemory server_pem = {
  11767. server_cert_pem.c_str(),
  11768. server_cert_pem.size(),
  11769. server_key_pem.c_str(),
  11770. server_key_pem.size(),
  11771. client_ca_pem.c_str(),
  11772. client_ca_pem.size(),
  11773. nullptr // no password for server key
  11774. };
  11775. SSLServer svr(server_pem);
  11776. ASSERT_TRUE(svr.is_valid());
  11777. svr.Get("/test", [&](const Request &, Response &res) {
  11778. res.set_content("test", "text/plain");
  11779. });
  11780. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11781. auto se = detail::scope_exit([&] {
  11782. svr.stop();
  11783. t.join();
  11784. ASSERT_FALSE(svr.is_running());
  11785. });
  11786. svr.wait_until_ready();
  11787. // Create client with PEM memory
  11788. const char *password = client_encrypted_private_key_pass.empty()
  11789. ? nullptr
  11790. : client_encrypted_private_key_pass.c_str();
  11791. SSLClient::PemMemory client_pem = {
  11792. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  11793. client_key_pem.size(), password};
  11794. SSLClient cli(HOST, PORT, client_pem);
  11795. cli.enable_server_certificate_verification(false);
  11796. cli.set_connection_timeout(30);
  11797. auto res = cli.Get("/test");
  11798. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11799. ASSERT_EQ(StatusCode::OK_200, res->status);
  11800. }
  11801. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  11802. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11803. }
  11804. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  11805. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  11806. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  11807. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  11808. }
  11809. TEST(SSLClientServerTest, ClientCertMissing) {
  11810. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  11811. CLIENT_CA_CERT_DIR);
  11812. ASSERT_TRUE(svr.is_valid());
  11813. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  11814. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11815. auto se = detail::scope_exit([&] {
  11816. svr.stop();
  11817. t.join();
  11818. ASSERT_FALSE(svr.is_running());
  11819. });
  11820. svr.wait_until_ready();
  11821. SSLClient cli(HOST, PORT);
  11822. cli.set_connection_timeout(30);
  11823. auto res = cli.Get("/test");
  11824. ASSERT_TRUE(!res);
  11825. // When client cert is missing and server requires it, connection fails
  11826. // Error type depends on backend implementation
  11827. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  11828. res.error() == Error::SSLConnection);
  11829. // Verify backend error is captured
  11830. // Note: This test may have different error codes depending on the exact
  11831. // verification failure
  11832. EXPECT_NE(0UL, res.ssl_backend_error());
  11833. }
  11834. TEST(SSLClientServerTest, TrustDirOptional) {
  11835. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  11836. ASSERT_TRUE(svr.is_valid());
  11837. svr.Get("/test", [&](const Request &, Response &res) {
  11838. res.set_content("test", "text/plain");
  11839. });
  11840. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11841. auto se = detail::scope_exit([&] {
  11842. svr.stop();
  11843. t.join();
  11844. ASSERT_FALSE(svr.is_running());
  11845. });
  11846. svr.wait_until_ready();
  11847. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11848. cli.enable_server_certificate_verification(false);
  11849. cli.set_connection_timeout(30);
  11850. auto res = cli.Get("/test");
  11851. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11852. ASSERT_EQ(StatusCode::OK_200, res->status);
  11853. }
  11854. TEST(SSLClientServerTest, SSLConnectTimeout) {
  11855. class NoListenSSLServer : public SSLServer {
  11856. public:
  11857. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  11858. const char *client_ca_cert_file_path,
  11859. const char *client_ca_cert_dir_path = nullptr)
  11860. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  11861. client_ca_cert_dir_path),
  11862. stop_(false) {}
  11863. std::atomic_bool stop_;
  11864. private:
  11865. bool process_and_close_socket(socket_t /*sock*/) override {
  11866. // Don't create SSL context
  11867. while (!stop_.load()) {
  11868. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  11869. }
  11870. return true;
  11871. }
  11872. };
  11873. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  11874. CLIENT_CA_CERT_FILE);
  11875. ASSERT_TRUE(svr.is_valid());
  11876. svr.Get("/test", [&](const Request &, Response &res) {
  11877. res.set_content("test", "text/plain");
  11878. });
  11879. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11880. auto se = detail::scope_exit([&] {
  11881. svr.stop_ = true;
  11882. svr.stop();
  11883. t.join();
  11884. ASSERT_FALSE(svr.is_running());
  11885. });
  11886. svr.wait_until_ready();
  11887. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11888. cli.enable_server_certificate_verification(false);
  11889. cli.set_connection_timeout(1);
  11890. auto res = cli.Get("/test");
  11891. ASSERT_TRUE(!res);
  11892. EXPECT_EQ(Error::SSLConnection, res.error());
  11893. // Timeout results in WantRead error code (maps to backend-specific value)
  11894. EXPECT_NE(0, res.ssl_error());
  11895. }
  11896. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  11897. // Test SSLServer with client certificate verification using the standard
  11898. // constructor (ContextSetupCallback is tested by backend-specific tests)
  11899. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  11900. CLIENT_CA_CERT_DIR);
  11901. ASSERT_TRUE(svr.is_valid());
  11902. svr.Get("/test", [&](const Request &req, Response &res) {
  11903. res.set_content("test", "text/plain");
  11904. auto cert = req.peer_cert();
  11905. ASSERT_TRUE(static_cast<bool>(cert));
  11906. auto common_name = cert.subject_cn();
  11907. EXPECT_EQ("Common Name", common_name);
  11908. });
  11909. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11910. auto se = detail::scope_exit([&] {
  11911. svr.stop();
  11912. t.join();
  11913. ASSERT_FALSE(svr.is_running());
  11914. });
  11915. svr.wait_until_ready();
  11916. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11917. cli.enable_server_certificate_verification(false);
  11918. cli.set_connection_timeout(30);
  11919. auto res = cli.Get("/test");
  11920. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11921. ASSERT_EQ(StatusCode::OK_200, res->status);
  11922. }
  11923. // Test verify_hostname for both OpenSSL and MbedTLS backends
  11924. // Verifies that wildcard matching and exact matching work consistently
  11925. TEST(SSLClientServerTest, TlsVerifyHostname) {
  11926. using namespace httplib::tls;
  11927. // We need a running server to test against
  11928. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11929. ASSERT_TRUE(svr.is_valid());
  11930. svr.Get("/test", [](const Request &, Response &res) {
  11931. res.set_content("ok", "text/plain");
  11932. });
  11933. thread t([&]() { svr.listen(HOST, PORT); });
  11934. auto se = detail::scope_exit([&] {
  11935. svr.stop();
  11936. t.join();
  11937. });
  11938. svr.wait_until_ready();
  11939. bool verify_callback_called = false;
  11940. bool verify_result_wrong = false;
  11941. SSLClient cli(HOST, PORT);
  11942. cli.enable_server_certificate_verification(true);
  11943. cli.set_ca_cert_path(CA_CERT_FILE);
  11944. cli.set_connection_timeout(5);
  11945. // Note: Test certificate has CN="Common Name", not "localhost"
  11946. bool verify_result_cn = false;
  11947. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  11948. verify_callback_called = true;
  11949. if (!ctx.cert) return false;
  11950. // Test 1: "Common Name" should match (our test server cert CN)
  11951. verify_result_cn = ctx.check_hostname("Common Name");
  11952. // Test 2: wrong hostname should not match
  11953. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  11954. return true; // Accept for the purpose of this test
  11955. });
  11956. auto res = cli.Get("/test");
  11957. // The request may succeed or fail depending on cert configuration
  11958. // but the callback should have been called
  11959. ASSERT_TRUE(verify_callback_called)
  11960. << "Verify callback should have been called";
  11961. // CN="Common Name" should match our test certificate
  11962. //
  11963. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  11964. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  11965. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  11966. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  11967. // <openssl/base.h>, which is included transitively when
  11968. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  11969. #if defined(OPENSSL_IS_BORINGSSL)
  11970. EXPECT_FALSE(verify_result_cn)
  11971. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  11972. #else
  11973. EXPECT_TRUE(verify_result_cn)
  11974. << "verify_hostname should match 'Common Name' (certificate CN)";
  11975. #endif
  11976. // Wrong hostname should not match
  11977. EXPECT_FALSE(verify_result_wrong)
  11978. << "verify_hostname should not match 'wronghost.example.com'";
  11979. }
  11980. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  11981. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  11982. // X509_check_ip behavior and must hold for every backend.
  11983. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  11984. using namespace httplib::tls;
  11985. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  11986. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  11987. ASSERT_TRUE(svr.is_valid());
  11988. svr.Get("/test", [](const Request &, Response &res) {
  11989. res.set_content("ok", "text/plain");
  11990. });
  11991. thread t([&]() { svr.listen(HOST, PORT); });
  11992. auto se = detail::scope_exit([&] {
  11993. svr.stop();
  11994. t.join();
  11995. });
  11996. svr.wait_until_ready();
  11997. bool verify_callback_called = false;
  11998. bool ip_matched_via_cn = true;
  11999. SSLClient cli(HOST, PORT);
  12000. cli.enable_server_certificate_verification(true);
  12001. cli.set_ca_cert_path(CA_CERT_FILE);
  12002. cli.set_connection_timeout(5);
  12003. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12004. verify_callback_called = true;
  12005. if (!ctx.cert) return false;
  12006. // The IP appears only in the CN, so it must NOT be accepted.
  12007. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  12008. return true; // Accept for the purpose of this test
  12009. });
  12010. cli.Get("/test");
  12011. ASSERT_TRUE(verify_callback_called)
  12012. << "Verify callback should have been called";
  12013. EXPECT_FALSE(ip_matched_via_cn)
  12014. << "An IP host must not be authenticated via the certificate CN";
  12015. }
  12016. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  12017. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  12018. using namespace httplib::tls;
  12019. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  12020. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  12021. ASSERT_TRUE(svr.is_valid());
  12022. svr.Get("/test", [](const Request &, Response &res) {
  12023. res.set_content("ok", "text/plain");
  12024. });
  12025. thread t([&]() { svr.listen(HOST, PORT); });
  12026. auto se = detail::scope_exit([&] {
  12027. svr.stop();
  12028. t.join();
  12029. });
  12030. svr.wait_until_ready();
  12031. bool verify_callback_called = false;
  12032. bool san_matched = false;
  12033. bool wrong_ipv6_matched = true;
  12034. bool cn_ipv6_matched = true;
  12035. SSLClient cli(HOST, PORT);
  12036. cli.enable_server_certificate_verification(true);
  12037. cli.set_ca_cert_path(CA_CERT_FILE);
  12038. cli.set_connection_timeout(5);
  12039. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12040. verify_callback_called = true;
  12041. if (!ctx.cert) return false;
  12042. // Matches the IPv6 iPAddress SAN.
  12043. san_matched = ctx.check_hostname("2001:db8::1");
  12044. // A different IPv6 address must not match.
  12045. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  12046. // "::1" lives only in the CN, so it must not be accepted.
  12047. cn_ipv6_matched = ctx.check_hostname("::1");
  12048. return true; // Accept for the purpose of this test
  12049. });
  12050. cli.Get("/test");
  12051. ASSERT_TRUE(verify_callback_called)
  12052. << "Verify callback should have been called";
  12053. EXPECT_TRUE(san_matched)
  12054. << "verify_hostname should match an IPv6 iPAddress SAN";
  12055. EXPECT_FALSE(wrong_ipv6_matched)
  12056. << "verify_hostname should not match a non-matching IPv6 address";
  12057. EXPECT_FALSE(cn_ipv6_matched)
  12058. << "An IPv6 host must not be authenticated via the certificate CN";
  12059. }
  12060. #endif
  12061. // mbedTLS-specific callback constructor test
  12062. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  12063. #ifdef CPPHTTPLIB_SSL_ENABLED
  12064. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  12065. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12066. ASSERT_TRUE(svr.is_valid());
  12067. // Set up a handler to verify client certificate is present
  12068. bool client_cert_verified = false;
  12069. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  12070. // Verify that client certificate was provided
  12071. client_cert_verified = true;
  12072. res.set_content("success", "text/plain");
  12073. });
  12074. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12075. auto se = detail::scope_exit([&] {
  12076. svr.stop();
  12077. t.join();
  12078. ASSERT_FALSE(svr.is_running());
  12079. });
  12080. svr.wait_until_ready();
  12081. // Client with certificate
  12082. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12083. cli.enable_server_certificate_verification(false);
  12084. cli.set_connection_timeout(30);
  12085. auto res = cli.Get("/test");
  12086. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12087. ASSERT_EQ(StatusCode::OK_200, res->status);
  12088. ASSERT_TRUE(client_cert_verified);
  12089. EXPECT_EQ("success", res->body);
  12090. }
  12091. #endif
  12092. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  12093. // backends
  12094. #ifdef CPPHTTPLIB_SSL_ENABLED
  12095. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  12096. using namespace httplib::tls;
  12097. // Test that when client CA cert file is provided,
  12098. // the server properly requests and validates client certificates
  12099. // Create a server with client authentication
  12100. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12101. ASSERT_TRUE(svr.is_valid());
  12102. bool handler_called = false;
  12103. svr.Get("/test", [&](const Request &req, Response &res) {
  12104. handler_called = true;
  12105. // Verify that a client certificate was provided
  12106. auto cert = req.peer_cert();
  12107. ASSERT_TRUE(static_cast<bool>(cert));
  12108. // Get the issuer name
  12109. std::string issuer_str = cert.issuer_name();
  12110. ASSERT_FALSE(issuer_str.empty());
  12111. // The client certificate should be issued by our test CA
  12112. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  12113. res.set_content("authenticated", "text/plain");
  12114. });
  12115. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12116. auto se = detail::scope_exit([&] {
  12117. svr.stop();
  12118. t.join();
  12119. ASSERT_FALSE(svr.is_running());
  12120. });
  12121. svr.wait_until_ready();
  12122. // Connect with a client certificate issued by the CA
  12123. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12124. cli.enable_server_certificate_verification(false);
  12125. cli.set_connection_timeout(30);
  12126. auto res = cli.Get("/test");
  12127. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12128. ASSERT_EQ(StatusCode::OK_200, res->status);
  12129. ASSERT_TRUE(handler_called);
  12130. EXPECT_EQ("authenticated", res->body);
  12131. }
  12132. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  12133. using namespace httplib::tls;
  12134. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12135. ASSERT_TRUE(svr.is_valid());
  12136. svr.Get("/test", [](const Request &, Response &res) {
  12137. res.set_content("ok", "text/plain");
  12138. });
  12139. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12140. auto se = detail::scope_exit([&] {
  12141. svr.stop();
  12142. t.join();
  12143. });
  12144. svr.wait_until_ready();
  12145. SSLClient cli(HOST, PORT);
  12146. cli.enable_server_certificate_verification(false);
  12147. cli.set_connection_timeout(30);
  12148. bool cert_checked = false;
  12149. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12150. if (ctx.cert) {
  12151. auto sans = ctx.sans();
  12152. // Test certificate may or may not have SANs - just verify the API
  12153. // works If SANs exist, verify the types are valid
  12154. for (const auto &san : sans) {
  12155. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  12156. san.type == SanType::EMAIL || san.type == SanType::URI ||
  12157. san.type == SanType::OTHER);
  12158. EXPECT_FALSE(san.value.empty());
  12159. }
  12160. cert_checked = true;
  12161. }
  12162. return true;
  12163. });
  12164. auto res = cli.Get("/test");
  12165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12166. EXPECT_TRUE(cert_checked);
  12167. }
  12168. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  12169. using namespace httplib::tls;
  12170. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12171. ASSERT_TRUE(svr.is_valid());
  12172. svr.Get("/test", [](const Request &, Response &res) {
  12173. res.set_content("ok", "text/plain");
  12174. });
  12175. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12176. auto se = detail::scope_exit([&] {
  12177. svr.stop();
  12178. t.join();
  12179. });
  12180. svr.wait_until_ready();
  12181. SSLClient cli(HOST, PORT);
  12182. cli.enable_server_certificate_verification(false);
  12183. cli.set_connection_timeout(30);
  12184. bool validity_checked = false;
  12185. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12186. if (ctx.cert) {
  12187. time_t not_before = 0, not_after = 0;
  12188. bool result = ctx.validity(not_before, not_after);
  12189. EXPECT_TRUE(result);
  12190. // Verify that not_before < now < not_after for a valid cert
  12191. time_t now = time(nullptr);
  12192. EXPECT_LT(not_before, now);
  12193. EXPECT_GT(not_after, now);
  12194. validity_checked = true;
  12195. }
  12196. return true;
  12197. });
  12198. auto res = cli.Get("/test");
  12199. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12200. EXPECT_TRUE(validity_checked);
  12201. }
  12202. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  12203. using namespace httplib::tls;
  12204. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12205. ASSERT_TRUE(svr.is_valid());
  12206. svr.Get("/test", [](const Request &, Response &res) {
  12207. res.set_content("ok", "text/plain");
  12208. });
  12209. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12210. auto se = detail::scope_exit([&] {
  12211. svr.stop();
  12212. t.join();
  12213. });
  12214. svr.wait_until_ready();
  12215. SSLClient cli(HOST, PORT);
  12216. cli.enable_server_certificate_verification(false);
  12217. cli.set_connection_timeout(30);
  12218. bool serial_checked = false;
  12219. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12220. if (ctx.cert) {
  12221. std::string serial = ctx.serial();
  12222. EXPECT_FALSE(serial.empty());
  12223. // Serial should be a hex string
  12224. for (char c : serial) {
  12225. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  12226. (c >= 'a' && c <= 'f'));
  12227. }
  12228. serial_checked = true;
  12229. }
  12230. return true;
  12231. });
  12232. auto res = cli.Get("/test");
  12233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12234. EXPECT_TRUE(serial_checked);
  12235. }
  12236. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  12237. // Test 1: Valid CA file - no error should be recorded
  12238. {
  12239. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  12240. CLIENT_CA_CERT_FILE);
  12241. ASSERT_TRUE(svr.is_valid());
  12242. // With valid setup, last_ssl_error should be 0
  12243. EXPECT_EQ(0, svr.ssl_last_error());
  12244. }
  12245. // Test 2: Invalid CA file content
  12246. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  12247. {
  12248. // Create a temporary file with completely invalid content
  12249. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  12250. {
  12251. std::ofstream ofs(temp_invalid_ca);
  12252. ofs << "This is not a certificate file at all\n";
  12253. ofs << "Just plain text content\n";
  12254. }
  12255. // Create server with invalid CA file
  12256. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  12257. // Clean up temporary file
  12258. std::remove(temp_invalid_ca);
  12259. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  12260. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  12261. // Note: SSL_CTX_load_verify_locations typically fails first,
  12262. // but our error handling code path is still exercised
  12263. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  12264. }
  12265. }
  12266. TEST(VerifyCallbackTest, VerifyContextFields) {
  12267. using namespace httplib::tls;
  12268. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12269. ASSERT_TRUE(svr.is_valid());
  12270. svr.Get("/test", [](const Request &, Response &res) {
  12271. res.set_content("ok", "text/plain");
  12272. });
  12273. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12274. auto se = detail::scope_exit([&] {
  12275. svr.stop();
  12276. t.join();
  12277. });
  12278. svr.wait_until_ready();
  12279. SSLClient cli(HOST, PORT);
  12280. cli.enable_server_certificate_verification(false);
  12281. cli.set_connection_timeout(30);
  12282. int callback_count = 0;
  12283. bool saw_leaf_cert = false;
  12284. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12285. if (ctx.cert) {
  12286. callback_count++;
  12287. // We should see at least one certificate (the leaf)
  12288. std::string cn = ctx.subject_cn();
  12289. if (!cn.empty()) { saw_leaf_cert = true; }
  12290. // Verify context fields are populated
  12291. EXPECT_NE(ctx.session, nullptr);
  12292. EXPECT_GE(ctx.depth, 0);
  12293. }
  12294. return true;
  12295. });
  12296. auto res = cli.Get("/test");
  12297. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12298. EXPECT_GT(callback_count, 0);
  12299. EXPECT_TRUE(saw_leaf_cert);
  12300. }
  12301. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  12302. using httplib::tls::TlsError;
  12303. // Test that verify_error_to_string returns empty for success
  12304. std::string success_str = TlsError::verify_error_to_string(0);
  12305. EXPECT_TRUE(success_str.empty());
  12306. // Test that verify_error_to_string returns non-empty for error codes
  12307. // Using a common error code (certificate expired)
  12308. std::string error_str =
  12309. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  12310. EXPECT_FALSE(error_str.empty());
  12311. }
  12312. TEST(SessionVerifierTest, CertificateAccepted) {
  12313. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12314. ASSERT_TRUE(svr.is_valid());
  12315. svr.Get("/test", [](const Request &, Response &res) {
  12316. res.set_content("ok", "text/plain");
  12317. });
  12318. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12319. auto se = detail::scope_exit([&] {
  12320. svr.stop();
  12321. t.join();
  12322. });
  12323. svr.wait_until_ready();
  12324. SSLClient cli(HOST, PORT);
  12325. cli.enable_server_certificate_verification(false);
  12326. cli.set_connection_timeout(30);
  12327. bool callback_called = false;
  12328. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12329. EXPECT_NE(session, nullptr);
  12330. callback_called = true;
  12331. return SSLVerifierResponse::CertificateAccepted;
  12332. });
  12333. auto res = cli.Get("/test");
  12334. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12335. EXPECT_EQ(200, res->status);
  12336. EXPECT_TRUE(callback_called);
  12337. }
  12338. TEST(SessionVerifierTest, CertificateRejected) {
  12339. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12340. ASSERT_TRUE(svr.is_valid());
  12341. svr.Get("/test", [](const Request &, Response &res) {
  12342. res.set_content("ok", "text/plain");
  12343. });
  12344. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12345. auto se = detail::scope_exit([&] {
  12346. svr.stop();
  12347. t.join();
  12348. });
  12349. svr.wait_until_ready();
  12350. SSLClient cli(HOST, PORT);
  12351. cli.enable_server_certificate_verification(false);
  12352. cli.set_connection_timeout(30);
  12353. bool callback_called = false;
  12354. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12355. EXPECT_NE(session, nullptr);
  12356. callback_called = true;
  12357. return SSLVerifierResponse::CertificateRejected;
  12358. });
  12359. auto res = cli.Get("/test");
  12360. EXPECT_FALSE(res);
  12361. EXPECT_TRUE(callback_called);
  12362. }
  12363. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  12364. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12365. ASSERT_TRUE(svr.is_valid());
  12366. svr.Get("/test", [](const Request &, Response &res) {
  12367. res.set_content("ok", "text/plain");
  12368. });
  12369. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12370. auto se = detail::scope_exit([&] {
  12371. svr.stop();
  12372. t.join();
  12373. });
  12374. svr.wait_until_ready();
  12375. // NoDecisionMade with verification disabled should succeed (no default check)
  12376. SSLClient cli(HOST, PORT);
  12377. cli.enable_server_certificate_verification(false);
  12378. cli.set_connection_timeout(30);
  12379. bool callback_called = false;
  12380. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12381. EXPECT_NE(session, nullptr);
  12382. callback_called = true;
  12383. return SSLVerifierResponse::NoDecisionMade;
  12384. });
  12385. auto res = cli.Get("/test");
  12386. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12387. EXPECT_EQ(200, res->status);
  12388. EXPECT_TRUE(callback_called);
  12389. }
  12390. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  12391. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12392. ASSERT_TRUE(svr.is_valid());
  12393. svr.Get("/test", [](const Request &, Response &res) {
  12394. res.set_content("ok", "text/plain");
  12395. });
  12396. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12397. auto se = detail::scope_exit([&] {
  12398. svr.stop();
  12399. t.join();
  12400. });
  12401. svr.wait_until_ready();
  12402. // NoDecisionMade with verification enabled should fail (self-signed cert).
  12403. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  12404. // so we only check that the request fails, not whether the callback was
  12405. // called.
  12406. SSLClient cli(HOST, PORT);
  12407. cli.enable_server_certificate_verification(true);
  12408. cli.set_connection_timeout(30);
  12409. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12410. EXPECT_NE(session, nullptr);
  12411. return SSLVerifierResponse::NoDecisionMade;
  12412. });
  12413. auto res = cli.Get("/test");
  12414. EXPECT_FALSE(res);
  12415. }
  12416. TEST(SSLClientServerTest, ClientCAListFromPem) {
  12417. // Test SSL server using PemMemory constructor with client CA certificates
  12418. // Read PEM files
  12419. std::string server_cert_pem, server_key_pem, client_ca_pem;
  12420. read_file(SERVER_CERT_FILE, server_cert_pem);
  12421. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  12422. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  12423. // Create SSLServer with PemMemory constructor including client CA
  12424. SSLServer::PemMemory server_pem = {
  12425. server_cert_pem.c_str(),
  12426. server_cert_pem.size(),
  12427. server_key_pem.c_str(),
  12428. server_key_pem.size(),
  12429. client_ca_pem.c_str(),
  12430. client_ca_pem.size(),
  12431. nullptr // no password for server key
  12432. };
  12433. SSLServer svr(server_pem);
  12434. ASSERT_TRUE(svr.is_valid());
  12435. // No SSL error should be recorded for valid setup
  12436. EXPECT_EQ(0, svr.ssl_last_error());
  12437. // Set up server endpoints
  12438. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  12439. res.set_content("ok", "text/plain");
  12440. });
  12441. // Start server in a thread
  12442. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  12443. svr.wait_until_ready();
  12444. // Connect with client certificate (using constructor with paths)
  12445. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12446. cli.enable_server_certificate_verification(false);
  12447. auto res = cli.Get("/test-pem-ca");
  12448. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12449. EXPECT_EQ(200, res->status);
  12450. EXPECT_EQ("ok", res->body);
  12451. svr.stop();
  12452. server_thread.join();
  12453. }
  12454. #endif
  12455. #ifdef _WIN32
  12456. TEST(CleanupTest, WSACleanup) {
  12457. int ret = WSACleanup();
  12458. ASSERT_EQ(0, ret);
  12459. }
  12460. #endif
  12461. #ifndef CPPHTTPLIB_SSL_ENABLED
  12462. TEST(NoSSLSupport, SimpleInterface) {
  12463. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  12464. }
  12465. #endif
  12466. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  12467. TEST(InvalidScheme, SimpleInterface) {
  12468. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  12469. }
  12470. #endif
  12471. TEST(NoScheme, SimpleInterface) {
  12472. Client cli("yahoo.com:80");
  12473. ASSERT_TRUE(cli.is_valid());
  12474. }
  12475. TEST(SendAPI, SimpleInterface_Online) {
  12476. Client cli("http://yahoo.com");
  12477. Request req;
  12478. req.method = "GET";
  12479. req.path = "/";
  12480. auto res = cli.send(req);
  12481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12482. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  12483. }
  12484. TEST(SendAPI, WithParamsInRequest) {
  12485. Server svr;
  12486. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  12487. EXPECT_TRUE(req.has_param("test"));
  12488. EXPECT_EQ("test_value", req.get_param_value("test"));
  12489. });
  12490. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12491. auto se = detail::scope_exit([&] {
  12492. svr.stop();
  12493. t.join();
  12494. ASSERT_FALSE(svr.is_running());
  12495. });
  12496. svr.wait_until_ready();
  12497. Client cli(HOST, PORT);
  12498. {
  12499. Request req;
  12500. req.method = "GET";
  12501. req.path = "/";
  12502. req.params.emplace("test", "test_value");
  12503. auto res = cli.send(req);
  12504. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12505. }
  12506. {
  12507. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  12508. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12509. }
  12510. }
  12511. TEST(ClientImplMethods, GetSocketTest) {
  12512. httplib::Server svr;
  12513. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  12514. res.status = StatusCode::OK_200;
  12515. });
  12516. auto port = svr.bind_to_any_port("127.0.0.1");
  12517. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  12518. auto se = detail::scope_exit([&] {
  12519. svr.stop();
  12520. thread.join();
  12521. ASSERT_FALSE(svr.is_running());
  12522. });
  12523. svr.wait_until_ready();
  12524. {
  12525. httplib::Client cli("127.0.0.1", port);
  12526. cli.set_keep_alive(true);
  12527. // Use the behavior of cpp-httplib of opening the connection
  12528. // only when the first request happens. If that changes,
  12529. // this test would be obsolete.
  12530. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  12531. // This also implicitly tests the server. But other tests would fail much
  12532. // earlier than this one to be considered.
  12533. auto res = cli.Get("/");
  12534. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12535. EXPECT_EQ(StatusCode::OK_200, res->status);
  12536. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  12537. }
  12538. }
  12539. #ifdef CPPHTTPLIB_SSL_ENABLED
  12540. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  12541. Client cli("http://yahoo.com");
  12542. auto res = cli.Get("/");
  12543. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12544. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  12545. cli.set_follow_location(true);
  12546. res = cli.Get("/");
  12547. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12548. EXPECT_EQ(StatusCode::OK_200, res->status);
  12549. EXPECT_EQ("https://www.yahoo.com/", res->location);
  12550. }
  12551. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  12552. Client cli("https://yahoo.com");
  12553. auto res = cli.Get("/");
  12554. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12555. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  12556. cli.set_follow_location(true);
  12557. res = cli.Get("/");
  12558. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12559. EXPECT_EQ(StatusCode::OK_200, res->status);
  12560. EXPECT_EQ("https://www.yahoo.com/", res->location);
  12561. }
  12562. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  12563. Client cli("https://yahoo.com");
  12564. auto res = cli.Get("/");
  12565. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12566. ASSERT_FALSE(!res);
  12567. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12568. ASSERT_FALSE(res == nullptr);
  12569. ASSERT_TRUE(res != nullptr);
  12570. EXPECT_EQ(Error::Success, res.error());
  12571. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  12572. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  12573. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  12574. cli.set_follow_location(true);
  12575. res = cli.Get("/");
  12576. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12577. EXPECT_EQ(Error::Success, res.error());
  12578. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  12579. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  12580. EXPECT_EQ(StatusCode::OK_200, res->status);
  12581. EXPECT_EQ("https://www.yahoo.com/", res->location);
  12582. }
  12583. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  12584. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  12585. Client cli("https://cdnjs.cloudflare.com");
  12586. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  12587. Headers{{"Accept-Encoding", "br"}});
  12588. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12589. EXPECT_EQ(StatusCode::OK_200, res->status);
  12590. EXPECT_EQ(287630U, res->body.size());
  12591. EXPECT_EQ("application/javascript; charset=utf-8",
  12592. res->get_header_value("Content-Type"));
  12593. }
  12594. #endif
  12595. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  12596. #undef REDIR_HOST // Silence compiler warning
  12597. #define REDIR_HOST "https://httpbingo.org"
  12598. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  12599. Client cli(REDIR_HOST);
  12600. cli.set_follow_location(true);
  12601. auto res =
  12602. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  12603. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12604. EXPECT_EQ(StatusCode::OK_200, res->status);
  12605. }
  12606. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  12607. Client cli(REDIR_HOST);
  12608. cli.set_follow_location(true);
  12609. Params params;
  12610. params.emplace("url", "http://example.com");
  12611. params.emplace("status_code", "302");
  12612. auto res = cli.Get(REDIR_PATH, params, Headers{});
  12613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12614. EXPECT_EQ(StatusCode::OK_200, res->status);
  12615. }
  12616. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  12617. Client cli(REDIR_HOST);
  12618. cli.set_follow_location(true);
  12619. Params params;
  12620. params.emplace("url", "http://example.com");
  12621. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  12622. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12623. EXPECT_EQ(StatusCode::OK_200, res->status);
  12624. }
  12625. TEST(HttpToHttpsRedirectTest, CertFile) {
  12626. auto ssl_port = PORT + 1;
  12627. Server svr;
  12628. ASSERT_TRUE(svr.is_valid());
  12629. svr.Get("/index", [&](const Request &, Response &res) {
  12630. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  12631. "/index");
  12632. svr.stop();
  12633. });
  12634. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12635. ASSERT_TRUE(ssl_svr.is_valid());
  12636. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  12637. res.set_content("test", "text/plain");
  12638. ssl_svr.stop();
  12639. });
  12640. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12641. thread t2 =
  12642. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  12643. auto se = detail::scope_exit([&] {
  12644. t2.join();
  12645. t.join();
  12646. ASSERT_FALSE(svr.is_running());
  12647. });
  12648. svr.wait_until_ready();
  12649. ssl_svr.wait_until_ready();
  12650. Client cli("127.0.0.1", PORT);
  12651. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  12652. cli.enable_server_certificate_verification(true);
  12653. cli.set_follow_location(true);
  12654. cli.set_connection_timeout(30);
  12655. auto res = cli.Get("/index");
  12656. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12657. ASSERT_EQ(StatusCode::OK_200, res->status);
  12658. }
  12659. TEST(SSLClientRedirectTest, CertFile) {
  12660. auto ssl_port = PORT + 1;
  12661. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12662. ASSERT_TRUE(ssl_svr1.is_valid());
  12663. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  12664. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  12665. "/index");
  12666. ssl_svr1.stop();
  12667. });
  12668. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12669. ASSERT_TRUE(ssl_svr2.is_valid());
  12670. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  12671. res.set_content("test", "text/plain");
  12672. ssl_svr2.stop();
  12673. });
  12674. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  12675. thread t2 =
  12676. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  12677. auto se = detail::scope_exit([&] {
  12678. t2.join();
  12679. t.join();
  12680. ASSERT_FALSE(ssl_svr1.is_running());
  12681. });
  12682. ssl_svr1.wait_until_ready();
  12683. ssl_svr2.wait_until_ready();
  12684. SSLClient cli("127.0.0.1", PORT);
  12685. std::string cert;
  12686. read_file(SERVER_CERT2_FILE, cert);
  12687. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12688. cli.enable_server_certificate_verification(true);
  12689. cli.set_follow_location(true);
  12690. cli.set_connection_timeout(30);
  12691. auto res = cli.Get("/index");
  12692. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12693. ASSERT_EQ(StatusCode::OK_200, res->status);
  12694. }
  12695. #endif
  12696. #ifdef CPPHTTPLIB_SSL_ENABLED
  12697. // Test that set_ca_cert_store() skips system certs (consistent with
  12698. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  12699. // should be trusted - system certs should NOT be loaded.
  12700. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  12701. // Load a specific cert that is NOT a system CA cert
  12702. std::string cert;
  12703. read_file(SERVER_CERT2_FILE, cert);
  12704. SSLClient cli("google.com");
  12705. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12706. cli.enable_server_certificate_verification(true);
  12707. // This should FAIL because:
  12708. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  12709. // 2. System certs should NOT be loaded when custom store is set
  12710. // If system certs WERE loaded, this would succeed
  12711. auto res = cli.Get("/");
  12712. ASSERT_FALSE(res);
  12713. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12714. }
  12715. // Same as above, but through the native store handle path. Regression test:
  12716. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  12717. // merged system certs into the user-provided store.
  12718. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  12719. std::string cert;
  12720. read_file(SERVER_CERT2_FILE, cert);
  12721. SSLClient cli("google.com");
  12722. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  12723. cli.enable_server_certificate_verification(true);
  12724. auto res = cli.Get("/");
  12725. ASSERT_FALSE(res);
  12726. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12727. }
  12728. // A custom store set via the native handle must still verify a server whose
  12729. // cert it does contain.
  12730. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  12731. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12732. ASSERT_TRUE(svr.is_valid());
  12733. svr.Get("/test", [&](const Request &, Response &res) {
  12734. res.set_content("test", "text/plain");
  12735. });
  12736. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12737. auto se = detail::scope_exit([&] {
  12738. svr.stop();
  12739. t.join();
  12740. ASSERT_FALSE(svr.is_running());
  12741. });
  12742. svr.wait_until_ready();
  12743. SSLClient cli("127.0.0.1", PORT);
  12744. std::string cert;
  12745. read_file(SERVER_CERT2_FILE, cert);
  12746. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  12747. cli.enable_server_certificate_verification(true);
  12748. cli.set_connection_timeout(30);
  12749. auto res = cli.Get("/test");
  12750. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12751. ASSERT_EQ(StatusCode::OK_200, res->status);
  12752. }
  12753. // CA certs loaded through the universal Client must be transferred to the
  12754. // client created internally for following an HTTPS redirect. Regression test:
  12755. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  12756. // the CA data for redirect transfer.
  12757. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  12758. auto ssl_port = PORT + 1;
  12759. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12760. ASSERT_TRUE(ssl_svr1.is_valid());
  12761. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  12762. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  12763. "/index");
  12764. });
  12765. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12766. ASSERT_TRUE(ssl_svr2.is_valid());
  12767. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  12768. res.set_content("test", "text/plain");
  12769. });
  12770. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  12771. thread t2 =
  12772. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  12773. auto se = detail::scope_exit([&] {
  12774. ssl_svr2.stop();
  12775. ssl_svr1.stop();
  12776. t2.join();
  12777. t.join();
  12778. ASSERT_FALSE(ssl_svr1.is_running());
  12779. });
  12780. ssl_svr1.wait_until_ready();
  12781. ssl_svr2.wait_until_ready();
  12782. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  12783. std::string cert;
  12784. read_file(SERVER_CERT2_FILE, cert);
  12785. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12786. cli.enable_server_certificate_verification(true);
  12787. cli.set_follow_location(true);
  12788. cli.set_connection_timeout(30);
  12789. auto res = cli.Get("/index");
  12790. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12791. ASSERT_EQ(StatusCode::OK_200, res->status);
  12792. }
  12793. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  12794. // so a host signed by a system CA verifies even though a custom CA is set
  12795. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  12796. std::string cert;
  12797. read_file(SERVER_CERT2_FILE, cert);
  12798. SSLClient cli("google.com");
  12799. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12800. cli.enable_system_ca(true);
  12801. cli.enable_server_certificate_verification(true);
  12802. auto res = cli.Get("/");
  12803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12804. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12805. }
  12806. // The custom CA remains effective when combined with the system CA
  12807. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  12808. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12809. ASSERT_TRUE(svr.is_valid());
  12810. svr.Get("/test", [&](const Request &, Response &res) {
  12811. res.set_content("test", "text/plain");
  12812. });
  12813. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12814. auto se = detail::scope_exit([&] {
  12815. svr.stop();
  12816. t.join();
  12817. ASSERT_FALSE(svr.is_running());
  12818. });
  12819. svr.wait_until_ready();
  12820. SSLClient cli("127.0.0.1", PORT);
  12821. std::string cert;
  12822. read_file(SERVER_CERT2_FILE, cert);
  12823. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12824. cli.enable_system_ca(true);
  12825. cli.enable_server_certificate_verification(true);
  12826. cli.set_connection_timeout(30);
  12827. auto res = cli.Get("/test");
  12828. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12829. ASSERT_EQ(StatusCode::OK_200, res->status);
  12830. }
  12831. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  12832. // skip chain verification entirely (only the certificate identity was
  12833. // checked), so a server presenting an untrusted certificate with a matching
  12834. // IP SAN was accepted. The chain must be validated for IP hosts too.
  12835. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  12836. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12837. ASSERT_TRUE(svr.is_valid());
  12838. svr.Get("/test", [&](const Request &, Response &res) {
  12839. res.set_content("test", "text/plain");
  12840. });
  12841. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12842. auto se = detail::scope_exit([&] {
  12843. svr.stop();
  12844. t.join();
  12845. ASSERT_FALSE(svr.is_running());
  12846. });
  12847. svr.wait_until_ready();
  12848. SSLClient cli("127.0.0.1", PORT);
  12849. std::string cert;
  12850. // A trusted CA that did not sign the server certificate. The server cert
  12851. // (cert2) carries the matching IP SAN, so only chain validation can reject
  12852. // this connection.
  12853. read_file(CLIENT_CA_CERT_FILE, cert);
  12854. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12855. cli.enable_server_certificate_verification(true);
  12856. cli.set_connection_timeout(30);
  12857. auto res = cli.Get("/test");
  12858. ASSERT_FALSE(res);
  12859. }
  12860. // enable_system_ca(false) prevents system CA loading entirely
  12861. TEST(SSLClientTest, DisableSystemCa_Online) {
  12862. SSLClient cli("google.com");
  12863. cli.enable_system_ca(false);
  12864. cli.enable_server_certificate_verification(true);
  12865. auto res = cli.Get("/");
  12866. ASSERT_FALSE(res);
  12867. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  12868. // itself when the CA chain is empty
  12869. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  12870. res.error() == Error::SSLConnection);
  12871. }
  12872. // The universal Client forwards enable_system_ca()
  12873. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  12874. std::string cert;
  12875. read_file(SERVER_CERT2_FILE, cert);
  12876. Client cli("https://google.com");
  12877. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12878. cli.enable_system_ca(true);
  12879. cli.enable_server_certificate_verification(true);
  12880. auto res = cli.Get("/");
  12881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12882. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12883. }
  12884. // The system CA policy must carry over to the client created internally for
  12885. // following a cross-host HTTPS redirect
  12886. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  12887. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12888. ASSERT_TRUE(svr.is_valid());
  12889. svr.Get("/index", [&](const Request &, Response &res) {
  12890. res.set_redirect("https://www.google.com/");
  12891. });
  12892. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12893. auto se = detail::scope_exit([&] {
  12894. svr.stop();
  12895. t.join();
  12896. ASSERT_FALSE(svr.is_running());
  12897. });
  12898. svr.wait_until_ready();
  12899. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  12900. std::string cert;
  12901. read_file(SERVER_CERT2_FILE, cert);
  12902. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12903. cli.enable_system_ca(true);
  12904. cli.enable_server_certificate_verification(true);
  12905. cli.set_follow_location(true);
  12906. cli.set_connection_timeout(30);
  12907. // Receiving any response proves the redirect client completed the TLS
  12908. // handshake with a system-CA-signed host
  12909. auto res = cli.Get("/index");
  12910. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12911. }
  12912. TEST(MultipartFormDataTest, LargeData) {
  12913. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12914. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  12915. const ContentReader &content_reader) {
  12916. if (req.is_multipart_form_data()) {
  12917. std::vector<FormData> items;
  12918. content_reader(
  12919. [&](const FormData &file) {
  12920. items.push_back(file);
  12921. return true;
  12922. },
  12923. [&](const char *data, size_t data_length) {
  12924. items.back().content.append(data, data_length);
  12925. return true;
  12926. });
  12927. EXPECT_TRUE(std::string(items[0].name) == "document");
  12928. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  12929. EXPECT_TRUE(items[0].filename == "2MB_data");
  12930. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  12931. EXPECT_TRUE(items[1].name == "hello");
  12932. EXPECT_TRUE(items[1].content == "world");
  12933. EXPECT_TRUE(items[1].filename == "");
  12934. EXPECT_TRUE(items[1].content_type == "");
  12935. } else {
  12936. std::string body;
  12937. content_reader([&](const char *data, size_t data_length) {
  12938. body.append(data, data_length);
  12939. return true;
  12940. });
  12941. }
  12942. });
  12943. auto port = svr.bind_to_any_port(HOST);
  12944. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12945. auto se = detail::scope_exit([&] {
  12946. svr.stop();
  12947. t.join();
  12948. ASSERT_FALSE(svr.is_running());
  12949. });
  12950. svr.wait_until_ready();
  12951. {
  12952. std::string data(1024 * 1024 * 2, '.');
  12953. std::stringstream buffer;
  12954. buffer << data;
  12955. SSLClient cli(HOST, port);
  12956. cli.enable_server_certificate_verification(false);
  12957. UploadFormDataItems items{
  12958. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  12959. {"hello", "world", "", ""},
  12960. };
  12961. auto res = cli.Post("/post", items);
  12962. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12963. ASSERT_EQ(StatusCode::OK_200, res->status);
  12964. }
  12965. }
  12966. TEST(MultipartFormDataTest, DataProviderItems) {
  12967. std::random_device seed_gen;
  12968. std::mt19937 random(seed_gen());
  12969. std::string rand1;
  12970. rand1.resize(1000);
  12971. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  12972. std::string rand2;
  12973. rand2.resize(3000);
  12974. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  12975. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12976. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  12977. const ContentReader &content_reader) {
  12978. ASSERT_FALSE(req.is_multipart_form_data());
  12979. std::string body;
  12980. content_reader([&](const char *data, size_t data_length) {
  12981. body.append(data, data_length);
  12982. return true;
  12983. });
  12984. EXPECT_EQ(body, "");
  12985. });
  12986. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  12987. const ContentReader &content_reader) {
  12988. ASSERT_TRUE(req.is_multipart_form_data());
  12989. std::vector<FormData> items;
  12990. content_reader(
  12991. [&](const FormData &file) {
  12992. items.push_back(file);
  12993. return true;
  12994. },
  12995. [&](const char *data, size_t data_length) {
  12996. items.back().content.append(data, data_length);
  12997. return true;
  12998. });
  12999. ASSERT_TRUE(items.size() == 2);
  13000. EXPECT_EQ(std::string(items[0].name), "name1");
  13001. EXPECT_EQ(items[0].content, "Testing123");
  13002. EXPECT_EQ(items[0].filename, "filename1");
  13003. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  13004. EXPECT_EQ(items[1].name, "name2");
  13005. EXPECT_EQ(items[1].content, "Testing456");
  13006. EXPECT_EQ(items[1].filename, "");
  13007. EXPECT_EQ(items[1].content_type, "");
  13008. });
  13009. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  13010. const ContentReader &content_reader) {
  13011. ASSERT_TRUE(req.is_multipart_form_data());
  13012. std::vector<FormData> items;
  13013. content_reader(
  13014. [&](const FormData &file) {
  13015. items.push_back(file);
  13016. return true;
  13017. },
  13018. [&](const char *data, size_t data_length) {
  13019. items.back().content.append(data, data_length);
  13020. return true;
  13021. });
  13022. ASSERT_TRUE(items.size() == 2);
  13023. EXPECT_EQ(items[0].name, "name3");
  13024. EXPECT_EQ(items[0].content, rand1);
  13025. EXPECT_EQ(items[0].filename, "filename3");
  13026. EXPECT_EQ(items[0].content_type, "");
  13027. EXPECT_EQ(items[1].name, "name4");
  13028. EXPECT_EQ(items[1].content, rand2);
  13029. EXPECT_EQ(items[1].filename, "filename4");
  13030. EXPECT_EQ(items[1].content_type, "");
  13031. });
  13032. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  13033. const ContentReader &content_reader) {
  13034. ASSERT_TRUE(req.is_multipart_form_data());
  13035. std::vector<FormData> items;
  13036. content_reader(
  13037. [&](const FormData &file) {
  13038. items.push_back(file);
  13039. return true;
  13040. },
  13041. [&](const char *data, size_t data_length) {
  13042. items.back().content.append(data, data_length);
  13043. return true;
  13044. });
  13045. ASSERT_TRUE(items.size() == 4);
  13046. EXPECT_EQ(std::string(items[0].name), "name1");
  13047. EXPECT_EQ(items[0].content, "Testing123");
  13048. EXPECT_EQ(items[0].filename, "filename1");
  13049. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  13050. EXPECT_EQ(items[1].name, "name2");
  13051. EXPECT_EQ(items[1].content, "Testing456");
  13052. EXPECT_EQ(items[1].filename, "");
  13053. EXPECT_EQ(items[1].content_type, "");
  13054. EXPECT_EQ(items[2].name, "name3");
  13055. EXPECT_EQ(items[2].content, rand1);
  13056. EXPECT_EQ(items[2].filename, "filename3");
  13057. EXPECT_EQ(items[2].content_type, "");
  13058. EXPECT_EQ(items[3].name, "name4");
  13059. EXPECT_EQ(items[3].content, rand2);
  13060. EXPECT_EQ(items[3].filename, "filename4");
  13061. EXPECT_EQ(items[3].content_type, "");
  13062. });
  13063. auto port = svr.bind_to_any_port("localhost");
  13064. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13065. auto se = detail::scope_exit([&] {
  13066. svr.stop();
  13067. t.join();
  13068. ASSERT_FALSE(svr.is_running());
  13069. });
  13070. svr.wait_until_ready();
  13071. {
  13072. SSLClient cli("localhost", port);
  13073. cli.enable_server_certificate_verification(false);
  13074. UploadFormDataItems items{
  13075. {"name1", "Testing123", "filename1", "application/octet-stream"},
  13076. {"name2", "Testing456", "", ""}, // not a file
  13077. };
  13078. {
  13079. auto res = cli.Post("/post-none", {}, {}, {});
  13080. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13081. ASSERT_EQ(StatusCode::OK_200, res->status);
  13082. }
  13083. FormDataProviderItems providers;
  13084. {
  13085. auto res =
  13086. cli.Post("/post-items", {}, items, providers); // empty providers
  13087. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13088. ASSERT_EQ(StatusCode::OK_200, res->status);
  13089. }
  13090. providers.push_back({"name3",
  13091. [&](size_t offset, httplib::DataSink &sink) -> bool {
  13092. // test the offset is given correctly at each step
  13093. if (!offset)
  13094. sink.os.write(rand1.data(), 30);
  13095. else if (offset == 30)
  13096. sink.os.write(rand1.data() + 30, 300);
  13097. else if (offset == 330)
  13098. sink.os.write(rand1.data() + 330, 670);
  13099. else if (offset == rand1.size())
  13100. sink.done();
  13101. return true;
  13102. },
  13103. "filename3",
  13104. {}});
  13105. providers.push_back({"name4",
  13106. [&](size_t offset, httplib::DataSink &sink) -> bool {
  13107. // test the offset is given correctly at each step
  13108. if (!offset)
  13109. sink.os.write(rand2.data(), 2000);
  13110. else if (offset == 2000)
  13111. sink.os.write(rand2.data() + 2000, 1);
  13112. else if (offset == 2001)
  13113. sink.os.write(rand2.data() + 2001, 999);
  13114. else if (offset == rand2.size())
  13115. sink.done();
  13116. return true;
  13117. },
  13118. "filename4",
  13119. {}});
  13120. {
  13121. auto res = cli.Post("/post-providers", {}, {}, providers);
  13122. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13123. ASSERT_EQ(StatusCode::OK_200, res->status);
  13124. }
  13125. {
  13126. auto res = cli.Post("/post-both", {}, items, providers);
  13127. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13128. ASSERT_EQ(StatusCode::OK_200, res->status);
  13129. }
  13130. }
  13131. }
  13132. TEST(MultipartFormDataTest, BadHeader) {
  13133. Server svr;
  13134. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  13135. res.set_content("ok", "text/plain");
  13136. });
  13137. thread t = thread([&] { svr.listen(HOST, PORT); });
  13138. auto se = detail::scope_exit([&] {
  13139. svr.stop();
  13140. t.join();
  13141. ASSERT_FALSE(svr.is_running());
  13142. });
  13143. svr.wait_until_ready();
  13144. const std::string body =
  13145. "This is the preamble. It is to be ignored, though it\r\n"
  13146. "is a handy place for composition agents to include an\r\n"
  13147. "explanatory note to non-MIME conformant readers.\r\n"
  13148. "\r\n"
  13149. "\r\n"
  13150. "--simple boundary\r\n"
  13151. "Content-Disposition: form-data; name=\"field1\"\r\n"
  13152. ": BAD...\r\n"
  13153. "\r\n"
  13154. "value1\r\n"
  13155. "--simple boundary\r\n"
  13156. "Content-Disposition: form-data; name=\"field2\"; "
  13157. "filename=\"example.txt\"\r\n"
  13158. "\r\n"
  13159. "value2\r\n"
  13160. "--simple boundary--\r\n"
  13161. "This is the epilogue. It is also to be ignored.\r\n";
  13162. std::string content_type =
  13163. R"(multipart/form-data; boundary="simple boundary")";
  13164. Client cli(HOST, PORT);
  13165. auto res = cli.Post("/post", body, content_type.c_str());
  13166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13167. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  13168. }
  13169. TEST(MultipartFormDataTest, WithPreamble) {
  13170. Server svr;
  13171. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  13172. res.set_content("ok", "text/plain");
  13173. });
  13174. thread t = thread([&] { svr.listen(HOST, PORT); });
  13175. auto se = detail::scope_exit([&] {
  13176. svr.stop();
  13177. t.join();
  13178. ASSERT_FALSE(svr.is_running());
  13179. });
  13180. svr.wait_until_ready();
  13181. const std::string body =
  13182. "This is the preamble. It is to be ignored, though it\r\n"
  13183. "is a handy place for composition agents to include an\r\n"
  13184. "explanatory note to non-MIME conformant readers.\r\n"
  13185. "\r\n"
  13186. "\r\n"
  13187. "--simple boundary\r\n"
  13188. "Content-Disposition: form-data; name=\"field1\"\r\n"
  13189. "\r\n"
  13190. "value1\r\n"
  13191. "--simple boundary\r\n"
  13192. "Content-Disposition: form-data; name=\"field2\"; "
  13193. "filename=\"example.txt\"\r\n"
  13194. "\r\n"
  13195. "value2\r\n"
  13196. "--simple boundary--\r\n"
  13197. "This is the epilogue. It is also to be ignored.\r\n";
  13198. std::string content_type =
  13199. R"(multipart/form-data; boundary="simple boundary")";
  13200. Client cli(HOST, PORT);
  13201. auto res = cli.Post("/post", body, content_type.c_str());
  13202. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13203. EXPECT_EQ(StatusCode::OK_200, res->status);
  13204. }
  13205. TEST(MultipartFormDataTest, PostCustomBoundary) {
  13206. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13207. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  13208. const ContentReader &content_reader) {
  13209. if (req.is_multipart_form_data()) {
  13210. std::vector<FormData> items;
  13211. content_reader(
  13212. [&](const FormData &file) {
  13213. items.push_back(file);
  13214. return true;
  13215. },
  13216. [&](const char *data, size_t data_length) {
  13217. items.back().content.append(data, data_length);
  13218. return true;
  13219. });
  13220. EXPECT_TRUE(std::string(items[0].name) == "document");
  13221. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13222. EXPECT_TRUE(items[0].filename == "2MB_data");
  13223. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13224. EXPECT_TRUE(items[1].name == "hello");
  13225. EXPECT_TRUE(items[1].content == "world");
  13226. EXPECT_TRUE(items[1].filename == "");
  13227. EXPECT_TRUE(items[1].content_type == "");
  13228. } else {
  13229. std::string body;
  13230. content_reader([&](const char *data, size_t data_length) {
  13231. body.append(data, data_length);
  13232. return true;
  13233. });
  13234. }
  13235. });
  13236. auto port = svr.bind_to_any_port("localhost");
  13237. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13238. auto se = detail::scope_exit([&] {
  13239. svr.stop();
  13240. t.join();
  13241. ASSERT_FALSE(svr.is_running());
  13242. });
  13243. svr.wait_until_ready();
  13244. {
  13245. std::string data(1024 * 1024 * 2, '.');
  13246. std::stringstream buffer;
  13247. buffer << data;
  13248. SSLClient cli("localhost", port);
  13249. cli.enable_server_certificate_verification(false);
  13250. UploadFormDataItems items{
  13251. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13252. {"hello", "world", "", ""},
  13253. };
  13254. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  13255. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13256. ASSERT_EQ(StatusCode::OK_200, res->status);
  13257. }
  13258. }
  13259. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  13260. std::string data(1024 * 1024 * 2, '&');
  13261. std::stringstream buffer;
  13262. buffer << data;
  13263. Client cli("https://localhost:8080");
  13264. UploadFormDataItems items{
  13265. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13266. {"hello", "world", "", ""},
  13267. };
  13268. for (const char &c : " \t\r\n") {
  13269. auto res =
  13270. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  13271. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  13272. ASSERT_FALSE(res);
  13273. }
  13274. }
  13275. TEST(MultipartFormDataTest, PutFormData) {
  13276. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13277. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  13278. const ContentReader &content_reader) {
  13279. if (req.is_multipart_form_data()) {
  13280. std::vector<FormData> items;
  13281. content_reader(
  13282. [&](const FormData &file) {
  13283. items.push_back(file);
  13284. return true;
  13285. },
  13286. [&](const char *data, size_t data_length) {
  13287. items.back().content.append(data, data_length);
  13288. return true;
  13289. });
  13290. EXPECT_TRUE(std::string(items[0].name) == "document");
  13291. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13292. EXPECT_TRUE(items[0].filename == "2MB_data");
  13293. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13294. EXPECT_TRUE(items[1].name == "hello");
  13295. EXPECT_TRUE(items[1].content == "world");
  13296. EXPECT_TRUE(items[1].filename == "");
  13297. EXPECT_TRUE(items[1].content_type == "");
  13298. } else {
  13299. std::string body;
  13300. content_reader([&](const char *data, size_t data_length) {
  13301. body.append(data, data_length);
  13302. return true;
  13303. });
  13304. }
  13305. });
  13306. auto port = svr.bind_to_any_port("localhost");
  13307. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13308. auto se = detail::scope_exit([&] {
  13309. svr.stop();
  13310. t.join();
  13311. ASSERT_FALSE(svr.is_running());
  13312. });
  13313. svr.wait_until_ready();
  13314. {
  13315. std::string data(1024 * 1024 * 2, '&');
  13316. std::stringstream buffer;
  13317. buffer << data;
  13318. SSLClient cli("localhost", port);
  13319. cli.enable_server_certificate_verification(false);
  13320. UploadFormDataItems items{
  13321. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13322. {"hello", "world", "", ""},
  13323. };
  13324. auto res = cli.Put("/put", items);
  13325. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13326. ASSERT_EQ(StatusCode::OK_200, res->status);
  13327. }
  13328. }
  13329. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  13330. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13331. svr.Put("/put_customboundary",
  13332. [&](const Request &req, const Response & /*res*/,
  13333. const ContentReader &content_reader) {
  13334. if (req.is_multipart_form_data()) {
  13335. std::vector<FormData> items;
  13336. content_reader(
  13337. [&](const FormData &file) {
  13338. items.push_back(file);
  13339. return true;
  13340. },
  13341. [&](const char *data, size_t data_length) {
  13342. items.back().content.append(data, data_length);
  13343. return true;
  13344. });
  13345. EXPECT_TRUE(std::string(items[0].name) == "document");
  13346. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13347. EXPECT_TRUE(items[0].filename == "2MB_data");
  13348. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13349. EXPECT_TRUE(items[1].name == "hello");
  13350. EXPECT_TRUE(items[1].content == "world");
  13351. EXPECT_TRUE(items[1].filename == "");
  13352. EXPECT_TRUE(items[1].content_type == "");
  13353. } else {
  13354. std::string body;
  13355. content_reader([&](const char *data, size_t data_length) {
  13356. body.append(data, data_length);
  13357. return true;
  13358. });
  13359. }
  13360. });
  13361. auto port = svr.bind_to_any_port("localhost");
  13362. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13363. auto se = detail::scope_exit([&] {
  13364. svr.stop();
  13365. t.join();
  13366. ASSERT_FALSE(svr.is_running());
  13367. });
  13368. svr.wait_until_ready();
  13369. {
  13370. std::string data(1024 * 1024 * 2, '&');
  13371. std::stringstream buffer;
  13372. buffer << data;
  13373. SSLClient cli("localhost", port);
  13374. cli.enable_server_certificate_verification(false);
  13375. UploadFormDataItems items{
  13376. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13377. {"hello", "world", "", ""},
  13378. };
  13379. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  13380. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13381. ASSERT_EQ(StatusCode::OK_200, res->status);
  13382. }
  13383. }
  13384. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  13385. std::string data(1024 * 1024 * 2, '&');
  13386. std::stringstream buffer;
  13387. buffer << data;
  13388. Client cli("https://localhost:8080");
  13389. cli.enable_server_certificate_verification(false);
  13390. UploadFormDataItems items{
  13391. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13392. {"hello", "world", "", ""},
  13393. };
  13394. for (const char &c : " \t\r\n") {
  13395. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  13396. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  13397. ASSERT_FALSE(res);
  13398. }
  13399. }
  13400. TEST(MultipartFormDataTest, AlternateFilename) {
  13401. auto handled = false;
  13402. Server svr;
  13403. svr.Post("/test", [&](const Request &req, Response &res) {
  13404. ASSERT_EQ(2u, req.form.files.size());
  13405. ASSERT_EQ(1u, req.form.fields.size());
  13406. // Test files
  13407. const auto &file1 = req.form.get_file("file1");
  13408. ASSERT_EQ("file1", file1.name);
  13409. ASSERT_EQ("A.txt", file1.filename);
  13410. ASSERT_EQ("text/plain", file1.content_type);
  13411. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  13412. const auto &file2 = req.form.get_file("file2");
  13413. ASSERT_EQ("file2", file2.name);
  13414. ASSERT_EQ("a.html", file2.filename);
  13415. ASSERT_EQ("text/html", file2.content_type);
  13416. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  13417. file2.content);
  13418. // Test text field
  13419. const auto &text = req.form.get_field("text");
  13420. ASSERT_EQ("text default", text);
  13421. res.set_content("ok", "text/plain");
  13422. handled = true;
  13423. });
  13424. thread t = thread([&] { svr.listen(HOST, PORT); });
  13425. auto se = detail::scope_exit([&] {
  13426. svr.stop();
  13427. t.join();
  13428. ASSERT_FALSE(svr.is_running());
  13429. ASSERT_TRUE(handled);
  13430. });
  13431. svr.wait_until_ready();
  13432. auto req = "POST /test HTTP/1.1\r\n"
  13433. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13434. "Content-Length: 399\r\n"
  13435. "\r\n"
  13436. "----------\r\n"
  13437. "Content-Disposition: form-data; name=\"text\"\r\n"
  13438. "\r\n"
  13439. "text default\r\n"
  13440. "----------\r\n"
  13441. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  13442. "filename=\"a.txt\"; name=\"file1\"\r\n"
  13443. "Content-Type: text/plain\r\n"
  13444. "\r\n"
  13445. "Content of a.txt.\r\n"
  13446. "\r\n"
  13447. "----------\r\n"
  13448. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  13449. "\"a.html\"\r\n"
  13450. "Content-Type: text/html\r\n"
  13451. "\r\n"
  13452. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  13453. "\r\n"
  13454. "------------\r\n";
  13455. ASSERT_TRUE(send_request(1, req));
  13456. }
  13457. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  13458. auto handled = false;
  13459. Server svr;
  13460. svr.Post("/test", [&](const Request &req, Response &res) {
  13461. // Case-insensitive "utf-8''" prefix with a long value
  13462. const auto &file = req.form.get_file("file1");
  13463. ASSERT_EQ("file1", file.name);
  13464. // 8000 chars exercises both the Content-Disposition parser and the
  13465. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  13466. // Prior to the fix, std::regex_match on this header would cause O(N)
  13467. // stack recursion in libstdc++, leading to SIGSEGV.
  13468. std::string expected_filename(8000, 'A');
  13469. ASSERT_EQ(expected_filename, file.filename);
  13470. res.set_content("ok", "text/plain");
  13471. handled = true;
  13472. });
  13473. thread t = thread([&] { svr.listen(HOST, PORT); });
  13474. auto se = detail::scope_exit([&] {
  13475. svr.stop();
  13476. t.join();
  13477. ASSERT_FALSE(svr.is_running());
  13478. ASSERT_TRUE(handled);
  13479. });
  13480. svr.wait_until_ready();
  13481. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  13482. // Regression test for GHSA-qq6v-r583-3h69
  13483. std::string long_filename(8000, 'A');
  13484. std::string body = "----------\r\n"
  13485. "Content-Disposition: form-data; name=\"file1\"; "
  13486. "filename*=\"Utf-8''" +
  13487. long_filename +
  13488. "\"\r\n"
  13489. "\r\n"
  13490. "hello\r\n"
  13491. "------------\r\n";
  13492. auto req = "POST /test HTTP/1.1\r\n"
  13493. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13494. "Content-Length: " +
  13495. std::to_string(body.size()) + "\r\n\r\n" + body;
  13496. ASSERT_TRUE(send_request(1, req));
  13497. }
  13498. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  13499. auto handled = false;
  13500. Server svr;
  13501. svr.Post("/test", [&](const Request &req, Response &) {
  13502. ASSERT_EQ(2u, req.form.fields.size());
  13503. const auto &text1 = req.form.get_field("text1");
  13504. ASSERT_EQ("text1", text1);
  13505. const auto &text2 = req.form.get_field("text2");
  13506. ASSERT_EQ("text2", text2);
  13507. handled = true;
  13508. });
  13509. thread t = thread([&] { svr.listen(HOST, PORT); });
  13510. auto se = detail::scope_exit([&] {
  13511. svr.stop();
  13512. t.join();
  13513. ASSERT_FALSE(svr.is_running());
  13514. ASSERT_TRUE(handled);
  13515. });
  13516. svr.wait_until_ready();
  13517. auto req = "POST /test HTTP/1.1\r\n"
  13518. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13519. "Content-Length: 146\r\n"
  13520. "\r\n----------\r\n"
  13521. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13522. "\r\n"
  13523. "text1"
  13524. "\r\n----------\r\n"
  13525. "Content-Disposition: form-data; name=\"text2\"\r\n"
  13526. "\r\n"
  13527. "text2"
  13528. "\r\n------------";
  13529. std::string response;
  13530. ASSERT_TRUE(send_request(1, req, &response));
  13531. ASSERT_EQ("200", response.substr(9, 3));
  13532. }
  13533. TEST(MultipartFormDataTest, ContentLength) {
  13534. auto handled = false;
  13535. Server svr;
  13536. svr.Post("/test", [&](const Request &req, Response &) {
  13537. ASSERT_EQ(2u, req.form.fields.size());
  13538. const auto &text1 = req.form.get_field("text1");
  13539. ASSERT_EQ("text1", text1);
  13540. const auto &text2 = req.form.get_field("text2");
  13541. ASSERT_EQ("text2", text2);
  13542. handled = true;
  13543. });
  13544. thread t = thread([&] { svr.listen(HOST, PORT); });
  13545. auto se = detail::scope_exit([&] {
  13546. svr.stop();
  13547. t.join();
  13548. ASSERT_FALSE(svr.is_running());
  13549. ASSERT_TRUE(handled);
  13550. });
  13551. svr.wait_until_ready();
  13552. auto req = "POST /test HTTP/1.1\r\n"
  13553. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13554. "Content-Length: 167\r\n"
  13555. "\r\n----------\r\n"
  13556. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13557. "Content-Length: 5\r\n"
  13558. "\r\n"
  13559. "text1"
  13560. "\r\n----------\r\n"
  13561. "Content-Disposition: form-data; name=\"text2\"\r\n"
  13562. "\r\n"
  13563. "text2"
  13564. "\r\n------------\r\n";
  13565. std::string response;
  13566. ASSERT_TRUE(send_request(1, req, &response));
  13567. ASSERT_EQ("200", response.substr(9, 3));
  13568. }
  13569. TEST(MultipartFormDataTest, AccessPartHeaders) {
  13570. auto handled = false;
  13571. Server svr;
  13572. svr.Post("/test", [&](const Request &req, Response &) {
  13573. ASSERT_EQ(2u, req.form.fields.size());
  13574. const auto &text1 = req.form.get_field("text1");
  13575. ASSERT_EQ("text1", text1);
  13576. // TODO: Add header access for text fields if needed
  13577. const auto &text2 = req.form.get_field("text2");
  13578. ASSERT_EQ("text2", text2);
  13579. // TODO: Header access for text fields needs to be implemented
  13580. // auto &headers = it->second.headers;
  13581. // ASSERT_EQ(3U, headers.size());
  13582. // auto custom_header = headers.find("x-whatever");
  13583. // ASSERT_TRUE(custom_header != headers.end());
  13584. // ASSERT_NE("customvalue", custom_header->second);
  13585. // ASSERT_EQ("CustomValue", custom_header->second);
  13586. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  13587. handled = true;
  13588. });
  13589. thread t = thread([&] { svr.listen(HOST, PORT); });
  13590. auto se = detail::scope_exit([&] {
  13591. svr.stop();
  13592. t.join();
  13593. ASSERT_FALSE(svr.is_running());
  13594. ASSERT_TRUE(handled);
  13595. });
  13596. svr.wait_until_ready();
  13597. auto req = "POST /test HTTP/1.1\r\n"
  13598. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13599. "Content-Length: 232\r\n"
  13600. "\r\n----------\r\n"
  13601. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13602. "Content-Length: 5\r\n"
  13603. "X-Test: 1\r\n"
  13604. "\r\n"
  13605. "text1"
  13606. "\r\n----------\r\n"
  13607. "Content-Disposition: form-data; name=\"text2\"\r\n"
  13608. "Content-Type: text/plain\r\n"
  13609. "X-Whatever: CustomValue\r\n"
  13610. "\r\n"
  13611. "text2"
  13612. "\r\n------------\r\n"
  13613. "That should be disregarded. Not even read";
  13614. std::string response;
  13615. ASSERT_TRUE(send_request(1, req, &response));
  13616. ASSERT_EQ("200", response.substr(9, 3));
  13617. }
  13618. TEST(MultipartFormDataTest, LargeHeader) {
  13619. auto handled = false;
  13620. Server svr;
  13621. svr.Post("/test", [&](const Request &req, Response &) {
  13622. ASSERT_EQ(1u, req.form.fields.size());
  13623. const auto &text = req.form.get_field("name1");
  13624. ASSERT_EQ("text1", text);
  13625. handled = true;
  13626. });
  13627. thread t = thread([&] { svr.listen(HOST, PORT); });
  13628. auto se = detail::scope_exit([&] {
  13629. svr.stop();
  13630. t.join();
  13631. ASSERT_FALSE(svr.is_running());
  13632. ASSERT_TRUE(handled);
  13633. });
  13634. svr.wait_until_ready();
  13635. auto boundary = std::string("cpp-httplib-multipart-data");
  13636. std::string content = "--" + boundary +
  13637. "\r\n"
  13638. "Content-Disposition: form-data; name=\"name1\"\r\n"
  13639. "\r\n"
  13640. "text1\r\n"
  13641. "--" +
  13642. boundary + "--\r\n";
  13643. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  13644. "Content-Type: multipart/form-data;boundary=" +
  13645. boundary +
  13646. "\r\n"
  13647. "Content-Length: " +
  13648. std::to_string(content.size()) +
  13649. "\r\n"
  13650. "Dummy-Header: ";
  13651. std::string header_suffix = "\r\n"
  13652. "\r\n";
  13653. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  13654. size_t header_dummy_size =
  13655. read_buff_size -
  13656. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  13657. auto header_dummy = std::string(header_dummy_size, '@');
  13658. auto req = header_prefix + header_dummy + header_suffix + content;
  13659. std::string response;
  13660. ASSERT_TRUE(send_request(1, req, &response));
  13661. ASSERT_EQ("200", response.substr(9, 3));
  13662. }
  13663. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  13664. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  13665. // (not chunked Transfer-Encoding) after the streaming refactor.
  13666. auto handled = false;
  13667. Server svr;
  13668. svr.Post("/upload", [&](const Request &req, Response &res) {
  13669. auto cl_it = req.headers.find("Content-Length");
  13670. EXPECT_TRUE(cl_it != req.headers.end());
  13671. auto te_it = req.headers.find("Transfer-Encoding");
  13672. EXPECT_TRUE(te_it == req.headers.end());
  13673. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  13674. res.set_content("ok", "text/plain");
  13675. handled = true;
  13676. });
  13677. auto port = svr.bind_to_any_port(HOST);
  13678. auto t = thread([&] { svr.listen_after_bind(); });
  13679. auto se = detail::scope_exit([&] {
  13680. svr.stop();
  13681. t.join();
  13682. ASSERT_FALSE(svr.is_running());
  13683. ASSERT_TRUE(handled);
  13684. });
  13685. svr.wait_until_ready();
  13686. UploadFormDataItems items = {
  13687. {"field1", "hello", "", "text/plain"},
  13688. {"file1", "world", "test.txt", "application/octet-stream"},
  13689. };
  13690. Client cli(HOST, port);
  13691. auto res = cli.Post("/upload", {}, items);
  13692. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13693. EXPECT_EQ(StatusCode::OK_200, res->status);
  13694. }
  13695. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  13696. // Verify that make_multipart_content_provider coalesces many small segments
  13697. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  13698. constexpr size_t kItemCount = 1000;
  13699. UploadFormDataItems items;
  13700. items.reserve(kItemCount);
  13701. for (size_t i = 0; i < kItemCount; i++) {
  13702. items.push_back(
  13703. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  13704. }
  13705. const std::string boundary = "----test-boundary";
  13706. auto content_length = detail::get_multipart_content_length(items, boundary);
  13707. auto provider = detail::make_multipart_content_provider(items, boundary);
  13708. // Drive the provider the same way write_content_with_progress does
  13709. size_t write_count = 0;
  13710. size_t total_bytes = 0;
  13711. DataSink sink;
  13712. size_t offset = 0;
  13713. sink.write = [&](const char *d, size_t l) -> bool {
  13714. (void)d;
  13715. write_count++;
  13716. total_bytes += l;
  13717. offset += l;
  13718. return true;
  13719. };
  13720. sink.is_writable = []() -> bool { return true; };
  13721. while (offset < content_length) {
  13722. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  13723. }
  13724. EXPECT_EQ(content_length, total_bytes);
  13725. // The total number of segments is 3 * kItemCount + 1 = 3001.
  13726. // With buffering into 64KB blocks, write_count should be much smaller.
  13727. auto segment_count = 3 * kItemCount + 1;
  13728. EXPECT_LT(write_count, segment_count / 10);
  13729. }
  13730. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  13731. // Integration test: send many UploadFormDataItems and verify the server
  13732. // receives all of them correctly (#2410).
  13733. constexpr size_t kItemCount = 500;
  13734. auto handled = false;
  13735. Server svr;
  13736. svr.Post("/upload", [&](const Request &req, Response &res) {
  13737. EXPECT_EQ(kItemCount, req.form.fields.size());
  13738. for (size_t i = 0; i < kItemCount; i++) {
  13739. auto key = "field" + std::to_string(i);
  13740. auto val = "value" + std::to_string(i);
  13741. auto it = req.form.fields.find(key);
  13742. if (it != req.form.fields.end()) {
  13743. EXPECT_EQ(val, it->second.content);
  13744. } else {
  13745. ADD_FAILURE() << "Missing field: " << key;
  13746. }
  13747. }
  13748. res.set_content("ok", "text/plain");
  13749. handled = true;
  13750. });
  13751. auto port = svr.bind_to_any_port(HOST);
  13752. auto t = thread([&] { svr.listen_after_bind(); });
  13753. auto se = detail::scope_exit([&] {
  13754. svr.stop();
  13755. t.join();
  13756. ASSERT_FALSE(svr.is_running());
  13757. ASSERT_TRUE(handled);
  13758. });
  13759. svr.wait_until_ready();
  13760. UploadFormDataItems items;
  13761. items.reserve(kItemCount);
  13762. for (size_t i = 0; i < kItemCount; i++) {
  13763. items.push_back(
  13764. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  13765. }
  13766. Client cli(HOST, port);
  13767. auto res = cli.Post("/upload", items);
  13768. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13769. EXPECT_EQ(StatusCode::OK_200, res->status);
  13770. }
  13771. TEST(MultipartFormDataTest, MakeFileProvider) {
  13772. // Verify make_file_provider sends a file's contents correctly.
  13773. const std::string file_content(4096, 'Z');
  13774. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  13775. {
  13776. std::ofstream ofs(tmp_path, std::ios::binary);
  13777. ofs.write(file_content.data(),
  13778. static_cast<std::streamsize>(file_content.size()));
  13779. }
  13780. auto handled = false;
  13781. Server svr;
  13782. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  13783. const ContentReader &content_reader) {
  13784. ASSERT_TRUE(req.is_multipart_form_data());
  13785. std::vector<FormData> items;
  13786. content_reader(
  13787. [&](const FormData &file) {
  13788. items.push_back(file);
  13789. return true;
  13790. },
  13791. [&](const char *data, size_t data_length) {
  13792. items.back().content.append(data, data_length);
  13793. return true;
  13794. });
  13795. ASSERT_EQ(1u, items.size());
  13796. EXPECT_EQ("myfile", items[0].name);
  13797. EXPECT_EQ("data.bin", items[0].filename);
  13798. EXPECT_EQ("application/octet-stream", items[0].content_type);
  13799. EXPECT_EQ(file_content, items[0].content);
  13800. handled = true;
  13801. });
  13802. auto port = svr.bind_to_any_port(HOST);
  13803. auto t = thread([&] { svr.listen_after_bind(); });
  13804. auto se = detail::scope_exit([&] {
  13805. svr.stop();
  13806. t.join();
  13807. ASSERT_FALSE(svr.is_running());
  13808. ASSERT_TRUE(handled);
  13809. std::remove(tmp_path.c_str());
  13810. });
  13811. svr.wait_until_ready();
  13812. FormDataProviderItems providers;
  13813. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  13814. "application/octet-stream"));
  13815. Client cli(HOST, port);
  13816. auto res = cli.Post("/upload", {}, {}, providers);
  13817. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13818. EXPECT_EQ(StatusCode::OK_200, res->status);
  13819. }
  13820. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  13821. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  13822. // (100) headers is rejected with a 400 Bad Request response.
  13823. Server svr;
  13824. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  13825. res.set_content("ok", "text/plain");
  13826. });
  13827. thread t = thread([&] { svr.listen(HOST, PORT); });
  13828. auto se = detail::scope_exit([&] {
  13829. svr.stop();
  13830. t.join();
  13831. ASSERT_FALSE(svr.is_running());
  13832. });
  13833. svr.wait_until_ready();
  13834. // Build a multipart part with 101 custom headers (exceeding
  13835. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  13836. std::stringstream body;
  13837. body << "--simpleboundary\r\n"
  13838. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  13839. for (int i = 0; i < 101; i++) {
  13840. body << "X-Custom-Header-" << i << ": value\r\n";
  13841. }
  13842. body << "\r\n"
  13843. << "value1\r\n"
  13844. << "--simpleboundary--\r\n";
  13845. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  13846. Client cli(HOST, PORT);
  13847. auto res = cli.Post("/post", body.str(), content_type.c_str());
  13848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13849. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  13850. }
  13851. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  13852. // A body that never contains the declared boundary must not be accumulated
  13853. // while the parser waits for it. Buffering it would also make every read
  13854. // rescan everything seen so far, which is quadratic in the body size.
  13855. Server svr;
  13856. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  13857. res.set_content("ok", "text/plain");
  13858. });
  13859. auto port = svr.bind_to_any_port(HOST);
  13860. thread t = thread([&] { svr.listen_after_bind(); });
  13861. auto se = detail::scope_exit([&] {
  13862. svr.stop();
  13863. t.join();
  13864. ASSERT_FALSE(svr.is_running());
  13865. });
  13866. svr.wait_until_ready();
  13867. Client cli(HOST, port);
  13868. cli.set_read_timeout(60, 0);
  13869. cli.set_write_timeout(60, 0);
  13870. // '-' is the worst case: it matches the first character of the boundary, so
  13871. // every position has to be checked against it.
  13872. auto post_dashes = [&](size_t size) {
  13873. const std::string body(size, '-');
  13874. auto start = std::chrono::steady_clock::now();
  13875. auto res =
  13876. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  13877. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  13878. std::chrono::steady_clock::now() - start)
  13879. .count();
  13880. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  13881. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  13882. return ms;
  13883. };
  13884. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  13885. // Windows.
  13886. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  13887. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  13888. // Comparing the two sizes rather than checking an absolute duration keeps
  13889. // this meaningful across build types and CI load, both of which move the
  13890. // absolute numbers by more than an order of magnitude. Four times the bytes
  13891. // costs about four times the time when parsing is linear, and about sixteen
  13892. // times when the body is buffered and rescanned.
  13893. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  13894. EXPECT_LT(ms_16mb, ms_4mb * 10)
  13895. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  13896. << "ms, which suggests the body is being buffered and rescanned";
  13897. }
  13898. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  13899. // A boundary can only be followed by CRLF or by "--", so anything else is
  13900. // malformed no matter what comes next. The parser must say so right away
  13901. // instead of buffering the rest of the declared body.
  13902. Server svr;
  13903. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  13904. res.set_content("ok", "text/plain");
  13905. });
  13906. auto port = svr.bind_to_any_port(HOST);
  13907. thread t = thread([&] { svr.listen_after_bind(); });
  13908. auto se = detail::scope_exit([&] {
  13909. svr.stop();
  13910. t.join();
  13911. ASSERT_FALSE(svr.is_running());
  13912. });
  13913. svr.wait_until_ready();
  13914. // Announce a 1 MB body but send only the malformed prefix. A parser that
  13915. // buffers instead of failing would still be waiting for the remaining bytes.
  13916. const std::string body = "--zzzz\r\n"
  13917. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13918. "\r\n"
  13919. "text1"
  13920. "\r\n--zzzzXX";
  13921. const std::string req = "POST /post HTTP/1.1\r\n"
  13922. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  13923. "Content-Length: 1048576\r\n"
  13924. "\r\n" +
  13925. body;
  13926. std::string response;
  13927. ASSERT_TRUE(send_request(3, req, &response, port));
  13928. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  13929. EXPECT_EQ("400", response.substr(9, 3));
  13930. }
  13931. // Posts a multipart body split into two writes, so that the server sees the
  13932. // split at whatever offset the caller chose, and expects the single "text1"
  13933. // field to come through.
  13934. static void expect_split_multipart_ok(const std::string &body1,
  13935. const std::string &body2) {
  13936. auto handled = false;
  13937. Server svr;
  13938. svr.Post("/post", [&](const Request &req, Response &) {
  13939. EXPECT_EQ(1u, req.form.fields.size());
  13940. EXPECT_EQ("text1", req.form.get_field("text1"));
  13941. handled = true;
  13942. });
  13943. auto port = svr.bind_to_any_port(HOST);
  13944. thread t = thread([&] { svr.listen_after_bind(); });
  13945. auto se = detail::scope_exit([&] {
  13946. svr.stop();
  13947. t.join();
  13948. ASSERT_FALSE(svr.is_running());
  13949. ASSERT_TRUE(handled);
  13950. });
  13951. svr.wait_until_ready();
  13952. // "Connection: close" makes the server close once it has answered, so the
  13953. // response drain ends immediately instead of idling until the read timeout.
  13954. const std::string head =
  13955. "POST /post HTTP/1.1\r\n"
  13956. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  13957. "Connection: close\r\n"
  13958. "Content-Length: " +
  13959. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  13960. std::string response;
  13961. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  13962. ASSERT_GE(response.size(), 12u) << "no response";
  13963. EXPECT_EQ("200", response.substr(9, 3));
  13964. }
  13965. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  13966. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  13967. // ignored, including when it does not arrive in the same read as the
  13968. // close-delimiter itself.
  13969. expect_split_multipart_ok("--zzzz\r\n"
  13970. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13971. "\r\n"
  13972. "text1"
  13973. "\r\n--zzzz--",
  13974. "\r\nthis epilogue must be ignored\r\n");
  13975. }
  13976. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  13977. // The initial boundary may be preceded by a preamble of any length and may
  13978. // straddle a read boundary. Discarding data while waiting for it must not
  13979. // throw away a partial boundary sitting at the end of the buffer.
  13980. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  13981. "zz\r\n"
  13982. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13983. "\r\n"
  13984. "text1"
  13985. "\r\n--zzzz--\r\n");
  13986. }
  13987. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  13988. // The received boundary was only checked for being non-empty, so it could be
  13989. // as long as a header is allowed to be. The parser scans the body for
  13990. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  13991. // costs a nearly full comparison at nearly every position, making the
  13992. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  13993. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  13994. Server svr;
  13995. svr.Post("/post", [](const Request &req, Response &res) {
  13996. EXPECT_EQ(1u, req.form.fields.size());
  13997. EXPECT_EQ("text1", req.form.get_field("text1"));
  13998. res.set_content("ok", "text/plain");
  13999. });
  14000. auto port = svr.bind_to_any_port(HOST);
  14001. thread t = thread([&] { svr.listen_after_bind(); });
  14002. auto se = detail::scope_exit([&] {
  14003. svr.stop();
  14004. t.join();
  14005. ASSERT_FALSE(svr.is_running());
  14006. });
  14007. svr.wait_until_ready();
  14008. Client cli(HOST, port);
  14009. auto post_with_boundary_of_length = [&](size_t len) {
  14010. const std::string boundary(len, 'a');
  14011. const std::string body =
  14012. "--" + boundary +
  14013. "\r\n"
  14014. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14015. "\r\n"
  14016. "text1"
  14017. "\r\n--" +
  14018. boundary + "--\r\n";
  14019. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  14020. };
  14021. auto res = post_with_boundary_of_length(70);
  14022. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14023. EXPECT_EQ(StatusCode::OK_200, res->status);
  14024. res = post_with_boundary_of_length(71);
  14025. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14026. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14027. }
  14028. TEST(MakeFileBodyTest, Basic) {
  14029. const std::string file_content(4096, 'Z');
  14030. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  14031. {
  14032. std::ofstream ofs(tmp_path, std::ios::binary);
  14033. ofs.write(file_content.data(),
  14034. static_cast<std::streamsize>(file_content.size()));
  14035. }
  14036. auto handled = false;
  14037. Server svr;
  14038. svr.Post("/upload", [&](const Request &req, Response &res) {
  14039. EXPECT_EQ(file_content, req.body);
  14040. handled = true;
  14041. res.status = StatusCode::OK_200;
  14042. });
  14043. auto port = svr.bind_to_any_port(HOST);
  14044. auto t = thread([&] { svr.listen_after_bind(); });
  14045. auto se = detail::scope_exit([&] {
  14046. svr.stop();
  14047. t.join();
  14048. ASSERT_FALSE(svr.is_running());
  14049. ASSERT_TRUE(handled);
  14050. std::remove(tmp_path.c_str());
  14051. });
  14052. svr.wait_until_ready();
  14053. auto fb = make_file_body(tmp_path);
  14054. ASSERT_GT(fb.first, 0u);
  14055. Client cli(HOST, port);
  14056. auto res =
  14057. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  14058. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14059. EXPECT_EQ(StatusCode::OK_200, res->status);
  14060. }
  14061. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  14062. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  14063. {
  14064. std::ofstream ofs(path, std::ios::binary);
  14065. const std::string content(100, 'A');
  14066. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  14067. }
  14068. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  14069. auto body = make_file_body(path);
  14070. ASSERT_EQ(100u, body.first);
  14071. ASSERT_TRUE(static_cast<bool>(body.second));
  14072. // Rewritten shorter after its length was measured - and, on a server, after
  14073. // that length has already gone out as Content-Length.
  14074. {
  14075. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  14076. const std::string content(10, 'A');
  14077. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  14078. }
  14079. std::string written;
  14080. DataSink sink;
  14081. sink.write = [&](const char *d, size_t l) {
  14082. written.append(d, l);
  14083. return true;
  14084. };
  14085. // The provider has to report failure. write_content_with_progress() advances
  14086. // its offset only by what was written, so a provider that returns true
  14087. // without completing the length it promised is called again straight away,
  14088. // and again.
  14089. EXPECT_FALSE(body.second(0, body.first, sink));
  14090. EXPECT_EQ(std::string(10, 'A'), written);
  14091. }
  14092. TEST(MakeFileBodyTest, WholeFileIsSent) {
  14093. const std::string path = "./httplib_test_make_file_body_whole.bin";
  14094. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  14095. {
  14096. std::ofstream ofs(path, std::ios::binary);
  14097. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  14098. }
  14099. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  14100. auto body = make_file_body(path);
  14101. ASSERT_EQ(content.size(), body.first);
  14102. ASSERT_TRUE(static_cast<bool>(body.second));
  14103. std::string written;
  14104. DataSink sink;
  14105. sink.write = [&](const char *d, size_t l) {
  14106. written.append(d, l);
  14107. return true;
  14108. };
  14109. EXPECT_TRUE(body.second(0, body.first, sink));
  14110. EXPECT_EQ(content, written);
  14111. }
  14112. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  14113. static constexpr unsigned int number_of_tasks{1000000};
  14114. std::atomic_uint count{0};
  14115. std::unique_ptr<TaskQueue> task_queue{
  14116. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  14117. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  14118. auto queued = task_queue->enqueue(
  14119. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  14120. EXPECT_TRUE(queued);
  14121. }
  14122. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14123. task_queue->shutdown();
  14124. #else
  14125. EXPECT_NO_THROW(task_queue->shutdown());
  14126. #endif
  14127. EXPECT_EQ(number_of_tasks, count.load());
  14128. }
  14129. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  14130. static constexpr unsigned int number_of_tasks{1000000};
  14131. static constexpr unsigned int qlimit{2};
  14132. unsigned int queued_count{0};
  14133. std::atomic_uint count{0};
  14134. std::unique_ptr<TaskQueue> task_queue{
  14135. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  14136. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  14137. if (task_queue->enqueue(
  14138. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  14139. queued_count++;
  14140. }
  14141. }
  14142. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14143. task_queue->shutdown();
  14144. #else
  14145. EXPECT_NO_THROW(task_queue->shutdown());
  14146. #endif
  14147. EXPECT_EQ(queued_count, count.load());
  14148. EXPECT_TRUE(queued_count <= number_of_tasks);
  14149. EXPECT_TRUE(queued_count >= qlimit);
  14150. }
  14151. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  14152. // Use a short idle timeout so a dynamic thread spawns, times out and
  14153. // exits during the test, and the pool keeps working afterwards.
  14154. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  14155. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  14156. /*idle_timeout_sec=*/1}};
  14157. std::atomic_uint count{0};
  14158. std::condition_variable cv;
  14159. std::mutex mtx;
  14160. bool release = false;
  14161. // Block the base thread so the second task spawns a dynamic thread.
  14162. EXPECT_TRUE(task_queue->enqueue([&] {
  14163. std::unique_lock<std::mutex> lock(mtx);
  14164. while (!release) {
  14165. cv.wait(lock);
  14166. }
  14167. count++;
  14168. }));
  14169. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  14170. // Let the dynamic thread finish its task and exceed the idle timeout.
  14171. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  14172. {
  14173. std::unique_lock<std::mutex> lock(mtx);
  14174. release = true;
  14175. }
  14176. cv.notify_all();
  14177. // The pool must still accept and run tasks after the dynamic thread exited.
  14178. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  14179. task_queue->shutdown();
  14180. EXPECT_EQ(3u, count.load());
  14181. }
  14182. TEST(TaskQueueTest, MaxQueuedRequests) {
  14183. static constexpr unsigned int qlimit{3};
  14184. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  14185. std::condition_variable sem_cv;
  14186. std::mutex sem_mtx;
  14187. int credits = 0;
  14188. bool queued;
  14189. /* Fill up the queue with tasks that will block until we give them credits to
  14190. * complete. */
  14191. for (unsigned int n = 0; n <= qlimit;) {
  14192. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  14193. std::unique_lock<std::mutex> lock(sem_mtx);
  14194. while (credits <= 0) {
  14195. sem_cv.wait(lock);
  14196. }
  14197. /* Consume the credit and signal the test code if they are all gone. */
  14198. if (--credits == 0) { sem_cv.notify_one(); }
  14199. });
  14200. if (n < qlimit) {
  14201. /* The first qlimit enqueues must succeed. */
  14202. EXPECT_TRUE(queued);
  14203. } else {
  14204. /* The last one will succeed only when the worker thread
  14205. * starts and dequeues the first blocking task. Although
  14206. * not necessary for the correctness of this test, we sleep for
  14207. * a short while to avoid busy waiting. */
  14208. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  14209. }
  14210. if (queued) { n++; }
  14211. }
  14212. /* Further enqueues must fail since the queue is full. */
  14213. for (auto i = 0; i < 4; i++) {
  14214. queued = task_queue->enqueue([] {});
  14215. EXPECT_FALSE(queued);
  14216. }
  14217. /* Give the credits to allow the previous tasks to complete. */
  14218. {
  14219. std::unique_lock<std::mutex> lock(sem_mtx);
  14220. credits += qlimit + 1;
  14221. }
  14222. sem_cv.notify_all();
  14223. /* Wait for all the credits to be consumed. */
  14224. {
  14225. std::unique_lock<std::mutex> lock(sem_mtx);
  14226. while (credits > 0) {
  14227. sem_cv.wait(lock);
  14228. }
  14229. }
  14230. /* Check that we are able again to enqueue at least qlimit tasks. */
  14231. for (unsigned int i = 0; i < qlimit; i++) {
  14232. queued = task_queue->enqueue([] {});
  14233. EXPECT_TRUE(queued);
  14234. }
  14235. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14236. task_queue->shutdown();
  14237. #else
  14238. EXPECT_NO_THROW(task_queue->shutdown());
  14239. #endif
  14240. }
  14241. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  14242. Server svr;
  14243. svr.Get("/", [](const Request & /*req*/, Response &res) {
  14244. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  14245. });
  14246. svr.Get("/hello", [](const Request &req, Response &res) {
  14247. res.set_content(req.get_param_value("key"), "text/plain");
  14248. });
  14249. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14250. auto se = detail::scope_exit([&] {
  14251. svr.stop();
  14252. thread.join();
  14253. ASSERT_FALSE(svr.is_running());
  14254. });
  14255. svr.wait_until_ready();
  14256. {
  14257. Client cli(HOST, PORT);
  14258. cli.set_follow_location(true);
  14259. auto res = cli.Get("/");
  14260. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14261. EXPECT_EQ(StatusCode::OK_200, res->status);
  14262. EXPECT_EQ("val&key2=val2", res->body);
  14263. }
  14264. }
  14265. #endif
  14266. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  14267. Server svr;
  14268. svr.Get("/", [](const Request & /*req*/, Response &res) {
  14269. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  14270. });
  14271. svr.Get("/hello", [](const Request &req, Response &res) {
  14272. res.set_content(req.get_param_value("key"), "text/plain");
  14273. });
  14274. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14275. auto se = detail::scope_exit([&] {
  14276. svr.stop();
  14277. thread.join();
  14278. ASSERT_FALSE(svr.is_running());
  14279. });
  14280. svr.wait_until_ready();
  14281. {
  14282. Client cli(HOST, PORT);
  14283. cli.set_follow_location(true);
  14284. auto res = cli.Get("/");
  14285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14286. EXPECT_EQ(StatusCode::OK_200, res->status);
  14287. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  14288. }
  14289. }
  14290. TEST(RedirectTest, RedirectWithPlusInPath) {
  14291. Server svr;
  14292. svr.Get("/", [](const Request & /*req*/, Response &res) {
  14293. res.set_redirect("/a+b");
  14294. });
  14295. // Route pattern uses regex; escape + as \\+
  14296. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  14297. res.set_content(req.path, "text/plain");
  14298. });
  14299. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14300. auto se = detail::scope_exit([&] {
  14301. svr.stop();
  14302. thread.join();
  14303. ASSERT_FALSE(svr.is_running());
  14304. });
  14305. svr.wait_until_ready();
  14306. {
  14307. Client cli(HOST, PORT);
  14308. cli.set_follow_location(true);
  14309. auto res = cli.Get("/");
  14310. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14311. EXPECT_EQ(StatusCode::OK_200, res->status);
  14312. EXPECT_EQ("/a+b", res->body);
  14313. }
  14314. }
  14315. #ifdef CPPHTTPLIB_SSL_ENABLED
  14316. TEST(RedirectTest, Issue2185_Online) {
  14317. SSLClient client("github.com");
  14318. client.set_follow_location(true);
  14319. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  14320. "Coollab-Windows.zip");
  14321. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14322. EXPECT_EQ(StatusCode::OK_200, res->status);
  14323. EXPECT_EQ(9920427U, res->body.size());
  14324. }
  14325. #endif
  14326. TEST(VulnerabilityTest, CRLFInjection) {
  14327. Server svr;
  14328. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  14329. res.set_content("Hello 1", "text/plain");
  14330. });
  14331. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  14332. res.set_content("Hello 2", "text/plain");
  14333. });
  14334. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  14335. res.set_content("Hello 3", "text/plain");
  14336. });
  14337. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  14338. res.set_content("Hello 4", "text/plain");
  14339. });
  14340. svr.set_logger([](const Request &req, const Response & /*res*/) {
  14341. for (const auto &x : req.headers) {
  14342. auto key = x.first;
  14343. EXPECT_STRNE("evil", key.c_str());
  14344. }
  14345. });
  14346. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14347. auto se = detail::scope_exit([&] {
  14348. svr.stop();
  14349. thread.join();
  14350. ASSERT_FALSE(svr.is_running());
  14351. });
  14352. svr.wait_until_ready();
  14353. {
  14354. Client cli(HOST, PORT);
  14355. cli.Post("/test1", "A=B",
  14356. "application/x-www-form-urlencoded\r\nevil: hello1");
  14357. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  14358. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  14359. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  14360. }
  14361. }
  14362. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  14363. auto server_thread = std::thread([] {
  14364. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  14365. default_socket_options(srv);
  14366. sockaddr_in addr{};
  14367. addr.sin_family = AF_INET;
  14368. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  14369. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  14370. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  14371. ::listen(srv, 1);
  14372. sockaddr_in cli_addr{};
  14373. socklen_t cli_len = sizeof(cli_addr);
  14374. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  14375. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  14376. std::string buf_all;
  14377. char buf[2048];
  14378. ssize_t n;
  14379. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  14380. buf_all.append(buf, static_cast<size_t>(n));
  14381. size_t pos;
  14382. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  14383. auto request_block = buf_all.substr(0, pos + 4); // include separator
  14384. auto e = request_block.find("\r\n");
  14385. if (e != std::string::npos) {
  14386. auto request_line = request_block.substr(0, e);
  14387. std::string msg =
  14388. "CRLF injection detected in request line: '" + request_line + "'";
  14389. EXPECT_FALSE(true) << msg;
  14390. }
  14391. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  14392. ::send(cli,
  14393. #ifdef _WIN32
  14394. static_cast<const char *>(resp.c_str()),
  14395. static_cast<int>(resp.size()),
  14396. #else
  14397. resp.c_str(), resp.size(),
  14398. #endif
  14399. 0);
  14400. buf_all.erase(0, pos + 4);
  14401. }
  14402. }
  14403. detail::close_socket(cli);
  14404. detail::close_socket(srv);
  14405. });
  14406. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  14407. auto cli = Client("127.0.0.1", PORT + 1);
  14408. auto headers = Headers{
  14409. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  14410. {"Connection", "keep-alive"}};
  14411. auto res = cli.Get("/hi", headers);
  14412. EXPECT_FALSE(res);
  14413. EXPECT_EQ(Error::InvalidHeaders, res.error());
  14414. server_thread.join();
  14415. }
  14416. TEST(PathParamsTest, StaticMatch) {
  14417. const auto pattern = "/users/all";
  14418. detail::PathParamsMatcher matcher(pattern);
  14419. Request request;
  14420. request.path = "/users/all";
  14421. ASSERT_TRUE(matcher.match(request));
  14422. std::unordered_map<std::string, std::string> expected_params = {};
  14423. EXPECT_EQ(request.path_params, expected_params);
  14424. }
  14425. TEST(PathParamsTest, StaticMismatch) {
  14426. const auto pattern = "/users/all";
  14427. detail::PathParamsMatcher matcher(pattern);
  14428. Request request;
  14429. request.path = "/users/1";
  14430. ASSERT_FALSE(matcher.match(request));
  14431. }
  14432. TEST(PathParamsTest, SingleParamInTheMiddle) {
  14433. const auto pattern = "/users/:id/subscriptions";
  14434. detail::PathParamsMatcher matcher(pattern);
  14435. Request request;
  14436. request.path = "/users/42/subscriptions";
  14437. ASSERT_TRUE(matcher.match(request));
  14438. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  14439. EXPECT_EQ(request.path_params, expected_params);
  14440. }
  14441. TEST(PathParamsTest, SingleParamInTheEnd) {
  14442. const auto pattern = "/users/:id";
  14443. detail::PathParamsMatcher matcher(pattern);
  14444. Request request;
  14445. request.path = "/users/24";
  14446. ASSERT_TRUE(matcher.match(request));
  14447. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  14448. EXPECT_EQ(request.path_params, expected_params);
  14449. }
  14450. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  14451. const auto pattern = "/users/:id/";
  14452. detail::PathParamsMatcher matcher(pattern);
  14453. Request request;
  14454. request.path = "/users/42/";
  14455. ASSERT_TRUE(matcher.match(request));
  14456. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  14457. EXPECT_EQ(request.path_params, expected_params);
  14458. }
  14459. TEST(PathParamsTest, EmptyParam) {
  14460. const auto pattern = "/users/:id/";
  14461. detail::PathParamsMatcher matcher(pattern);
  14462. Request request;
  14463. request.path = "/users//";
  14464. ASSERT_TRUE(matcher.match(request));
  14465. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  14466. EXPECT_EQ(request.path_params, expected_params);
  14467. }
  14468. TEST(PathParamsTest, FragmentMismatch) {
  14469. const auto pattern = "/users/:id/";
  14470. detail::PathParamsMatcher matcher(pattern);
  14471. Request request;
  14472. request.path = "/admins/24/";
  14473. ASSERT_FALSE(matcher.match(request));
  14474. }
  14475. TEST(PathParamsTest, ExtraFragments) {
  14476. const auto pattern = "/users/:id";
  14477. detail::PathParamsMatcher matcher(pattern);
  14478. Request request;
  14479. request.path = "/users/42/subscriptions";
  14480. ASSERT_FALSE(matcher.match(request));
  14481. }
  14482. TEST(PathParamsTest, MissingTrailingParam) {
  14483. const auto pattern = "/users/:id";
  14484. detail::PathParamsMatcher matcher(pattern);
  14485. Request request;
  14486. request.path = "/users";
  14487. ASSERT_FALSE(matcher.match(request));
  14488. }
  14489. TEST(PathParamsTest, MissingParamInTheMiddle) {
  14490. const auto pattern = "/users/:id/subscriptions";
  14491. detail::PathParamsMatcher matcher(pattern);
  14492. Request request;
  14493. request.path = "/users/subscriptions";
  14494. ASSERT_FALSE(matcher.match(request));
  14495. }
  14496. TEST(PathParamsTest, MultipleParams) {
  14497. const auto pattern = "/users/:userid/subscriptions/:subid";
  14498. detail::PathParamsMatcher matcher(pattern);
  14499. Request request;
  14500. request.path = "/users/42/subscriptions/2";
  14501. ASSERT_TRUE(matcher.match(request));
  14502. std::unordered_map<std::string, std::string> expected_params = {
  14503. {"userid", "42"}, {"subid", "2"}};
  14504. EXPECT_EQ(request.path_params, expected_params);
  14505. }
  14506. TEST(PathParamsTest, SequenceOfParams) {
  14507. const auto pattern = "/values/:x/:y/:z";
  14508. detail::PathParamsMatcher matcher(pattern);
  14509. Request request;
  14510. request.path = "/values/1/2/3";
  14511. ASSERT_TRUE(matcher.match(request));
  14512. std::unordered_map<std::string, std::string> expected_params = {
  14513. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  14514. EXPECT_EQ(request.path_params, expected_params);
  14515. }
  14516. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  14517. const auto pattern = "/prefix:suffix";
  14518. detail::PathParamsMatcher matcher(pattern);
  14519. Request request;
  14520. request.path = "/prefix:suffix";
  14521. ASSERT_TRUE(matcher.match(request));
  14522. const std::unordered_map<std::string, std::string> expected_params = {};
  14523. EXPECT_EQ(request.path_params, expected_params);
  14524. }
  14525. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  14526. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  14527. // calling thread's stack on a long enough path for a quantified pattern;
  14528. // RegexMatcher must refuse to run regex matching on paths beyond
  14529. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  14530. detail::RegexMatcher matcher("/files/(.*)");
  14531. Request within_limit;
  14532. within_limit.path = "/files/" + std::string(10, 'A');
  14533. EXPECT_TRUE(matcher.match(within_limit));
  14534. Request over_limit;
  14535. over_limit.path =
  14536. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  14537. EXPECT_FALSE(matcher.match(over_limit));
  14538. }
  14539. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  14540. Server svr;
  14541. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  14542. res.set_content("ok", "text/plain");
  14543. });
  14544. auto port = svr.bind_to_any_port(HOST);
  14545. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  14546. auto se = detail::scope_exit([&] {
  14547. svr.stop();
  14548. thread.join();
  14549. ASSERT_FALSE(svr.is_running());
  14550. });
  14551. svr.wait_until_ready();
  14552. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  14553. // request URI limit; this used to be able to crash the process.
  14554. std::string path =
  14555. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  14556. std::string req = "GET " + path +
  14557. " HTTP/1.1\r\n"
  14558. "Host: " +
  14559. std::string(HOST) + ":" + std::to_string(port) +
  14560. "\r\n"
  14561. "Connection: close\r\n"
  14562. "\r\n";
  14563. std::string response;
  14564. ASSERT_TRUE(send_request(5, req, &response, port));
  14565. EXPECT_NE(std::string::npos, response.find("404"));
  14566. }
  14567. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  14568. Server svr;
  14569. auto handler = [](const Request & /*req*/, Response &res) {
  14570. res.set_content("hit", "text/plain");
  14571. };
  14572. // No regex metacharacter, so this one is compared literally
  14573. svr.Get("/literal/route", handler);
  14574. // '.' is a regex metacharacter, so this one must keep regex semantics
  14575. svr.Get("/a.c", handler);
  14576. auto port = svr.bind_to_any_port(HOST);
  14577. std::thread t([&]() { svr.listen_after_bind(); });
  14578. auto se = detail::scope_exit([&] {
  14579. svr.stop();
  14580. t.join();
  14581. ASSERT_FALSE(svr.is_running());
  14582. });
  14583. svr.wait_until_ready();
  14584. Client cli(HOST, port);
  14585. struct {
  14586. const char *path;
  14587. int status;
  14588. } cases[] = {
  14589. {"/literal/route", StatusCode::OK_200},
  14590. {"/literal/routes", StatusCode::NotFound_404},
  14591. {"/literal/rout", StatusCode::NotFound_404},
  14592. {"/abc", StatusCode::OK_200},
  14593. {"/a.c", StatusCode::OK_200},
  14594. };
  14595. for (const auto &x : cases) {
  14596. auto res = cli.Get(x.path);
  14597. ASSERT_TRUE(res) << x.path;
  14598. EXPECT_EQ(x.status, res->status) << x.path;
  14599. }
  14600. }
  14601. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  14602. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  14603. // from exhausting the stack, so it must only constrain routes that actually
  14604. // run a regular expression. A literal route is matched by comparison and
  14605. // stays usable at any length.
  14606. Server svr;
  14607. const std::string pattern =
  14608. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  14609. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  14610. res.set_content("hit", "text/plain");
  14611. });
  14612. auto port = svr.bind_to_any_port(HOST);
  14613. std::thread t([&]() { svr.listen_after_bind(); });
  14614. auto se = detail::scope_exit([&] {
  14615. svr.stop();
  14616. t.join();
  14617. ASSERT_FALSE(svr.is_running());
  14618. });
  14619. svr.wait_until_ready();
  14620. Client cli(HOST, port);
  14621. auto res = cli.Get(pattern);
  14622. ASSERT_TRUE(res);
  14623. EXPECT_EQ(StatusCode::OK_200, res->status);
  14624. }
  14625. TEST(ParseUrlTest, VariousPatterns) {
  14626. {
  14627. detail::UrlComponents uc;
  14628. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  14629. EXPECT_EQ("http", uc.scheme);
  14630. EXPECT_EQ("example.com", uc.host);
  14631. EXPECT_EQ("8080", uc.port);
  14632. EXPECT_EQ("/path", uc.path);
  14633. EXPECT_EQ("?q=1", uc.query);
  14634. }
  14635. {
  14636. detail::UrlComponents uc;
  14637. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  14638. EXPECT_EQ("https", uc.scheme);
  14639. EXPECT_EQ("example.com", uc.host);
  14640. EXPECT_TRUE(uc.port.empty());
  14641. EXPECT_EQ("/path", uc.path);
  14642. }
  14643. {
  14644. detail::UrlComponents uc;
  14645. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  14646. EXPECT_EQ("::1", uc.host);
  14647. EXPECT_EQ("8080", uc.port);
  14648. EXPECT_EQ("/path", uc.path);
  14649. }
  14650. {
  14651. detail::UrlComponents uc;
  14652. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  14653. }
  14654. {
  14655. // Bytes after the IPv6 literal must be a delimiter, not folded into
  14656. // the path while the connection still targets the bracketed host.
  14657. detail::UrlComponents uc;
  14658. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  14659. }
  14660. {
  14661. detail::UrlComponents uc;
  14662. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  14663. }
  14664. {
  14665. detail::UrlComponents uc;
  14666. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  14667. EXPECT_EQ("::1", uc.host);
  14668. EXPECT_TRUE(uc.port.empty());
  14669. EXPECT_EQ("/path", uc.path);
  14670. }
  14671. {
  14672. detail::UrlComponents uc;
  14673. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  14674. EXPECT_TRUE(uc.scheme.empty());
  14675. EXPECT_EQ("example.com", uc.host);
  14676. EXPECT_EQ("/path", uc.path);
  14677. EXPECT_EQ("?q=1", uc.query);
  14678. }
  14679. {
  14680. detail::UrlComponents uc;
  14681. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  14682. EXPECT_TRUE(uc.host.empty());
  14683. EXPECT_EQ("/path", uc.path);
  14684. EXPECT_EQ("?q=1", uc.query);
  14685. }
  14686. {
  14687. detail::UrlComponents uc;
  14688. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  14689. EXPECT_EQ("example.com", uc.host);
  14690. EXPECT_EQ("8080", uc.port);
  14691. }
  14692. {
  14693. // Unix socket path — must not be parsed as host
  14694. detail::UrlComponents uc;
  14695. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  14696. EXPECT_TRUE(uc.host.empty());
  14697. }
  14698. {
  14699. detail::UrlComponents uc;
  14700. ASSERT_TRUE(detail::parse_url("", uc));
  14701. EXPECT_TRUE(uc.host.empty());
  14702. EXPECT_TRUE(uc.path.empty());
  14703. }
  14704. {
  14705. detail::UrlComponents uc;
  14706. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  14707. }
  14708. {
  14709. detail::UrlComponents uc;
  14710. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  14711. }
  14712. {
  14713. // Accepted by parse_url; callers restrict to http/https
  14714. detail::UrlComponents uc;
  14715. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  14716. EXPECT_EQ("ftp", uc.scheme);
  14717. }
  14718. {
  14719. detail::UrlComponents uc;
  14720. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  14721. }
  14722. {
  14723. detail::UrlComponents uc;
  14724. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  14725. }
  14726. }
  14727. TEST(ParseUrlTest, FragmentHandling) {
  14728. {
  14729. detail::UrlComponents uc;
  14730. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  14731. EXPECT_EQ("/path", uc.path);
  14732. EXPECT_TRUE(uc.query.empty());
  14733. }
  14734. {
  14735. detail::UrlComponents uc;
  14736. ASSERT_TRUE(detail::parse_url("#frag", uc));
  14737. EXPECT_TRUE(uc.path.empty());
  14738. EXPECT_TRUE(uc.query.empty());
  14739. }
  14740. }
  14741. TEST(ParseUrlTest, UserinfoHandling) {
  14742. // Userinfo with @ but no colon — host includes @
  14743. detail::UrlComponents uc;
  14744. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  14745. EXPECT_EQ("user@host.com", uc.host);
  14746. EXPECT_EQ("/path", uc.path);
  14747. }
  14748. TEST(ParseUrlTest, IPv6EdgeCases) {
  14749. {
  14750. detail::UrlComponents uc;
  14751. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  14752. EXPECT_TRUE(uc.scheme.empty());
  14753. EXPECT_EQ("::1", uc.host);
  14754. EXPECT_EQ("8080", uc.port);
  14755. }
  14756. {
  14757. // Zone ID '%25' is not in [a-fA-F0-9:]
  14758. detail::UrlComponents uc;
  14759. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  14760. }
  14761. }
  14762. TEST(ParseUrlTest, SchemeEdgeCases) {
  14763. {
  14764. detail::UrlComponents uc;
  14765. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  14766. }
  14767. {
  14768. detail::UrlComponents uc;
  14769. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  14770. }
  14771. {
  14772. detail::UrlComponents uc;
  14773. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  14774. }
  14775. }
  14776. TEST(ParseUrlTest, PortEdgeCases) {
  14777. {
  14778. detail::UrlComponents uc;
  14779. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  14780. EXPECT_TRUE(uc.port.empty());
  14781. EXPECT_EQ("/path", uc.path);
  14782. }
  14783. {
  14784. // parse_url accepts any port string; validation is done by parse_port
  14785. detail::UrlComponents uc;
  14786. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  14787. EXPECT_EQ("abc", uc.port);
  14788. }
  14789. }
  14790. TEST(ParseUrlTest, WebSocketPatterns) {
  14791. {
  14792. detail::UrlComponents uc;
  14793. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  14794. EXPECT_EQ("ws", uc.scheme);
  14795. EXPECT_EQ("echo.example.com", uc.host);
  14796. EXPECT_EQ("8080", uc.port);
  14797. EXPECT_EQ("/ws", uc.path);
  14798. }
  14799. {
  14800. detail::UrlComponents uc;
  14801. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  14802. EXPECT_EQ("wss", uc.scheme);
  14803. EXPECT_EQ("echo.example.com", uc.host);
  14804. EXPECT_TRUE(uc.port.empty());
  14805. EXPECT_EQ("/ws", uc.path);
  14806. }
  14807. }
  14808. TEST(ParseUrlTest, QueryOnly) {
  14809. detail::UrlComponents uc;
  14810. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  14811. EXPECT_TRUE(uc.host.empty());
  14812. EXPECT_TRUE(uc.path.empty());
  14813. EXPECT_EQ("?q=1&r=2", uc.query);
  14814. }
  14815. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  14816. detail::UrlComponents uc;
  14817. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  14818. EXPECT_TRUE(uc.scheme.empty());
  14819. EXPECT_EQ("example.com", uc.host);
  14820. EXPECT_EQ("443", uc.port);
  14821. EXPECT_EQ("/path", uc.path);
  14822. }
  14823. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  14824. // If ipv6 regex working, regex match codepath is taken.
  14825. // else port will default to 80 in Client impl
  14826. int clientImplMagicPort = 80;
  14827. int port = 4321;
  14828. // above ports must be different to avoid false negative
  14829. EXPECT_NE(clientImplMagicPort, port);
  14830. std::string ipV6TestURL = "http://[ff06::c3]";
  14831. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  14832. CLIENT_PRIVATE_KEY_FILE);
  14833. EXPECT_EQ(cli.port(), port);
  14834. }
  14835. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  14836. auto file_path = "./www/dir/index.html";
  14837. auto dir_path = "./www/dir";
  14838. detail::FileStat stat_file(file_path);
  14839. EXPECT_TRUE(stat_file.is_file());
  14840. EXPECT_FALSE(stat_file.is_dir());
  14841. detail::FileStat stat_dir(dir_path);
  14842. EXPECT_FALSE(stat_dir.is_file());
  14843. EXPECT_TRUE(stat_dir.is_dir());
  14844. }
  14845. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  14846. // IPv4 with default HTTP port (80)
  14847. EXPECT_EQ("example.com",
  14848. detail::make_host_and_port_string("example.com", 80, false));
  14849. // IPv4 with default HTTPS port (443)
  14850. EXPECT_EQ("example.com",
  14851. detail::make_host_and_port_string("example.com", 443, true));
  14852. // IPv4 with non-default HTTP port
  14853. EXPECT_EQ("example.com:8080",
  14854. detail::make_host_and_port_string("example.com", 8080, false));
  14855. // IPv4 with non-default HTTPS port
  14856. EXPECT_EQ("example.com:8443",
  14857. detail::make_host_and_port_string("example.com", 8443, true));
  14858. // IPv6 with default HTTP port (80)
  14859. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  14860. // IPv6 with default HTTPS port (443)
  14861. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  14862. // IPv6 with non-default HTTP port
  14863. EXPECT_EQ("[::1]:8080",
  14864. detail::make_host_and_port_string("::1", 8080, false));
  14865. // IPv6 with non-default HTTPS port
  14866. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  14867. // IPv6 full address with default port
  14868. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  14869. detail::make_host_and_port_string(
  14870. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  14871. // IPv6 full address with non-default port
  14872. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  14873. detail::make_host_and_port_string(
  14874. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  14875. // IPv6 localhost with non-default port
  14876. EXPECT_EQ("[::1]:3000",
  14877. detail::make_host_and_port_string("::1", 3000, false));
  14878. // IPv6 with zone ID (link-local address) with default port
  14879. EXPECT_EQ("[fe80::1%eth0]",
  14880. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  14881. // IPv6 with zone ID (link-local address) with non-default port
  14882. EXPECT_EQ("[fe80::1%eth0]:8080",
  14883. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  14884. // Edge case: Port 443 with is_ssl=false (should add port)
  14885. EXPECT_EQ("example.com:443",
  14886. detail::make_host_and_port_string("example.com", 443, false));
  14887. // Edge case: Port 80 with is_ssl=true (should add port)
  14888. EXPECT_EQ("example.com:80",
  14889. detail::make_host_and_port_string("example.com", 80, true));
  14890. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  14891. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  14892. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  14893. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  14894. // Security fix: Already bracketed IPv6 should not get double brackets
  14895. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  14896. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  14897. EXPECT_EQ("[::1]:8080",
  14898. detail::make_host_and_port_string("[::1]", 8080, false));
  14899. EXPECT_EQ("[2001:db8::1]:8080",
  14900. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  14901. EXPECT_EQ("[fe80::1%eth0]",
  14902. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  14903. EXPECT_EQ("[fe80::1%eth0]:8080",
  14904. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  14905. // Edge case: Empty host (should return as-is)
  14906. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  14907. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  14908. // This is a known limitation but shouldn't crash
  14909. EXPECT_EQ("[host:name]",
  14910. detail::make_host_and_port_string("host:name", 80, false));
  14911. // Port number edge cases (no validation, but should not crash)
  14912. EXPECT_EQ("example.com:0",
  14913. detail::make_host_and_port_string("example.com", 0, false));
  14914. EXPECT_EQ("example.com:-1",
  14915. detail::make_host_and_port_string("example.com", -1, false));
  14916. EXPECT_EQ("example.com:65535",
  14917. detail::make_host_and_port_string("example.com", 65535, false));
  14918. EXPECT_EQ("example.com:65536",
  14919. detail::make_host_and_port_string("example.com", 65536, false));
  14920. }
  14921. #ifdef CPPHTTPLIB_SSL_ENABLED
  14922. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  14923. httplib::SSLClient cli("roblox.com", 443);
  14924. cli.set_follow_location(true);
  14925. auto res = cli.Get("/");
  14926. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14927. EXPECT_EQ(StatusCode::OK_200, res->status);
  14928. }
  14929. #endif
  14930. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  14931. Server svr;
  14932. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  14933. EXPECT_EQ(res.status, 400);
  14934. });
  14935. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14936. auto se = detail::scope_exit([&] {
  14937. svr.stop();
  14938. thread.join();
  14939. ASSERT_FALSE(svr.is_running());
  14940. });
  14941. svr.wait_until_ready();
  14942. Client cli(HOST, PORT);
  14943. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  14944. }
  14945. TEST(InvalidHeaderCharsTest, is_field_name) {
  14946. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  14947. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  14948. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  14949. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  14950. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  14951. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  14952. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  14953. EXPECT_FALSE(detail::fields::is_field_name(""));
  14954. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  14955. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  14956. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  14957. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  14958. }
  14959. TEST(InvalidHeaderCharsTest, is_field_value) {
  14960. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  14961. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  14962. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  14963. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  14964. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  14965. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  14966. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  14967. EXPECT_TRUE(detail::fields::is_field_value(""));
  14968. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  14969. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  14970. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  14971. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  14972. EXPECT_TRUE(detail::fields::is_field_value("0"));
  14973. }
  14974. TEST(InvalidHeaderCharsTest, OnServer) {
  14975. Server svr;
  14976. svr.Get("/test_name", [&](const Request &req, Response &res) {
  14977. std::string header = "Not Set";
  14978. if (req.has_param("header")) { header = req.get_param_value("header"); }
  14979. res.set_header(header, "value");
  14980. res.set_content("Page Content Page Content", "text/plain");
  14981. });
  14982. svr.Get("/test_value", [&](const Request &req, Response &res) {
  14983. std::string header = "Not Set";
  14984. if (req.has_param("header")) { header = req.get_param_value("header"); }
  14985. res.set_header("X-Test", header);
  14986. res.set_content("Page Content Page Content", "text/plain");
  14987. });
  14988. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14989. auto se = detail::scope_exit([&] {
  14990. svr.stop();
  14991. thread.join();
  14992. ASSERT_FALSE(svr.is_running());
  14993. });
  14994. svr.wait_until_ready();
  14995. Client cli(HOST, PORT);
  14996. {
  14997. auto res = cli.Get(
  14998. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  14999. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15000. EXPECT_EQ("Page Content Page Content", res->body);
  15001. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  15002. }
  15003. {
  15004. auto res = cli.Get(
  15005. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  15006. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15007. EXPECT_EQ("Page Content Page Content", res->body);
  15008. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  15009. }
  15010. }
  15011. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  15012. auto handled = false;
  15013. Server svr;
  15014. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  15015. thread t = thread([&] { svr.listen(HOST, PORT); });
  15016. auto se = detail::scope_exit([&] {
  15017. svr.stop();
  15018. t.join();
  15019. ASSERT_FALSE(svr.is_running());
  15020. ASSERT_FALSE(handled);
  15021. });
  15022. svr.wait_until_ready();
  15023. auto req = "POST /test HTTP/1.1\r\n"
  15024. "Content-Length: x\r\n"
  15025. "\r\n";
  15026. std::string response;
  15027. ASSERT_TRUE(send_request(1, req, &response));
  15028. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  15029. response.substr(0, response.find("\r\n")));
  15030. }
  15031. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  15032. // case-insensitive, and a server that receives a 100-continue expectation in
  15033. // an HTTP/1.0 request MUST ignore it.
  15034. static void probe_expect(int port, const std::string &req, bool *got_100) {
  15035. std::string response;
  15036. ASSERT_TRUE(send_request(1, req, &response, port));
  15037. *got_100 = response.find("100 Continue") != std::string::npos;
  15038. }
  15039. class ExpectTokenTest : public ::testing::Test {
  15040. protected:
  15041. void SetUp() override {
  15042. svr_.Post("/p", [](const Request &, Response &res) {
  15043. res.set_content("ok", "text/plain");
  15044. });
  15045. port_ = svr_.bind_to_any_port(HOST);
  15046. thread_ = thread([&]() { svr_.listen_after_bind(); });
  15047. svr_.wait_until_ready();
  15048. }
  15049. void TearDown() override {
  15050. svr_.stop();
  15051. if (thread_.joinable()) { thread_.join(); }
  15052. }
  15053. std::string request(const char *version, const char *expect_value) const {
  15054. return std::string("POST /p ") + version +
  15055. "\r\n"
  15056. "Host: localhost\r\n"
  15057. "Content-Length: 2\r\n"
  15058. "Connection: close\r\n"
  15059. "Expect: " +
  15060. expect_value +
  15061. "\r\n"
  15062. "\r\n"
  15063. "hi";
  15064. }
  15065. Server svr_;
  15066. int port_ = 0;
  15067. thread thread_;
  15068. };
  15069. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  15070. bool got_100 = false;
  15071. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  15072. EXPECT_TRUE(got_100);
  15073. }
  15074. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  15075. bool got_100 = true;
  15076. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  15077. EXPECT_FALSE(got_100);
  15078. }
  15079. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  15080. bool got_100 = false;
  15081. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  15082. EXPECT_TRUE(got_100);
  15083. }
  15084. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  15085. bool got_100 = false;
  15086. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  15087. EXPECT_TRUE(got_100);
  15088. }
  15089. #ifndef _WIN32
  15090. TEST(Expect100ContinueTest, ServerClosesConnection) {
  15091. static constexpr char reject[] = "Unauthorized";
  15092. static constexpr char accept[] = "Upload accepted";
  15093. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  15094. Server svr;
  15095. svr.set_expect_100_continue_handler(
  15096. [](const Request & /*req*/, Response &res) {
  15097. res.status = StatusCode::Unauthorized_401;
  15098. res.set_content(reject, "text/plain");
  15099. return res.status;
  15100. });
  15101. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  15102. res.set_content(accept, "text/plain");
  15103. });
  15104. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15105. auto se = detail::scope_exit([&] {
  15106. svr.stop();
  15107. thread.join();
  15108. ASSERT_FALSE(svr.is_running());
  15109. });
  15110. svr.wait_until_ready();
  15111. {
  15112. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  15113. curl_easy_init(), &curl_easy_cleanup};
  15114. ASSERT_NE(curl, nullptr);
  15115. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  15116. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  15117. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  15118. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  15119. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  15120. &curl_slist_free_all};
  15121. ASSERT_NE(list, nullptr);
  15122. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  15123. struct read_data {
  15124. size_t read_size;
  15125. size_t total_size;
  15126. } data = {0, total_size};
  15127. using read_callback_t =
  15128. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  15129. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  15130. void *userdata) -> size_t {
  15131. read_data *d = (read_data *)userdata;
  15132. if (!userdata || d->read_size >= d->total_size) { return 0; }
  15133. std::fill_n(ptr, size * nmemb, 'A');
  15134. d->read_size += size * nmemb;
  15135. return size * nmemb;
  15136. };
  15137. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  15138. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  15139. std::vector<char> buffer;
  15140. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  15141. using write_callback_t =
  15142. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  15143. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  15144. void *userdata) -> size_t {
  15145. std::vector<char> *buf = (std::vector<char> *)userdata;
  15146. buf->reserve(buf->size() + size * nmemb + 1);
  15147. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  15148. return size * nmemb;
  15149. };
  15150. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  15151. {
  15152. const auto res = curl_easy_perform(curl.get());
  15153. ASSERT_EQ(res, CURLE_OK);
  15154. }
  15155. {
  15156. auto response_code = long{};
  15157. const auto res =
  15158. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  15159. ASSERT_EQ(res, CURLE_OK);
  15160. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  15161. }
  15162. {
  15163. auto dl = curl_off_t{};
  15164. const auto res =
  15165. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  15166. ASSERT_EQ(res, CURLE_OK);
  15167. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  15168. }
  15169. {
  15170. buffer.push_back('\0');
  15171. ASSERT_STRCASEEQ(buffer.data(), reject);
  15172. }
  15173. }
  15174. }
  15175. #endif
  15176. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  15177. // Regression test for #2458.
  15178. //
  15179. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  15180. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  15181. // ticket can make the client socket spuriously readable during the
  15182. // 100-continue wait. If the readiness is mistaken for an incoming response,
  15183. // the client withholds the body and then blocks reading a response that never
  15184. // comes, failing with `Failed to read connection`.
  15185. //
  15186. // A correct client (like curl) sends the body once no `100 Continue` arrives
  15187. // within the timeout. This raw OpenSSL server deliberately never sends
  15188. // `100 Continue`; the client must still deliver the body and receive 200.
  15189. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  15190. signal(SIGPIPE, SIG_IGN);
  15191. const auto port = PORT + 4;
  15192. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15193. ASSERT_NE(srv, INVALID_SOCKET);
  15194. int opt = 1;
  15195. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  15196. sockaddr_in addr{};
  15197. addr.sin_family = AF_INET;
  15198. addr.sin_port = htons(static_cast<uint16_t>(port));
  15199. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15200. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  15201. ASSERT_EQ(0, ::listen(srv, 1));
  15202. std::atomic<size_t> server_body_bytes{0};
  15203. auto server_thread = std::thread([&] {
  15204. sockaddr_in cli_addr{};
  15205. socklen_t cli_len = sizeof(cli_addr);
  15206. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  15207. if (cli == INVALID_SOCKET) { return; }
  15208. // Bound the lifetime of the server side so a buggy client (which never
  15209. // sends the body) cannot make this thread block forever on join.
  15210. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  15211. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  15212. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  15213. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  15214. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  15215. SSL *ssl = SSL_new(ctx);
  15216. SSL_set_fd(ssl, static_cast<int>(cli));
  15217. if (SSL_accept(ssl) > 0) {
  15218. // Read the request headers. Reading here also flushes the TLS 1.3
  15219. // session tickets to the client. Deliberately do NOT send
  15220. // `100 Continue`.
  15221. std::string buf;
  15222. char tmp[1024];
  15223. while (buf.find("\r\n\r\n") == std::string::npos) {
  15224. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  15225. if (n <= 0) { break; }
  15226. buf.append(tmp, static_cast<size_t>(n));
  15227. }
  15228. // A correct client sends the body now; count what arrives.
  15229. auto pos = buf.find("\r\n\r\n");
  15230. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  15231. while (body < 4096) {
  15232. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  15233. if (n <= 0) { break; }
  15234. body += static_cast<size_t>(n);
  15235. }
  15236. server_body_bytes = body;
  15237. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  15238. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  15239. SSL_shutdown(ssl);
  15240. }
  15241. SSL_free(ssl);
  15242. detail::close_socket(cli);
  15243. SSL_CTX_free(ctx);
  15244. });
  15245. auto se = detail::scope_exit([&] {
  15246. server_thread.join();
  15247. detail::close_socket(srv);
  15248. });
  15249. SSLClient cli("127.0.0.1", port);
  15250. cli.enable_server_certificate_verification(false);
  15251. cli.set_connection_timeout(5, 0);
  15252. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  15253. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  15254. std::string body(4096, 'A');
  15255. auto res = cli.Put("/api/test", body, "application/json");
  15256. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  15257. EXPECT_EQ(StatusCode::OK_200, res->status);
  15258. EXPECT_EQ(body.size(), server_body_bytes.load());
  15259. }
  15260. #endif
  15261. template <typename S, typename C>
  15262. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  15263. svr.Get("/stream", [&](const Request &, Response &res) {
  15264. auto data = new std::string("01234567890123456789");
  15265. res.set_content_provider(
  15266. data->size(), "text/plain",
  15267. [&, data](size_t offset, size_t length, DataSink &sink) {
  15268. const size_t DATA_CHUNK_SIZE = 4;
  15269. const auto &d = *data;
  15270. std::this_thread::sleep_for(std::chrono::seconds(1));
  15271. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  15272. return true;
  15273. },
  15274. [data](bool success) {
  15275. EXPECT_FALSE(success);
  15276. delete data;
  15277. });
  15278. });
  15279. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  15280. auto i = new size_t(0);
  15281. res.set_content_provider(
  15282. "text/plain",
  15283. [i](size_t, DataSink &sink) {
  15284. if (*i < 5) {
  15285. std::this_thread::sleep_for(std::chrono::seconds(1));
  15286. sink.write("abcd", 4);
  15287. (*i)++;
  15288. } else {
  15289. sink.done();
  15290. }
  15291. return true;
  15292. },
  15293. [i](bool success) {
  15294. EXPECT_FALSE(success);
  15295. delete i;
  15296. });
  15297. });
  15298. svr.Get("/chunked", [&](const Request &, Response &res) {
  15299. auto i = new size_t(0);
  15300. res.set_chunked_content_provider(
  15301. "text/plain",
  15302. [i](size_t, DataSink &sink) {
  15303. if (*i < 5) {
  15304. std::this_thread::sleep_for(std::chrono::seconds(1));
  15305. sink.os << "abcd";
  15306. (*i)++;
  15307. } else {
  15308. sink.done();
  15309. }
  15310. return true;
  15311. },
  15312. [i](bool success) {
  15313. EXPECT_FALSE(success);
  15314. delete i;
  15315. });
  15316. });
  15317. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  15318. auto se = detail::scope_exit([&] {
  15319. svr.stop();
  15320. listen_thread.join();
  15321. ASSERT_FALSE(svr.is_running());
  15322. });
  15323. svr.wait_until_ready();
  15324. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  15325. {
  15326. auto start = std::chrono::steady_clock::now();
  15327. auto res = cli.Get("/stream");
  15328. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  15329. std::chrono::steady_clock::now() - start)
  15330. .count();
  15331. ASSERT_FALSE(res);
  15332. EXPECT_EQ(Error::Read, res.error());
  15333. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  15334. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  15335. }
  15336. {
  15337. auto start = std::chrono::steady_clock::now();
  15338. auto res = cli.Get("/stream_without_length");
  15339. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  15340. std::chrono::steady_clock::now() - start)
  15341. .count();
  15342. ASSERT_FALSE(res);
  15343. EXPECT_EQ(Error::Read, res.error());
  15344. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  15345. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  15346. }
  15347. {
  15348. auto start = std::chrono::steady_clock::now();
  15349. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  15350. EXPECT_EQ("abcd", string(data, data_length));
  15351. return true;
  15352. });
  15353. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  15354. std::chrono::steady_clock::now() - start)
  15355. .count();
  15356. ASSERT_FALSE(res);
  15357. EXPECT_EQ(Error::Read, res.error());
  15358. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  15359. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  15360. }
  15361. }
  15362. TEST(MaxTimeoutTest, ContentStream) {
  15363. time_t timeout = 2000;
  15364. time_t threshold = 200;
  15365. Server svr;
  15366. Client cli("localhost", PORT);
  15367. max_timeout_test(svr, cli, timeout, threshold);
  15368. }
  15369. #ifdef CPPHTTPLIB_SSL_ENABLED
  15370. TEST(MaxTimeoutTest, ContentStreamSSL) {
  15371. time_t timeout = 2000;
  15372. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  15373. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15374. SSLClient cli("localhost", PORT);
  15375. cli.enable_server_certificate_verification(false);
  15376. max_timeout_test(svr, cli, timeout, threshold);
  15377. }
  15378. #endif
  15379. class EventDispatcher {
  15380. public:
  15381. EventDispatcher() {}
  15382. bool wait_event(DataSink *sink) {
  15383. unique_lock<mutex> lk(m_);
  15384. int id = id_;
  15385. // Wait with timeout to prevent hanging if client disconnects
  15386. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  15387. [&] { return cid_ == id; })) {
  15388. return false; // Timeout occurred
  15389. }
  15390. sink->write(message_.data(), message_.size());
  15391. return true;
  15392. }
  15393. void send_event(const string &message) {
  15394. lock_guard<mutex> lk(m_);
  15395. cid_ = id_++;
  15396. message_ = message;
  15397. cv_.notify_all();
  15398. }
  15399. private:
  15400. mutex m_;
  15401. condition_variable cv_;
  15402. atomic_int id_{0};
  15403. atomic_int cid_{-1};
  15404. string message_;
  15405. };
  15406. TEST(ClientInThreadTest, Issue2068) {
  15407. EventDispatcher ed;
  15408. Server svr;
  15409. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  15410. res.set_chunked_content_provider("text/event-stream",
  15411. [&](size_t /*offset*/, DataSink &sink) {
  15412. return ed.wait_event(&sink);
  15413. });
  15414. });
  15415. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  15416. svr.wait_until_ready();
  15417. thread event_thread([&] {
  15418. int id = 0;
  15419. while (svr.is_running()) {
  15420. this_thread::sleep_for(chrono::milliseconds(500));
  15421. std::stringstream ss;
  15422. ss << "data: " << id << "\n\n";
  15423. ed.send_event(ss.str());
  15424. id++;
  15425. }
  15426. });
  15427. auto se = detail::scope_exit([&] {
  15428. svr.stop();
  15429. listen_thread.join();
  15430. event_thread.join();
  15431. ASSERT_FALSE(svr.is_running());
  15432. });
  15433. {
  15434. auto client = detail::make_unique<Client>(HOST, PORT);
  15435. client->set_read_timeout(std::chrono::minutes(10));
  15436. std::atomic<bool> stop{false};
  15437. std::thread t([&] {
  15438. client->Get("/event1",
  15439. [&](const char *, size_t) -> bool { return !stop; });
  15440. });
  15441. std::this_thread::sleep_for(std::chrono::seconds(2));
  15442. stop = true;
  15443. client->stop();
  15444. t.join();
  15445. // Reset client after thread has finished
  15446. client.reset();
  15447. }
  15448. }
  15449. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  15450. auto handled = false;
  15451. Server svr;
  15452. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  15453. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15454. auto se = detail::scope_exit([&] {
  15455. svr.stop();
  15456. t.join();
  15457. ASSERT_FALSE(svr.is_running());
  15458. ASSERT_FALSE(handled);
  15459. });
  15460. svr.wait_until_ready();
  15461. // Two Content-Length headers with different values — must be rejected
  15462. auto req = "POST /test HTTP/1.1\r\n"
  15463. "Content-Length: 5\r\n"
  15464. "Content-Length: 10\r\n"
  15465. "\r\n"
  15466. "hello";
  15467. std::string response;
  15468. ASSERT_TRUE(send_request(1, req, &response));
  15469. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  15470. response.substr(0, response.find("\r\n")));
  15471. }
  15472. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  15473. auto handled = false;
  15474. Server svr;
  15475. svr.Post("/test", [&](const Request &, Response &res) {
  15476. handled = true;
  15477. res.set_content("ok", "text/plain");
  15478. });
  15479. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15480. auto se = detail::scope_exit([&] {
  15481. svr.stop();
  15482. t.join();
  15483. ASSERT_FALSE(svr.is_running());
  15484. ASSERT_TRUE(handled);
  15485. });
  15486. svr.wait_until_ready();
  15487. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  15488. auto req = "POST /test HTTP/1.1\r\n"
  15489. "Content-Length: 5\r\n"
  15490. "Content-Length: 5\r\n"
  15491. "\r\n"
  15492. "hello";
  15493. std::string response;
  15494. ASSERT_TRUE(send_request(1, req, &response));
  15495. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  15496. }
  15497. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  15498. Server svr;
  15499. svr.Get("/", [](const Request &req, Response &res) {
  15500. EXPECT_EQ(2U, req.trailers.size());
  15501. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  15502. // Denied
  15503. EXPECT_FALSE(req.has_trailer("Content-Length"));
  15504. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  15505. // Accepted
  15506. EXPECT_TRUE(req.has_trailer("X-Hello"));
  15507. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  15508. EXPECT_TRUE(req.has_trailer("X-World"));
  15509. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  15510. res.set_content("ok", "text/plain");
  15511. });
  15512. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15513. auto se = detail::scope_exit([&] {
  15514. svr.stop();
  15515. t.join();
  15516. ASSERT_FALSE(svr.is_running());
  15517. });
  15518. svr.wait_until_ready();
  15519. const std::string req = "GET / HTTP/1.1\r\n"
  15520. "Transfer-Encoding: chunked\r\n"
  15521. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  15522. "\r\n"
  15523. "0\r\n"
  15524. "Content-Length: 10\r\n"
  15525. "Host: internal.local\r\n"
  15526. "Content-Type: malicious/content\r\n"
  15527. "Cookie: any\r\n"
  15528. "Set-Cookie: any\r\n"
  15529. "X-Forwarded-For: attacker.com\r\n"
  15530. "X-Real-Ip: 1.1.1.1\r\n"
  15531. "X-Hello: hello\r\n"
  15532. "X-World: world\r\n"
  15533. "\r\n";
  15534. std::string res;
  15535. ASSERT_TRUE(send_request(1, req, &res));
  15536. }
  15537. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  15538. // several field lines, and the combined value is what has to be parsed. A
  15539. // Trailer field split across lines therefore declares every name it lists;
  15540. // reading only the first line silently drops the trailers the later lines
  15541. // declare. The prohibited-trailer filter still applies to every line.
  15542. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  15543. Server svr;
  15544. size_t observed_trailer_count = 0;
  15545. std::string observed_hello;
  15546. std::string observed_world;
  15547. bool observed_content_length = true;
  15548. svr.Get("/", [&](const Request &req, Response &res) {
  15549. observed_trailer_count = req.trailers.size();
  15550. observed_hello = req.get_trailer_value("X-Hello");
  15551. observed_world = req.get_trailer_value("X-World");
  15552. observed_content_length = req.has_trailer("Content-Length");
  15553. res.set_content("ok", "text/plain");
  15554. });
  15555. auto port = svr.bind_to_any_port(HOST);
  15556. thread t = thread([&]() { svr.listen_after_bind(); });
  15557. auto se = detail::scope_exit([&] {
  15558. svr.stop();
  15559. t.join();
  15560. ASSERT_FALSE(svr.is_running());
  15561. });
  15562. svr.wait_until_ready();
  15563. const std::string req = "GET / HTTP/1.1\r\n"
  15564. "Transfer-Encoding: chunked\r\n"
  15565. "Trailer: X-Hello\r\n"
  15566. "Trailer: X-World, Content-Length\r\n"
  15567. "\r\n"
  15568. "0\r\n"
  15569. "X-Hello: hello\r\n"
  15570. "X-World: world\r\n"
  15571. "Content-Length: 10\r\n"
  15572. "\r\n";
  15573. std::string res;
  15574. ASSERT_TRUE(send_request(1, req, &res, port));
  15575. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  15576. // Accepted: both field lines contribute to the declared set
  15577. EXPECT_EQ(2U, observed_trailer_count);
  15578. EXPECT_EQ(observed_hello, "hello");
  15579. EXPECT_EQ(observed_world, "world");
  15580. // Denied: a prohibited name stays prohibited on a later field line
  15581. EXPECT_FALSE(observed_content_length);
  15582. }
  15583. // A direct client that is not listed in trusted_proxies must not be able to
  15584. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  15585. // the peer address on the actual TCP connection determines whether the
  15586. // header is honored.
  15587. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  15588. Server svr;
  15589. // Deliberately does NOT include the loopback address the test client
  15590. // actually connects from, so the direct connection is not a trusted proxy.
  15591. svr.set_trusted_proxies({"203.0.113.66"});
  15592. std::string observed_remote_addr;
  15593. svr.Get("/ip", [&](const Request &req, Response &res) {
  15594. observed_remote_addr = req.remote_addr;
  15595. res.set_content("ok", "text/plain");
  15596. });
  15597. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15598. auto se = detail::scope_exit([&] {
  15599. svr.stop();
  15600. t.join();
  15601. ASSERT_FALSE(svr.is_running());
  15602. });
  15603. svr.wait_until_ready();
  15604. Client cli(HOST, PORT);
  15605. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  15606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15607. EXPECT_EQ(StatusCode::OK_200, res->status);
  15608. // The connecting peer is not a trusted proxy, so the spoofed header must be
  15609. // ignored entirely and the real connection-level address retained.
  15610. EXPECT_TRUE(observed_remote_addr == "::1" ||
  15611. observed_remote_addr == "127.0.0.1");
  15612. }
  15613. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  15614. Server svr;
  15615. std::string observed_remote_addr;
  15616. std::string observed_xff;
  15617. svr.Get("/ip", [&](const Request &req, Response &res) {
  15618. observed_remote_addr = req.remote_addr;
  15619. observed_xff = req.get_header_value("X-Forwarded-For");
  15620. res.set_content("ok", "text/plain");
  15621. });
  15622. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15623. auto se = detail::scope_exit([&] {
  15624. svr.stop();
  15625. t.join();
  15626. ASSERT_FALSE(svr.is_running());
  15627. });
  15628. svr.wait_until_ready();
  15629. Client cli(HOST, PORT);
  15630. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  15631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15632. EXPECT_EQ(StatusCode::OK_200, res->status);
  15633. EXPECT_EQ(observed_xff, "203.0.113.66");
  15634. EXPECT_TRUE(observed_remote_addr == "::1" ||
  15635. observed_remote_addr == "127.0.0.1");
  15636. }
  15637. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  15638. Server svr;
  15639. svr.set_trusted_proxies({"203.0.113.66"});
  15640. std::string observed_remote_addr;
  15641. std::string observed_xff;
  15642. svr.Get("/ip", [&](const Request &req, Response &res) {
  15643. observed_remote_addr = req.remote_addr;
  15644. observed_xff = req.get_header_value("X-Forwarded-For");
  15645. res.set_content("ok", "text/plain");
  15646. });
  15647. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15648. auto se = detail::scope_exit([&] {
  15649. svr.stop();
  15650. t.join();
  15651. ASSERT_FALSE(svr.is_running());
  15652. });
  15653. svr.wait_until_ready();
  15654. Client cli(HOST, PORT);
  15655. auto res = cli.Get("/ip");
  15656. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15657. EXPECT_EQ(StatusCode::OK_200, res->status);
  15658. EXPECT_EQ(observed_xff, "");
  15659. EXPECT_TRUE(observed_remote_addr == "::1" ||
  15660. observed_remote_addr == "127.0.0.1");
  15661. }
  15662. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  15663. Server svr;
  15664. // Include the loopback address the test client actually connects from, so
  15665. // the direct connection itself is recognized as the trusted proxy hop.
  15666. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  15667. std::string observed_remote_addr;
  15668. std::string observed_xff;
  15669. svr.Get("/ip", [&](const Request &req, Response &res) {
  15670. observed_remote_addr = req.remote_addr;
  15671. observed_xff = req.get_header_value("X-Forwarded-For");
  15672. res.set_content("ok", "text/plain");
  15673. });
  15674. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15675. auto se = detail::scope_exit([&] {
  15676. svr.stop();
  15677. t.join();
  15678. ASSERT_FALSE(svr.is_running());
  15679. });
  15680. svr.wait_until_ready();
  15681. Client cli(HOST, PORT);
  15682. auto res = cli.Get(
  15683. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  15684. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15685. EXPECT_EQ(StatusCode::OK_200, res->status);
  15686. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  15687. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  15688. }
  15689. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  15690. Server svr;
  15691. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  15692. std::string observed_remote_addr;
  15693. std::string observed_xff;
  15694. svr.Get("/ip", [&](const Request &req, Response &res) {
  15695. observed_remote_addr = req.remote_addr;
  15696. observed_xff = req.get_header_value("X-Forwarded-For");
  15697. res.set_content("ok", "text/plain");
  15698. });
  15699. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15700. auto se = detail::scope_exit([&] {
  15701. svr.stop();
  15702. t.join();
  15703. ASSERT_FALSE(svr.is_running());
  15704. });
  15705. svr.wait_until_ready();
  15706. Client cli(HOST, PORT);
  15707. auto res = cli.Get(
  15708. "/ip",
  15709. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  15710. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15711. EXPECT_EQ(StatusCode::OK_200, res->status);
  15712. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  15713. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  15714. }
  15715. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  15716. Server svr;
  15717. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  15718. std::string observed_remote_addr;
  15719. std::string observed_xff;
  15720. svr.Get("/ip", [&](const Request &req, Response &res) {
  15721. observed_remote_addr = req.remote_addr;
  15722. observed_xff = req.get_header_value("X-Forwarded-For");
  15723. res.set_content("ok", "text/plain");
  15724. });
  15725. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15726. auto se = detail::scope_exit([&] {
  15727. svr.stop();
  15728. t.join();
  15729. ASSERT_FALSE(svr.is_running());
  15730. });
  15731. svr.wait_until_ready();
  15732. Client cli(HOST, PORT);
  15733. auto res = cli.Get(
  15734. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  15735. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15736. EXPECT_EQ(StatusCode::OK_200, res->status);
  15737. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  15738. // by the closest hop) is used. The leftmost entry is fully client-controlled
  15739. // and must not be selected.
  15740. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  15741. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  15742. }
  15743. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  15744. Server svr;
  15745. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  15746. std::string observed_remote_addr;
  15747. svr.Get("/ip", [&](const Request &req, Response &res) {
  15748. observed_remote_addr = req.remote_addr;
  15749. res.set_content("ok", "text/plain");
  15750. });
  15751. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15752. auto se = detail::scope_exit([&] {
  15753. svr.stop();
  15754. t.join();
  15755. ASSERT_FALSE(svr.is_running());
  15756. });
  15757. svr.wait_until_ready();
  15758. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  15759. // a forged address and the trusted proxy's own address; the forged value must
  15760. // not win over the address the trusted proxy actually recorded.
  15761. Client cli(HOST, PORT);
  15762. auto res = cli.Get(
  15763. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  15764. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15765. EXPECT_EQ(StatusCode::OK_200, res->status);
  15766. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  15767. }
  15768. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  15769. Server svr;
  15770. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  15771. std::string observed_remote_addr;
  15772. std::string observed_xff;
  15773. svr.Get("/ip", [&](const Request &req, Response &res) {
  15774. observed_remote_addr = req.remote_addr;
  15775. observed_xff = req.get_header_value("X-Forwarded-For");
  15776. res.set_content("ok", "text/plain");
  15777. });
  15778. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15779. auto se = detail::scope_exit([&] {
  15780. svr.stop();
  15781. t.join();
  15782. ASSERT_FALSE(svr.is_running());
  15783. });
  15784. svr.wait_until_ready();
  15785. Client cli(HOST, PORT);
  15786. auto res = cli.Get(
  15787. "/ip",
  15788. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  15789. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15790. EXPECT_EQ(StatusCode::OK_200, res->status);
  15791. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  15792. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  15793. }
  15794. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  15795. Server svr;
  15796. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  15797. std::string observed_remote_addr;
  15798. std::string observed_xff;
  15799. svr.Get("/ip", [&](const Request &req, Response &res) {
  15800. observed_remote_addr = req.remote_addr;
  15801. observed_xff = req.get_header_value("X-Forwarded-For");
  15802. res.set_content("ok", "text/plain");
  15803. });
  15804. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15805. auto se = detail::scope_exit([&] {
  15806. svr.stop();
  15807. t.join();
  15808. ASSERT_FALSE(svr.is_running());
  15809. });
  15810. svr.wait_until_ready();
  15811. std::string raw_req =
  15812. "GET /ip HTTP/1.1\r\n"
  15813. "Host: localhost\r\n"
  15814. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  15815. "Connection: close\r\n"
  15816. "\r\n";
  15817. std::string out;
  15818. ASSERT_TRUE(send_request(5, raw_req, &out));
  15819. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  15820. // Header parser trims surrounding whitespace of the header value
  15821. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  15822. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  15823. }
  15824. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  15825. // one comma-joined value, in the order received. Proxies such as HAProxy append
  15826. // their own X-Forwarded-For as a separate field line rather than extending the
  15827. // one the client sent, so every occurrence has to be taken into account.
  15828. // Reading only the first one hands back the address the client chose.
  15829. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  15830. Server svr;
  15831. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  15832. std::string observed_remote_addr;
  15833. size_t observed_xff_count = 0;
  15834. svr.Get("/ip", [&](const Request &req, Response &res) {
  15835. observed_remote_addr = req.remote_addr;
  15836. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  15837. res.set_content("ok", "text/plain");
  15838. });
  15839. auto port = svr.bind_to_any_port(HOST);
  15840. thread t = thread([&]() { svr.listen_after_bind(); });
  15841. auto se = detail::scope_exit([&] {
  15842. svr.stop();
  15843. t.join();
  15844. ASSERT_FALSE(svr.is_running());
  15845. });
  15846. svr.wait_until_ready();
  15847. // The client supplies the first field line; the trusted proxy appends the
  15848. // address it observed as a second one.
  15849. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  15850. "Host: localhost\r\n"
  15851. "X-Forwarded-For: 1.2.3.4\r\n"
  15852. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  15853. "Connection: close\r\n"
  15854. "\r\n";
  15855. std::string out;
  15856. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  15857. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  15858. EXPECT_EQ(observed_xff_count, 2U);
  15859. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  15860. // The same chain spread over one field line per hop derives the same client
  15861. // address, i.e. the split and the comma-joined representations agree.
  15862. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  15863. "Host: localhost\r\n"
  15864. "X-Forwarded-For: 1.2.3.4\r\n"
  15865. "X-Forwarded-For: 198.51.100.23\r\n"
  15866. "X-Forwarded-For: 192.0.2.45\r\n"
  15867. "Connection: close\r\n"
  15868. "\r\n";
  15869. out.clear();
  15870. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  15871. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  15872. EXPECT_EQ(observed_xff_count, 3U);
  15873. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  15874. }
  15875. // An X-Forwarded-For header whose value parses to zero IP segments must not
  15876. // crash the server (it used to call front() on an empty vector inside
  15877. // get_client_ip). The connection-level remote address must be retained instead.
  15878. static void run_malformed_xff_test(const std::string &xff_value) {
  15879. Server svr;
  15880. svr.set_trusted_proxies({"192.0.2.45"});
  15881. std::string observed_remote_addr;
  15882. svr.Get("/ip", [&](const Request &req, Response &res) {
  15883. observed_remote_addr = req.remote_addr;
  15884. res.set_content("ok", "text/plain");
  15885. });
  15886. int port = 0;
  15887. thread t = thread([&]() {
  15888. port = svr.bind_to_any_port(HOST);
  15889. svr.listen_after_bind();
  15890. });
  15891. auto se = detail::scope_exit([&] {
  15892. svr.stop();
  15893. t.join();
  15894. ASSERT_FALSE(svr.is_running());
  15895. });
  15896. svr.wait_until_ready();
  15897. Client cli(HOST, port);
  15898. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  15899. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15900. EXPECT_EQ(StatusCode::OK_200, res->status);
  15901. EXPECT_TRUE(observed_remote_addr == "::1" ||
  15902. observed_remote_addr == "127.0.0.1");
  15903. }
  15904. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  15905. run_malformed_xff_test("");
  15906. }
  15907. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  15908. run_malformed_xff_test(",");
  15909. }
  15910. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  15911. run_malformed_xff_test(", , ,");
  15912. }
  15913. // The same rule applies to Accept: a request whose acceptable types are spread
  15914. // over several field lines must be negotiated against all of them.
  15915. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  15916. // case-insensitive connection options. Comparing the whole field value against
  15917. // one option misses a client that sends several of them, and misses every
  15918. // casing but the one written in the comparison.
  15919. //
  15920. // Sends req, reads the response, then reuses the same socket for a second
  15921. // request to find out whether the server kept the connection.
  15922. static void probe_connection_reuse(int port, const std::string &req,
  15923. bool *announced_close, bool *reusable) {
  15924. auto error = Error::Success;
  15925. auto sock = detail::create_client_socket(
  15926. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  15927. /*connection_timeout_sec=*/5, 0,
  15928. /*read_timeout_sec=*/1, 0,
  15929. /*write_timeout_sec=*/5, 0, std::string(), error);
  15930. ASSERT_NE(sock, INVALID_SOCKET);
  15931. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  15932. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  15933. "Host: localhost\r\n"
  15934. "Connection: close\r\n"
  15935. "\r\n";
  15936. std::string first_response;
  15937. std::string second_response;
  15938. detail::process_client_socket(
  15939. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  15940. [&](Stream &strm) {
  15941. if (strm.write(req.data(), req.size()) !=
  15942. static_cast<ssize_t>(req.size())) {
  15943. return false;
  15944. }
  15945. char buf[512];
  15946. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  15947. // Headers plus the two-byte body of the handler below
  15948. while (reader.getline()) {
  15949. first_response += reader.ptr();
  15950. if (first_response.find("ok") != std::string::npos) { break; }
  15951. }
  15952. if (strm.write(second.data(), second.size()) !=
  15953. static_cast<ssize_t>(second.size())) {
  15954. return true;
  15955. }
  15956. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  15957. while (reader2.getline()) {
  15958. second_response += reader2.ptr();
  15959. if (second_response.find("ok") != std::string::npos) { break; }
  15960. }
  15961. return true;
  15962. });
  15963. *announced_close =
  15964. first_response.find("Connection: close") != std::string::npos;
  15965. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  15966. }
  15967. class ConnectionTokenTest : public ::testing::Test {
  15968. protected:
  15969. void SetUp() override {
  15970. svr_.Get("/keepalive", [](const Request &, Response &res) {
  15971. res.set_content("ok", "text/plain");
  15972. });
  15973. port_ = svr_.bind_to_any_port(HOST);
  15974. thread_ = thread([&]() { svr_.listen_after_bind(); });
  15975. svr_.wait_until_ready();
  15976. }
  15977. void TearDown() override {
  15978. svr_.stop();
  15979. if (thread_.joinable()) { thread_.join(); }
  15980. }
  15981. Server svr_;
  15982. int port_ = 0;
  15983. thread thread_;
  15984. };
  15985. // "close" alongside another option still closes the connection, and the
  15986. // response says so rather than leaving the peer to discover it.
  15987. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  15988. bool announced_close = false;
  15989. bool reusable = true;
  15990. probe_connection_reuse(port_,
  15991. "GET /keepalive HTTP/1.1\r\n"
  15992. "Host: localhost\r\n"
  15993. "Connection: keep-alive, close\r\n"
  15994. "\r\n",
  15995. &announced_close, &reusable);
  15996. EXPECT_TRUE(announced_close);
  15997. EXPECT_FALSE(reusable);
  15998. }
  15999. // "close" split over two field lines is the same list, so it is honored too.
  16000. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  16001. bool announced_close = false;
  16002. bool reusable = true;
  16003. probe_connection_reuse(port_,
  16004. "GET /keepalive HTTP/1.1\r\n"
  16005. "Host: localhost\r\n"
  16006. "Connection: keep-alive\r\n"
  16007. "Connection: close\r\n"
  16008. "\r\n",
  16009. &announced_close, &reusable);
  16010. EXPECT_TRUE(announced_close);
  16011. EXPECT_FALSE(reusable);
  16012. }
  16013. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  16014. // keep-alive in the spelling everyone actually sends keeps its connection.
  16015. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  16016. bool announced_close = false;
  16017. bool reusable = false;
  16018. probe_connection_reuse(port_,
  16019. "GET /keepalive HTTP/1.0\r\n"
  16020. "Host: localhost\r\n"
  16021. "Connection: keep-alive\r\n"
  16022. "\r\n",
  16023. &announced_close, &reusable);
  16024. EXPECT_FALSE(announced_close);
  16025. EXPECT_TRUE(reusable);
  16026. }
  16027. // A token the value merely contains is not the token itself.
  16028. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  16029. bool announced_close = false;
  16030. bool reusable = false;
  16031. probe_connection_reuse(port_,
  16032. "GET /keepalive HTTP/1.1\r\n"
  16033. "Host: localhost\r\n"
  16034. "Connection: notclose\r\n"
  16035. "\r\n",
  16036. &announced_close, &reusable);
  16037. EXPECT_FALSE(announced_close);
  16038. EXPECT_TRUE(reusable);
  16039. }
  16040. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  16041. Server svr;
  16042. std::vector<std::string> observed_types;
  16043. svr.Get("/", [&](const Request &req, Response &res) {
  16044. observed_types = req.accept_content_types;
  16045. res.set_content("ok", "text/plain");
  16046. });
  16047. auto port = svr.bind_to_any_port(HOST);
  16048. thread t = thread([&]() { svr.listen_after_bind(); });
  16049. auto se = detail::scope_exit([&] {
  16050. svr.stop();
  16051. t.join();
  16052. ASSERT_FALSE(svr.is_running());
  16053. });
  16054. svr.wait_until_ready();
  16055. Client cli(HOST, port);
  16056. Headers headers;
  16057. headers.emplace("Accept", "text/plain;q=0.5");
  16058. headers.emplace("Accept", "application/json");
  16059. auto res = cli.Get("/", headers);
  16060. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16061. EXPECT_EQ(StatusCode::OK_200, res->status);
  16062. // Sorted by q-value, so the second field line's type comes first
  16063. ASSERT_EQ(2U, observed_types.size());
  16064. EXPECT_EQ("application/json", observed_types[0]);
  16065. EXPECT_EQ("text/plain", observed_types[1]);
  16066. }
  16067. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  16068. // empty field line must not contribute a bare comma to the combined value.
  16069. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  16070. Server svr;
  16071. std::vector<std::string> observed_types;
  16072. svr.Get("/", [&](const Request &req, Response &res) {
  16073. observed_types = req.accept_content_types;
  16074. res.set_content("ok", "text/plain");
  16075. });
  16076. auto port = svr.bind_to_any_port(HOST);
  16077. thread t = thread([&]() { svr.listen_after_bind(); });
  16078. auto se = detail::scope_exit([&] {
  16079. svr.stop();
  16080. t.join();
  16081. ASSERT_FALSE(svr.is_running());
  16082. });
  16083. svr.wait_until_ready();
  16084. // Empty first field line, then a real one
  16085. std::string raw_req = "GET / HTTP/1.1\r\n"
  16086. "Host: localhost\r\n"
  16087. "Accept:\r\n"
  16088. "Accept: application/json\r\n"
  16089. "Connection: close\r\n"
  16090. "\r\n";
  16091. std::string out;
  16092. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  16093. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  16094. ASSERT_EQ(1U, observed_types.size());
  16095. EXPECT_EQ("application/json", observed_types[0]);
  16096. }
  16097. // The skip in get_combined_header_value() is what keeps an empty field line
  16098. // from contributing a bare comma. Only a trailing empty field line exercises
  16099. // it: a leading one is already covered by the "combined is still empty" check,
  16100. // and parse_accept_header() now ignores the empty element either way, so the
  16101. // request-level test above can no longer tell the two apart.
  16102. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  16103. Headers headers;
  16104. headers.emplace("Accept", "text/html");
  16105. headers.emplace("Accept", "");
  16106. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  16107. headers.clear();
  16108. headers.emplace("Accept", "");
  16109. headers.emplace("Accept", "application/json");
  16110. EXPECT_EQ("application/json",
  16111. detail::get_combined_header_value(headers, "Accept"));
  16112. }
  16113. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  16114. // An encoding offered on a later Accept-Encoding field line is still offered.
  16115. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  16116. Server svr;
  16117. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16118. res.set_content(std::string(1024, 'x'), "text/plain");
  16119. });
  16120. auto port = svr.bind_to_any_port(HOST);
  16121. thread t = thread([&]() { svr.listen_after_bind(); });
  16122. auto se = detail::scope_exit([&] {
  16123. svr.stop();
  16124. t.join();
  16125. ASSERT_FALSE(svr.is_running());
  16126. });
  16127. svr.wait_until_ready();
  16128. Client cli(HOST, port);
  16129. cli.set_decompress(false);
  16130. Headers headers;
  16131. headers.emplace("Accept-Encoding", "identity");
  16132. headers.emplace("Accept-Encoding", "gzip");
  16133. auto res = cli.Get("/", headers);
  16134. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16135. EXPECT_EQ(StatusCode::OK_200, res->status);
  16136. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  16137. }
  16138. #endif
  16139. #ifndef _WIN32
  16140. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  16141. Server svr;
  16142. svr.Post("/post", [&](const Request &req, Response &res) {
  16143. res.set_content(req.body, "text/plain");
  16144. });
  16145. svr.Put("/put", [&](const Request &req, Response &res) {
  16146. res.set_content(req.body, "text/plain");
  16147. });
  16148. svr.Patch("/patch", [&](const Request &req, Response &res) {
  16149. res.set_content(req.body, "text/plain");
  16150. });
  16151. svr.Delete("/delete", [&](const Request &req, Response &res) {
  16152. res.set_content(req.body, "text/plain");
  16153. });
  16154. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16155. auto se = detail::scope_exit([&] {
  16156. svr.stop();
  16157. t.join();
  16158. ASSERT_FALSE(svr.is_running());
  16159. });
  16160. svr.wait_until_ready();
  16161. std::string resp;
  16162. // POST without Content-Length
  16163. ASSERT_TRUE(send_request(5,
  16164. "POST /post HTTP/1.1\r\n"
  16165. "Host: localhost\r\n"
  16166. "Connection: close\r\n"
  16167. "\r\n",
  16168. &resp));
  16169. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  16170. // PUT without Content-Length
  16171. resp.clear();
  16172. ASSERT_TRUE(send_request(5,
  16173. "PUT /put HTTP/1.1\r\n"
  16174. "Host: localhost\r\n"
  16175. "Connection: close\r\n"
  16176. "\r\n",
  16177. &resp));
  16178. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  16179. // PATCH without Content-Length
  16180. resp.clear();
  16181. ASSERT_TRUE(send_request(5,
  16182. "PATCH /patch HTTP/1.1\r\n"
  16183. "Host: localhost\r\n"
  16184. "Connection: close\r\n"
  16185. "\r\n",
  16186. &resp));
  16187. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  16188. // DELETE without Content-Length
  16189. resp.clear();
  16190. ASSERT_TRUE(send_request(5,
  16191. "DELETE /delete HTTP/1.1\r\n"
  16192. "Host: localhost\r\n"
  16193. "Connection: close\r\n"
  16194. "\r\n",
  16195. &resp));
  16196. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  16197. }
  16198. #endif
  16199. //==============================================================================
  16200. // open_stream() Tests
  16201. //==============================================================================
  16202. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  16203. std::string result;
  16204. char buf[8192];
  16205. ssize_t n;
  16206. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  16207. result.append(buf, static_cast<size_t>(n));
  16208. }
  16209. return result;
  16210. }
  16211. // Mock stream for unit tests
  16212. class MockStream : public Stream {
  16213. public:
  16214. std::string data;
  16215. size_t pos = 0;
  16216. ssize_t error_after = -1; // -1 = no error
  16217. explicit MockStream(const std::string &d, ssize_t err = -1)
  16218. : data(d), error_after(err) {}
  16219. bool is_readable() const override { return true; }
  16220. bool wait_readable() const override { return true; }
  16221. bool wait_writable() const override { return true; }
  16222. ssize_t read(char *ptr, size_t size) override {
  16223. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  16224. if (pos >= data.size()) return 0;
  16225. size_t limit =
  16226. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  16227. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  16228. std::memcpy(ptr, data.data() + pos, to_read);
  16229. pos += to_read;
  16230. return static_cast<ssize_t>(to_read);
  16231. }
  16232. ssize_t write(const char *, size_t) override { return -1; }
  16233. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  16234. ip = "127.0.0.1";
  16235. port = 0;
  16236. }
  16237. void get_local_ip_and_port(std::string &ip, int &port) const override {
  16238. ip = "127.0.0.1";
  16239. port = 0;
  16240. }
  16241. socket_t socket() const override { return INVALID_SOCKET; }
  16242. time_t duration() const override { return 0; }
  16243. };
  16244. TEST(StreamHandleTest, Basic) {
  16245. ClientImpl::StreamHandle handle;
  16246. EXPECT_FALSE(handle.is_valid());
  16247. handle.response = detail::make_unique<Response>();
  16248. handle.error = Error::Connection;
  16249. EXPECT_FALSE(handle.is_valid());
  16250. handle.error = Error::Success;
  16251. EXPECT_TRUE(handle.is_valid());
  16252. }
  16253. TEST(BodyReaderTest, Basic) {
  16254. MockStream stream("Hello, World!");
  16255. detail::BodyReader reader;
  16256. reader.stream = &stream;
  16257. reader.content_length = 13;
  16258. char buf[32];
  16259. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  16260. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  16261. EXPECT_TRUE(reader.eof);
  16262. }
  16263. TEST(BodyReaderTest, NoStream) {
  16264. detail::BodyReader reader;
  16265. char buf[32];
  16266. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  16267. EXPECT_EQ(Error::Connection, reader.last_error);
  16268. }
  16269. TEST(BodyReaderTest, Error) {
  16270. MockStream stream("Hello, World!", 5);
  16271. detail::BodyReader reader;
  16272. reader.stream = &stream;
  16273. reader.content_length = 13;
  16274. char buf[32];
  16275. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  16276. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  16277. EXPECT_EQ(Error::Read, reader.last_error);
  16278. }
  16279. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  16280. // Mock-based StreamHandle tests relying on private internals are removed.
  16281. class OpenStreamTest : public ::testing::Test {
  16282. protected:
  16283. void SetUp() override {
  16284. svr_.Get("/hello", [](const Request &, Response &res) {
  16285. res.set_content("Hello World!", "text/plain");
  16286. });
  16287. svr_.Get("/large", [](const Request &, Response &res) {
  16288. res.set_content(std::string(10000, 'X'), "text/plain");
  16289. });
  16290. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  16291. res.set_content("Hello World!", "image/jpeg");
  16292. res.set_header("Content-Encoding", "UTF-8");
  16293. });
  16294. svr_.Get("/chunked", [](const Request &, Response &res) {
  16295. res.set_chunked_content_provider("text/plain",
  16296. [](size_t offset, DataSink &sink) {
  16297. if (offset < 15) {
  16298. sink.write("chunk", 5);
  16299. return true;
  16300. }
  16301. sink.done();
  16302. return true;
  16303. });
  16304. });
  16305. svr_.Get("/compressible", [](const Request &, Response &res) {
  16306. res.set_chunked_content_provider("text/plain", [](size_t offset,
  16307. DataSink &sink) {
  16308. if (offset < 100 * 1024) {
  16309. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  16310. sink.write(chunk.data(), chunk.size());
  16311. return true;
  16312. }
  16313. sink.done();
  16314. return true;
  16315. });
  16316. });
  16317. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  16318. [](const Request & /*req*/, Response &res) {
  16319. auto i = new int(0);
  16320. res.set_header("Trailer", "Content-Length, X-Allowed");
  16321. res.set_chunked_content_provider(
  16322. "text/plain",
  16323. [i](size_t /*offset*/, DataSink &sink) {
  16324. switch (*i) {
  16325. case 0: sink.os << "123"; break;
  16326. case 1: sink.os << "456"; break;
  16327. case 2: sink.os << "789"; break;
  16328. case 3: {
  16329. sink.done_with_trailer(
  16330. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  16331. } break;
  16332. }
  16333. (*i)++;
  16334. return true;
  16335. },
  16336. [i](bool success) {
  16337. EXPECT_TRUE(success);
  16338. delete i;
  16339. });
  16340. });
  16341. // Echo headers endpoint for header-related tests
  16342. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  16343. std::string body;
  16344. for (const auto &h : req.headers) {
  16345. body.append(h.first);
  16346. body.push_back(':');
  16347. body.append(h.second);
  16348. body.push_back('\n');
  16349. }
  16350. res.set_content(body, "text/plain");
  16351. });
  16352. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  16353. std::string body;
  16354. for (const auto &h : req.headers) {
  16355. body.append(h.first);
  16356. body.push_back(':');
  16357. body.append(h.second);
  16358. body.push_back('\n');
  16359. }
  16360. res.set_content(body, "text/plain");
  16361. });
  16362. port_ = svr_.bind_to_any_port("127.0.0.1");
  16363. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  16364. svr_.wait_until_ready();
  16365. }
  16366. void TearDown() override {
  16367. svr_.stop();
  16368. if (thread_.joinable()) thread_.join();
  16369. }
  16370. Server svr_;
  16371. std::thread thread_;
  16372. int port_ = 0;
  16373. };
  16374. TEST_F(OpenStreamTest, Basic) {
  16375. Client cli("127.0.0.1", port_);
  16376. auto handle = cli.open_stream("GET", "/hello");
  16377. EXPECT_TRUE(handle.is_valid());
  16378. EXPECT_EQ("Hello World!", read_all(handle));
  16379. }
  16380. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  16381. Client cli("127.0.0.1", port_);
  16382. auto handle = cli.open_stream("GET", "/unknown-encoding");
  16383. ASSERT_TRUE(handle.is_valid());
  16384. EXPECT_EQ("Hello World!", read_all(handle));
  16385. }
  16386. TEST_F(OpenStreamTest, SmallBuffer) {
  16387. Client cli("127.0.0.1", port_);
  16388. auto handle = cli.open_stream("GET", "/hello");
  16389. std::string result;
  16390. char buf[4];
  16391. ssize_t n;
  16392. while ((n = handle.read(buf, sizeof(buf))) > 0)
  16393. result.append(buf, static_cast<size_t>(n));
  16394. EXPECT_EQ("Hello World!", result);
  16395. }
  16396. TEST_F(OpenStreamTest, DefaultHeaders) {
  16397. Client cli("127.0.0.1", port_);
  16398. // open_stream GET should include Host, User-Agent and Accept-Encoding
  16399. {
  16400. auto handle = cli.open_stream("GET", "/echo-headers");
  16401. ASSERT_TRUE(handle.is_valid());
  16402. auto body = read_all(handle);
  16403. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  16404. std::string::npos);
  16405. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  16406. std::string::npos);
  16407. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  16408. }
  16409. // open_stream POST with body and no explicit content_type should NOT add
  16410. // text/plain Content-Type (behavior differs from non-streaming path), but
  16411. // should include Content-Length
  16412. {
  16413. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  16414. ASSERT_TRUE(handle.is_valid());
  16415. auto body = read_all(handle);
  16416. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  16417. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  16418. }
  16419. // open_stream POST with explicit Content-Type should preserve it
  16420. {
  16421. auto handle = cli.open_stream("POST", "/echo-headers", {},
  16422. {{"Content-Type", "application/custom"}},
  16423. "{}", "application/custom");
  16424. ASSERT_TRUE(handle.is_valid());
  16425. auto body = read_all(handle);
  16426. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  16427. }
  16428. // User-specified User-Agent must not be overwritten for stream API
  16429. {
  16430. auto handle = cli.open_stream("GET", "/echo-headers", {},
  16431. {{"User-Agent", "MyAgent/1.2"}});
  16432. ASSERT_TRUE(handle.is_valid());
  16433. auto body = read_all(handle);
  16434. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  16435. }
  16436. }
  16437. TEST_F(OpenStreamTest, Large) {
  16438. Client cli("127.0.0.1", port_);
  16439. auto handle = cli.open_stream("GET", "/large");
  16440. EXPECT_EQ(10000u, read_all(handle).size());
  16441. }
  16442. TEST_F(OpenStreamTest, ConnectionError) {
  16443. Client cli("127.0.0.1", 9999);
  16444. auto handle = cli.open_stream("GET", "/hello");
  16445. EXPECT_FALSE(handle.is_valid());
  16446. }
  16447. TEST_F(OpenStreamTest, Chunked) {
  16448. Client cli("127.0.0.1", port_);
  16449. auto handle = cli.open_stream("GET", "/chunked");
  16450. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  16451. "Transfer-Encoding") == "chunked");
  16452. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  16453. }
  16454. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  16455. Client cli("127.0.0.1", port_);
  16456. auto handle =
  16457. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  16458. ASSERT_TRUE(handle.is_valid());
  16459. // Consume body to allow trailers to be received/parsed
  16460. auto body = read_all(handle);
  16461. // Explicitly parse trailers (ensure trailers are available for assertion)
  16462. handle.parse_trailers_if_needed();
  16463. EXPECT_EQ(std::string("123456789"), body);
  16464. // The response should include a Trailer header declaring both names
  16465. ASSERT_TRUE(handle.response);
  16466. EXPECT_TRUE(handle.response->has_header("Trailer"));
  16467. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  16468. handle.response->get_header_value("Trailer"));
  16469. // Prohibited trailer must not be present
  16470. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  16471. // Allowed trailer should be present
  16472. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  16473. EXPECT_EQ(std::string("yes"),
  16474. handle.response->get_trailer_value("X-Allowed"));
  16475. // Verify trailers are NOT present as regular headers
  16476. EXPECT_EQ(std::string(""),
  16477. handle.response->get_header_value("Content-Length"));
  16478. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  16479. }
  16480. static std::thread serve_single_response(std::promise<int> &port_promise,
  16481. const std::string &response) {
  16482. return std::thread([&port_promise, response] {
  16483. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16484. default_socket_options(srv);
  16485. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  16486. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  16487. sockaddr_in addr{};
  16488. addr.sin_family = AF_INET;
  16489. addr.sin_port = htons(0); // Let OS assign a free port
  16490. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16491. int opt = 1;
  16492. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  16493. #ifdef _WIN32
  16494. reinterpret_cast<const char *>(&opt),
  16495. #else
  16496. &opt,
  16497. #endif
  16498. sizeof(opt));
  16499. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  16500. ::listen(srv, 1) != 0) {
  16501. port_promise.set_value(-1);
  16502. detail::close_socket(srv);
  16503. return;
  16504. }
  16505. socklen_t addr_len = sizeof(addr);
  16506. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  16507. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  16508. sockaddr_in cli_addr{};
  16509. socklen_t cli_len = sizeof(cli_addr);
  16510. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  16511. if (cli != INVALID_SOCKET) {
  16512. // Read the complete HTTP request (until the blank line that terminates
  16513. // headers) before sending the response. If the server closes the socket
  16514. // while the client's request data is still unread in the kernel receive
  16515. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  16516. // connection on both sides: it discards the client's receive buffer
  16517. // (which already holds our response) and causes any in-progress write on
  16518. // the client to fail with ECONNRESET. Reading all request data first
  16519. // ensures close() emits a graceful FIN.
  16520. {
  16521. char rbuf[256];
  16522. std::string req;
  16523. while (req.find("\r\n\r\n") == std::string::npos) {
  16524. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  16525. if (n <= 0) { break; }
  16526. req.append(rbuf, static_cast<size_t>(n));
  16527. }
  16528. }
  16529. ::send(cli,
  16530. #ifdef _WIN32
  16531. static_cast<const char *>(response.c_str()),
  16532. static_cast<int>(response.size()),
  16533. #else
  16534. response.c_str(), response.size(),
  16535. #endif
  16536. 0);
  16537. detail::close_socket(cli);
  16538. }
  16539. detail::close_socket(srv);
  16540. });
  16541. }
  16542. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  16543. #ifndef _WIN32
  16544. signal(SIGPIPE, SIG_IGN);
  16545. #endif
  16546. std::promise<int> port_promise;
  16547. auto port_future = port_promise.get_future();
  16548. auto server_thread =
  16549. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  16550. "Content-Type: text/plain\r\n"
  16551. "Content-Length: not-a-number\r\n"
  16552. "Connection: close\r\n"
  16553. "\r\n"
  16554. "hello");
  16555. auto port = port_future.get();
  16556. ASSERT_GT(port, 0);
  16557. Client cli("127.0.0.1", port);
  16558. auto handle = cli.open_stream("GET", "/");
  16559. EXPECT_FALSE(handle.is_valid());
  16560. server_thread.join();
  16561. }
  16562. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  16563. #ifndef _WIN32
  16564. signal(SIGPIPE, SIG_IGN);
  16565. #endif
  16566. std::promise<int> port_promise;
  16567. auto port_future = port_promise.get_future();
  16568. auto server_thread = serve_single_response(
  16569. port_promise, "HTTP/1.1 200 OK\r\n"
  16570. "Content-Type: text/plain\r\n"
  16571. "Content-Length: 99999999999999999999999999\r\n"
  16572. "Connection: close\r\n"
  16573. "\r\n"
  16574. "hello");
  16575. auto port = port_future.get();
  16576. ASSERT_GT(port, 0);
  16577. // Historically std::stoull would throw std::out_of_range here and crash
  16578. // the process, then parsing silently clamped to a bogus framing length and
  16579. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  16580. // so the stream fails to open, matching the not-a-number case above. The
  16581. // process still must NOT terminate.
  16582. Client cli("127.0.0.1", port);
  16583. auto handle = cli.open_stream("GET", "/");
  16584. EXPECT_FALSE(handle.is_valid());
  16585. server_thread.join();
  16586. }
  16587. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  16588. TEST_F(OpenStreamTest, Gzip) {
  16589. Client cli("127.0.0.1", port_);
  16590. auto handle = cli.open_stream("GET", "/compressible", {},
  16591. {{"Accept-Encoding", "gzip"}});
  16592. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  16593. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  16594. }
  16595. #endif
  16596. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  16597. TEST_F(OpenStreamTest, Brotli) {
  16598. Client cli("127.0.0.1", port_);
  16599. auto handle =
  16600. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  16601. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  16602. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  16603. }
  16604. #endif
  16605. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  16606. TEST_F(OpenStreamTest, Zstd) {
  16607. Client cli("127.0.0.1", port_);
  16608. auto handle = cli.open_stream("GET", "/compressible", {},
  16609. {{"Accept-Encoding", "zstd"}});
  16610. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  16611. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  16612. }
  16613. #endif
  16614. #ifdef CPPHTTPLIB_SSL_ENABLED
  16615. class SSLOpenStreamTest : public ::testing::Test {
  16616. protected:
  16617. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  16618. void SetUp() override {
  16619. svr_.Get("/hello", [](const Request &, Response &res) {
  16620. res.set_content("Hello SSL World!", "text/plain");
  16621. });
  16622. svr_.Get("/chunked", [](const Request &, Response &res) {
  16623. res.set_chunked_content_provider("text/plain",
  16624. [](size_t offset, DataSink &sink) {
  16625. if (offset < 15) {
  16626. sink.write("chunk", 5);
  16627. return true;
  16628. }
  16629. sink.done();
  16630. return true;
  16631. });
  16632. });
  16633. svr_.Post("/echo", [](const Request &req, Response &res) {
  16634. res.set_content(req.body, req.get_header_value("Content-Type"));
  16635. });
  16636. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  16637. std::string body = req.body;
  16638. res.set_chunked_content_provider(
  16639. "text/plain", [body](size_t offset, DataSink &sink) {
  16640. if (offset < body.size()) {
  16641. sink.write(body.data() + offset, body.size() - offset);
  16642. }
  16643. sink.done();
  16644. return true;
  16645. });
  16646. });
  16647. port_ = svr_.bind_to_any_port("127.0.0.1");
  16648. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  16649. svr_.wait_until_ready();
  16650. }
  16651. void TearDown() override {
  16652. svr_.stop();
  16653. if (thread_.joinable()) thread_.join();
  16654. }
  16655. SSLServer svr_;
  16656. std::thread thread_;
  16657. int port_ = 0;
  16658. };
  16659. TEST_F(SSLOpenStreamTest, Basic) {
  16660. SSLClient cli("127.0.0.1", port_);
  16661. cli.enable_server_certificate_verification(false);
  16662. auto handle = cli.open_stream("GET", "/hello");
  16663. ASSERT_TRUE(handle.is_valid());
  16664. EXPECT_EQ("Hello SSL World!", read_all(handle));
  16665. }
  16666. TEST_F(SSLOpenStreamTest, Chunked) {
  16667. SSLClient cli("127.0.0.1", port_);
  16668. cli.enable_server_certificate_verification(false);
  16669. auto handle = cli.open_stream("GET", "/chunked");
  16670. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  16671. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  16672. "Transfer-Encoding") == "chunked");
  16673. auto body = read_all(handle);
  16674. EXPECT_EQ("chunkchunkchunk", body);
  16675. }
  16676. TEST_F(SSLOpenStreamTest, Post) {
  16677. SSLClient cli("127.0.0.1", port_);
  16678. cli.enable_server_certificate_verification(false);
  16679. auto handle =
  16680. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  16681. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  16682. EXPECT_EQ(200, handle.response->status);
  16683. auto body = read_all(handle);
  16684. EXPECT_EQ("Hello SSL POST", body);
  16685. }
  16686. TEST_F(SSLOpenStreamTest, PostChunked) {
  16687. SSLClient cli("127.0.0.1", port_);
  16688. cli.enable_server_certificate_verification(false);
  16689. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  16690. "Chunked SSL Data", "text/plain");
  16691. ASSERT_TRUE(handle.is_valid());
  16692. EXPECT_EQ(200, handle.response->status);
  16693. auto body = read_all(handle);
  16694. EXPECT_EQ("Chunked SSL Data", body);
  16695. }
  16696. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  16697. // Content-Length is terminated by the server closing the connection. When the
  16698. // SSL peer sends a close_notify after the body, the client must treat it as a
  16699. // clean EOF and return a successful response rather than an error.
  16700. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  16701. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16702. ASSERT_TRUE(svr.is_valid());
  16703. svr.set_keep_alive_max_count(1);
  16704. const std::string expected_body = "Hello from connection-close response!";
  16705. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  16706. res.set_content_provider("text/plain",
  16707. [&](size_t offset, DataSink &sink) -> bool {
  16708. if (offset < expected_body.size()) {
  16709. sink.write(expected_body.data() + offset,
  16710. expected_body.size() - offset);
  16711. }
  16712. sink.done();
  16713. return true;
  16714. });
  16715. });
  16716. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  16717. auto se = detail::scope_exit([&] {
  16718. svr.stop();
  16719. listen_thread.join();
  16720. ASSERT_FALSE(svr.is_running());
  16721. });
  16722. svr.wait_until_ready();
  16723. SSLClient cli(HOST, PORT);
  16724. cli.enable_server_certificate_verification(false);
  16725. auto res = cli.Get("/no-content-length");
  16726. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  16727. EXPECT_EQ(StatusCode::OK_200, res->status);
  16728. EXPECT_EQ(expected_body, res->body);
  16729. }
  16730. #endif // CPPHTTPLIB_SSL_ENABLED
  16731. //==============================================================================
  16732. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  16733. // results for various scenarios.
  16734. //==============================================================================
  16735. TEST(ParityTest, GetVsOpenStream) {
  16736. Server svr;
  16737. const std::string path = "/parity";
  16738. const std::string content = "Parity test content: hello world";
  16739. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  16740. res.set_content(content, "text/plain");
  16741. });
  16742. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16743. auto se = detail::scope_exit([&] {
  16744. svr.stop();
  16745. t.join();
  16746. ASSERT_FALSE(svr.is_running());
  16747. });
  16748. svr.wait_until_ready();
  16749. Client cli(HOST, PORT);
  16750. // Non-stream path
  16751. auto r1 = cli.Get(path);
  16752. ASSERT_TRUE(r1);
  16753. EXPECT_EQ(StatusCode::OK_200, r1->status);
  16754. // Stream path
  16755. auto h = cli.open_stream("GET", path);
  16756. ASSERT_TRUE(h.is_valid());
  16757. EXPECT_EQ(r1->body, read_all(h));
  16758. }
  16759. // Helper to compress data with provided compressor type T
  16760. template <typename Compressor>
  16761. static std::string compress_payload_for_parity(const std::string &in) {
  16762. std::string out;
  16763. Compressor compressor;
  16764. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  16765. [&](const char *data, size_t n) {
  16766. out.append(data, n);
  16767. return true;
  16768. });
  16769. EXPECT_TRUE(ok);
  16770. return out;
  16771. }
  16772. // Helper function for compression parity tests
  16773. template <typename Compressor>
  16774. static void test_compression_parity(const std::string &original,
  16775. const std::string &path,
  16776. const std::string &encoding) {
  16777. const std::string compressed =
  16778. compress_payload_for_parity<Compressor>(original);
  16779. Server svr;
  16780. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  16781. res.set_content(compressed, "application/octet-stream");
  16782. res.set_header("Content-Encoding", encoding);
  16783. });
  16784. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  16785. auto se = detail::scope_exit([&] {
  16786. svr.stop();
  16787. t.join();
  16788. ASSERT_FALSE(svr.is_running());
  16789. });
  16790. svr.wait_until_ready();
  16791. Client cli(HOST, PORT);
  16792. // Non-streaming
  16793. {
  16794. auto res = cli.Get(path);
  16795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16796. EXPECT_EQ(StatusCode::OK_200, res->status);
  16797. EXPECT_EQ(original, res->body);
  16798. }
  16799. // Streaming
  16800. {
  16801. auto h = cli.open_stream("GET", path);
  16802. ASSERT_TRUE(h.is_valid());
  16803. EXPECT_EQ(original, read_all(h));
  16804. }
  16805. }
  16806. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  16807. TEST(ParityTest, Gzip) {
  16808. test_compression_parity<detail::gzip_compressor>(
  16809. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  16810. }
  16811. #endif
  16812. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  16813. TEST(ParityTest, Brotli) {
  16814. test_compression_parity<detail::brotli_compressor>(
  16815. "Hello, brotli parity test payload", "/parity-br", "br");
  16816. }
  16817. #endif
  16818. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  16819. TEST(ParityTest, Zstd) {
  16820. test_compression_parity<detail::zstd_compressor>(
  16821. "Zstandard parity test payload", "/parity-zstd", "zstd");
  16822. }
  16823. #endif
  16824. //==============================================================================
  16825. // New Stream API Tests
  16826. //==============================================================================
  16827. inline std::string read_body(httplib::stream::Result &result) {
  16828. std::string body;
  16829. while (result.next()) {
  16830. body.append(result.data(), result.size());
  16831. }
  16832. return body;
  16833. }
  16834. TEST(ClientConnectionTest, Basic) {
  16835. httplib::ClientConnection conn;
  16836. EXPECT_FALSE(conn.is_open());
  16837. conn.sock = 1;
  16838. EXPECT_TRUE(conn.is_open());
  16839. httplib::ClientConnection conn2(std::move(conn));
  16840. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  16841. conn2.sock = INVALID_SOCKET;
  16842. }
  16843. // Unified test server for all stream::* tests
  16844. class StreamApiTest : public ::testing::Test {
  16845. protected:
  16846. void SetUp() override {
  16847. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  16848. res.set_content("Hello World!", "text/plain");
  16849. });
  16850. svr_.Get("/echo-params",
  16851. [](const httplib::Request &req, httplib::Response &res) {
  16852. std::string r;
  16853. for (const auto &p : req.params) {
  16854. if (!r.empty()) r += "&";
  16855. r += p.first + "=" + p.second;
  16856. }
  16857. res.set_content(r, "text/plain");
  16858. });
  16859. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  16860. res.set_content(req.body, req.get_header_value("Content-Type"));
  16861. });
  16862. svr_.Post("/echo-headers",
  16863. [](const httplib::Request &req, httplib::Response &res) {
  16864. std::string r;
  16865. for (const auto &h : req.headers)
  16866. r += h.first + ": " + h.second + "\n";
  16867. res.set_content(r, "text/plain");
  16868. });
  16869. svr_.Post("/echo-params",
  16870. [](const httplib::Request &req, httplib::Response &res) {
  16871. std::string r = "params:";
  16872. for (const auto &p : req.params)
  16873. r += p.first + "=" + p.second + ";";
  16874. res.set_content(r + " body:" + req.body, "text/plain");
  16875. });
  16876. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  16877. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  16878. });
  16879. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  16880. res.set_content("PUT:" + req.body, "text/plain");
  16881. });
  16882. svr_.Patch("/echo",
  16883. [](const httplib::Request &req, httplib::Response &res) {
  16884. res.set_content("PATCH:" + req.body, "text/plain");
  16885. });
  16886. svr_.Delete(
  16887. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  16888. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  16889. "text/plain");
  16890. });
  16891. svr_.Get("/head-test",
  16892. [](const httplib::Request &, httplib::Response &res) {
  16893. res.set_content("body for HEAD", "text/plain");
  16894. });
  16895. svr_.Options("/options",
  16896. [](const httplib::Request &, httplib::Response &res) {
  16897. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  16898. });
  16899. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  16900. svr_.wait_until_ready();
  16901. }
  16902. void TearDown() override {
  16903. svr_.stop();
  16904. if (thread_.joinable()) thread_.join();
  16905. }
  16906. httplib::Server svr_;
  16907. std::thread thread_;
  16908. };
  16909. // stream::Get tests
  16910. TEST_F(StreamApiTest, GetBasic) {
  16911. httplib::Client cli(HOST, PORT);
  16912. auto result = httplib::stream::Get(cli, "/hello");
  16913. ASSERT_TRUE(result.is_valid());
  16914. EXPECT_EQ(200, result.status());
  16915. EXPECT_EQ("Hello World!", read_body(result));
  16916. }
  16917. TEST_F(StreamApiTest, GetWithParams) {
  16918. httplib::Client cli(HOST, PORT);
  16919. httplib::Params params{{"foo", "bar"}};
  16920. auto result = httplib::stream::Get(cli, "/echo-params", params);
  16921. ASSERT_TRUE(result.is_valid());
  16922. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  16923. }
  16924. TEST_F(StreamApiTest, GetConnectionError) {
  16925. httplib::Client cli(HOST, 9999);
  16926. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  16927. }
  16928. TEST_F(StreamApiTest, Get404) {
  16929. httplib::Client cli(HOST, PORT);
  16930. auto result = httplib::stream::Get(cli, "/nonexistent");
  16931. EXPECT_TRUE(result.is_valid());
  16932. EXPECT_EQ(404, result.status());
  16933. }
  16934. // stream::Post tests
  16935. TEST_F(StreamApiTest, PostBasic) {
  16936. httplib::Client cli(HOST, PORT);
  16937. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  16938. "application/json");
  16939. ASSERT_TRUE(result.is_valid());
  16940. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  16941. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  16942. }
  16943. TEST_F(StreamApiTest, PostWithHeaders) {
  16944. httplib::Client cli(HOST, PORT);
  16945. httplib::Headers headers{{"X-Custom", "value"}};
  16946. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  16947. "text/plain");
  16948. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  16949. }
  16950. TEST_F(StreamApiTest, PostWithParams) {
  16951. httplib::Client cli(HOST, PORT);
  16952. httplib::Params params{{"k", "v"}};
  16953. auto result =
  16954. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  16955. auto body = read_body(result);
  16956. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  16957. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  16958. }
  16959. TEST_F(StreamApiTest, PostLarge) {
  16960. httplib::Client cli(HOST, PORT);
  16961. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  16962. size_t total = 0;
  16963. while (result.next()) {
  16964. total += result.size();
  16965. }
  16966. EXPECT_EQ(100u * 1024u, total);
  16967. }
  16968. // stream::Put/Patch tests
  16969. TEST_F(StreamApiTest, PutAndPatch) {
  16970. httplib::Client cli(HOST, PORT);
  16971. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  16972. EXPECT_EQ("PUT:test", read_body(put));
  16973. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  16974. EXPECT_EQ("PATCH:test", read_body(patch));
  16975. }
  16976. // stream::Delete tests
  16977. TEST_F(StreamApiTest, Delete) {
  16978. httplib::Client cli(HOST, PORT);
  16979. auto del1 = httplib::stream::Delete(cli, "/resource");
  16980. EXPECT_EQ("Deleted", read_body(del1));
  16981. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  16982. EXPECT_EQ("Deleted:data", read_body(del2));
  16983. }
  16984. // stream::Head/Options tests
  16985. TEST_F(StreamApiTest, HeadAndOptions) {
  16986. httplib::Client cli(HOST, PORT);
  16987. auto head = httplib::stream::Head(cli, "/head-test");
  16988. EXPECT_TRUE(head.is_valid());
  16989. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  16990. auto opts = httplib::stream::Options(cli, "/options");
  16991. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  16992. }
  16993. // SSL stream::* tests
  16994. #ifdef CPPHTTPLIB_SSL_ENABLED
  16995. class SSLStreamApiTest : public ::testing::Test {
  16996. protected:
  16997. void SetUp() override {
  16998. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  16999. res.set_content("Hello SSL!", "text/plain");
  17000. });
  17001. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  17002. res.set_content(req.body, "text/plain");
  17003. });
  17004. port_ = svr_.bind_to_any_port("127.0.0.1");
  17005. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  17006. svr_.wait_until_ready();
  17007. }
  17008. void TearDown() override {
  17009. svr_.stop();
  17010. if (thread_.joinable()) thread_.join();
  17011. }
  17012. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  17013. std::thread thread_;
  17014. int port_ = 0;
  17015. };
  17016. TEST_F(SSLStreamApiTest, GetAndPost) {
  17017. httplib::SSLClient cli("127.0.0.1", port_);
  17018. cli.enable_server_certificate_verification(false);
  17019. auto get = httplib::stream::Get(cli, "/hello");
  17020. EXPECT_EQ("Hello SSL!", read_body(get));
  17021. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  17022. EXPECT_EQ("test", read_body(post));
  17023. }
  17024. #endif
  17025. // Tests for Error::Timeout and Error::ConnectionClosed error types
  17026. // These errors are set in SocketStream/SSLSocketStream and propagated through
  17027. // BodyReader
  17028. TEST(ErrorHandlingTest, StreamReadTimeout) {
  17029. // Test that read timeout during streaming is detected
  17030. // Use a large content-length response where server delays mid-stream
  17031. Server svr;
  17032. svr.Get("/slow-stream", [](const Request &, Response &res) {
  17033. // Send a large response with delay in the middle
  17034. res.set_content_provider(
  17035. 1000, // content_length
  17036. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  17037. if (offset < 100) {
  17038. // Send first 100 bytes immediately
  17039. std::string data(100, 'A');
  17040. sink.write(data.c_str(), data.size());
  17041. return true;
  17042. }
  17043. // Then delay longer than client timeout
  17044. std::this_thread::sleep_for(std::chrono::seconds(3));
  17045. std::string data(900, 'B');
  17046. sink.write(data.c_str(), data.size());
  17047. return true;
  17048. });
  17049. });
  17050. auto port = 8091;
  17051. std::thread t([&]() { svr.listen("localhost", port); });
  17052. svr.wait_until_ready();
  17053. Client cli("localhost", port);
  17054. cli.set_read_timeout(1, 0); // 1 second timeout
  17055. auto handle = cli.open_stream("GET", "/slow-stream");
  17056. ASSERT_TRUE(handle.is_valid());
  17057. char buf[256];
  17058. ssize_t total = 0;
  17059. ssize_t n;
  17060. bool got_error = false;
  17061. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  17062. total += n;
  17063. }
  17064. if (n < 0) {
  17065. got_error = true;
  17066. // Should be timeout or read error
  17067. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  17068. handle.get_read_error() == Error::Read)
  17069. << "Actual error: " << to_string(handle.get_read_error());
  17070. }
  17071. // Either we got an error, or we got less data than expected
  17072. EXPECT_TRUE(got_error || total < 1000)
  17073. << "Expected timeout but got all " << total << " bytes";
  17074. svr.stop();
  17075. t.join();
  17076. }
  17077. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  17078. // Test connection closed detection via BodyReader
  17079. Server svr;
  17080. std::atomic<bool> close_now{false};
  17081. svr.Get("/will-close", [&](const Request &, Response &res) {
  17082. res.set_content_provider(
  17083. 10000, // Large content_length that we won't fully send
  17084. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  17085. if (offset < 100) {
  17086. std::string data(100, 'X');
  17087. sink.write(data.c_str(), data.size());
  17088. return true;
  17089. }
  17090. // Wait for signal then abort
  17091. while (!close_now) {
  17092. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  17093. }
  17094. return false; // Abort - server will close connection
  17095. });
  17096. });
  17097. auto port = 8092;
  17098. std::thread t([&]() { svr.listen("localhost", port); });
  17099. svr.wait_until_ready();
  17100. Client cli("localhost", port);
  17101. auto handle = cli.open_stream("GET", "/will-close");
  17102. ASSERT_TRUE(handle.is_valid());
  17103. char buf[256];
  17104. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  17105. EXPECT_GT(n, 0) << "First read should succeed";
  17106. // Signal server to close
  17107. close_now = true;
  17108. // Keep reading until error or EOF
  17109. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  17110. // Keep reading
  17111. }
  17112. // Should get an error since content_length wasn't satisfied
  17113. if (n < 0) {
  17114. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  17115. handle.get_read_error() == Error::Read)
  17116. << "Actual error: " << to_string(handle.get_read_error());
  17117. }
  17118. svr.stop();
  17119. t.join();
  17120. }
  17121. #ifdef CPPHTTPLIB_SSL_ENABLED
  17122. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  17123. // Test that read timeout during SSL streaming is detected
  17124. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17125. svr.Get("/slow-stream", [](const Request &, Response &res) {
  17126. res.set_content_provider(
  17127. 1000, "text/plain",
  17128. [](size_t offset, size_t /*length*/, DataSink &sink) {
  17129. if (offset < 100) {
  17130. std::string data(100, 'A');
  17131. sink.write(data.c_str(), data.size());
  17132. return true;
  17133. }
  17134. std::this_thread::sleep_for(std::chrono::seconds(3));
  17135. std::string data(900, 'B');
  17136. sink.write(data.c_str(), data.size());
  17137. return true;
  17138. });
  17139. });
  17140. auto port = 8093;
  17141. std::thread t([&]() { svr.listen("localhost", port); });
  17142. svr.wait_until_ready();
  17143. SSLClient cli("localhost", port);
  17144. cli.enable_server_certificate_verification(false);
  17145. cli.set_read_timeout(1, 0); // 1 second timeout
  17146. auto handle = cli.open_stream("GET", "/slow-stream");
  17147. ASSERT_TRUE(handle.is_valid());
  17148. char buf[256];
  17149. ssize_t total = 0;
  17150. ssize_t n;
  17151. bool got_error = false;
  17152. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  17153. total += n;
  17154. }
  17155. if (n < 0) {
  17156. got_error = true;
  17157. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  17158. handle.get_read_error() == Error::Read)
  17159. << "Actual error: " << to_string(handle.get_read_error());
  17160. }
  17161. EXPECT_TRUE(got_error || total < 1000)
  17162. << "Expected timeout but got all " << total << " bytes";
  17163. svr.stop();
  17164. t.join();
  17165. }
  17166. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  17167. // Test SSL connection closed detection
  17168. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17169. std::atomic<bool> close_now{false};
  17170. svr.Get("/will-close", [&](const Request &, Response &res) {
  17171. res.set_content_provider(
  17172. 10000, "text/plain",
  17173. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  17174. if (offset < 100) {
  17175. std::string data(100, 'X');
  17176. sink.write(data.c_str(), data.size());
  17177. return true;
  17178. }
  17179. while (!close_now) {
  17180. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  17181. }
  17182. return false;
  17183. });
  17184. });
  17185. auto port = 8094;
  17186. std::thread t([&]() { svr.listen("localhost", port); });
  17187. svr.wait_until_ready();
  17188. SSLClient cli("localhost", port);
  17189. cli.enable_server_certificate_verification(false);
  17190. auto handle = cli.open_stream("GET", "/will-close");
  17191. ASSERT_TRUE(handle.is_valid());
  17192. char buf[256];
  17193. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  17194. EXPECT_GT(n, 0);
  17195. // Signal server to close
  17196. close_now = true;
  17197. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  17198. // Keep reading
  17199. }
  17200. if (n < 0) {
  17201. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  17202. handle.get_read_error() == Error::Read)
  17203. << "Actual error: " << to_string(handle.get_read_error());
  17204. }
  17205. svr.stop();
  17206. t.join();
  17207. }
  17208. #endif
  17209. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  17210. using namespace httplib;
  17211. // Create a test file
  17212. const char *fname = "etag_testfile.txt";
  17213. const char *content = "etag-content";
  17214. {
  17215. std::ofstream ofs(fname);
  17216. ofs << content;
  17217. ASSERT_TRUE(ofs.good());
  17218. }
  17219. Server svr;
  17220. svr.set_mount_point("/static", ".");
  17221. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  17222. svr.wait_until_ready();
  17223. Client cli(HOST, PORT);
  17224. // First request: should get 200 with ETag header
  17225. auto res1 = cli.Get("/static/etag_testfile.txt");
  17226. ASSERT_TRUE(res1);
  17227. ASSERT_EQ(200, res1->status);
  17228. ASSERT_TRUE(res1->has_header("ETag"));
  17229. std::string etag = res1->get_header_value("ETag");
  17230. EXPECT_FALSE(etag.empty());
  17231. // Verify ETag format: W/"hex-hex"
  17232. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  17233. EXPECT_EQ('W', etag[0]);
  17234. EXPECT_EQ('/', etag[1]);
  17235. EXPECT_EQ('"', etag[2]);
  17236. EXPECT_EQ('"', etag.back());
  17237. // Exact match: expect 304 Not Modified
  17238. Headers h2 = {{"If-None-Match", etag}};
  17239. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  17240. ASSERT_TRUE(res2);
  17241. EXPECT_EQ(304, res2->status);
  17242. // Wildcard match: expect 304 Not Modified
  17243. Headers h3 = {{"If-None-Match", "*"}};
  17244. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  17245. ASSERT_TRUE(res3);
  17246. EXPECT_EQ(304, res3->status);
  17247. // Non-matching ETag: expect 200
  17248. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  17249. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  17250. ASSERT_TRUE(res4);
  17251. EXPECT_EQ(200, res4->status);
  17252. // Multiple ETags with one matching: expect 304
  17253. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  17254. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  17255. ASSERT_TRUE(res5);
  17256. EXPECT_EQ(304, res5->status);
  17257. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  17258. // that equivalent to the single comma-separated list above, so the match on
  17259. // the second line must still be found.
  17260. Headers h6;
  17261. h6.emplace("If-None-Match", "W/\"other\"");
  17262. h6.emplace("If-None-Match", etag);
  17263. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  17264. ASSERT_TRUE(res6);
  17265. EXPECT_EQ(304, res6->status);
  17266. svr.stop();
  17267. t.join();
  17268. std::remove(fname);
  17269. }
  17270. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  17271. using namespace httplib;
  17272. Server svr;
  17273. svr.set_mount_point("/static", ".");
  17274. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17275. svr.wait_until_ready();
  17276. Client cli(HOST, PORT);
  17277. // Send If-None-Match: * to a non-existent file
  17278. Headers h = {{"If-None-Match", "*"}};
  17279. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  17280. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17281. EXPECT_EQ(404, res->status);
  17282. svr.stop();
  17283. t.join();
  17284. }
  17285. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  17286. using namespace httplib;
  17287. // Create a test file
  17288. const char *fname = "etag_boundary_testfile.txt";
  17289. const char *content = "boundary-test";
  17290. {
  17291. std::ofstream ofs(fname);
  17292. ofs << content;
  17293. ASSERT_TRUE(ofs.good());
  17294. }
  17295. Server svr;
  17296. svr.set_mount_point("/static", ".");
  17297. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  17298. svr.wait_until_ready();
  17299. Client cli(HOST, PORT);
  17300. // Get the actual ETag
  17301. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  17302. ASSERT_TRUE(res1);
  17303. ASSERT_EQ(200, res1->status);
  17304. ASSERT_TRUE(res1->has_header("ETag"));
  17305. std::string etag = res1->get_header_value("ETag");
  17306. // Test 1: Very long ETag value (longer than actual ETag)
  17307. // Should NOT match and return 200 (not trigger out-of-bounds read)
  17308. Headers h1 = {{"If-None-Match", "W/"
  17309. "\"very-long-etag-value-that-is-much-longer-"
  17310. "than-the-actual-etag-value\""}};
  17311. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  17312. ASSERT_TRUE(res2);
  17313. EXPECT_EQ(200, res2->status); // Should not match
  17314. // Test 2: Long string followed by wildcard
  17315. // Should match on "*" and return 304 (without out-of-bounds read on the long
  17316. // string)
  17317. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  17318. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  17319. ASSERT_TRUE(res3);
  17320. EXPECT_EQ(304, res3->status); // Should match on "*"
  17321. // Test 3: Wildcard followed by long string
  17322. // Should match on "*" immediately and return 304
  17323. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  17324. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  17325. ASSERT_TRUE(res4);
  17326. EXPECT_EQ(304, res4->status); // Should match on "*"
  17327. // Test 4: Multiple long non-matching values
  17328. // Should NOT match and return 200 (test that all comparisons are safe)
  17329. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  17330. "W/\"second-long-non-matching-value\", "
  17331. "W/\"third-long-non-matching-value\""}};
  17332. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  17333. ASSERT_TRUE(res5);
  17334. EXPECT_EQ(200, res5->status); // Should not match
  17335. // Test 5: Single character that is not "*" (edge case)
  17336. Headers h5 = {{"If-None-Match", "X"}};
  17337. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  17338. ASSERT_TRUE(res6);
  17339. EXPECT_EQ(200, res6->status); // Should not match
  17340. svr.stop();
  17341. t.join();
  17342. std::remove(fname);
  17343. }
  17344. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  17345. using namespace httplib;
  17346. // Create a test file
  17347. const char *fname = "ims_testfile.txt";
  17348. const char *content = "if-modified-since-test";
  17349. {
  17350. std::ofstream ofs(fname);
  17351. ofs << content;
  17352. ASSERT_TRUE(ofs.good());
  17353. }
  17354. Server svr;
  17355. svr.set_mount_point("/static", ".");
  17356. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17357. svr.wait_until_ready();
  17358. Client cli(HOST, PORT);
  17359. // First request: should get 200 with Last-Modified header
  17360. auto res1 = cli.Get("/static/ims_testfile.txt");
  17361. ASSERT_TRUE(res1);
  17362. ASSERT_EQ(200, res1->status);
  17363. ASSERT_TRUE(res1->has_header("Last-Modified"));
  17364. std::string last_modified = res1->get_header_value("Last-Modified");
  17365. EXPECT_FALSE(last_modified.empty());
  17366. // If-Modified-Since with same time: expect 304
  17367. Headers h2 = {{"If-Modified-Since", last_modified}};
  17368. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  17369. ASSERT_TRUE(res2);
  17370. EXPECT_EQ(304, res2->status);
  17371. // If-Modified-Since with future time: expect 304
  17372. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  17373. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  17374. ASSERT_TRUE(res3);
  17375. EXPECT_EQ(304, res3->status);
  17376. // If-Modified-Since with past time: expect 200
  17377. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  17378. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  17379. ASSERT_TRUE(res4);
  17380. EXPECT_EQ(200, res4->status);
  17381. // If-None-Match takes precedence over If-Modified-Since
  17382. // (send matching ETag with old If-Modified-Since -> should still be 304)
  17383. ASSERT_TRUE(res1->has_header("ETag"));
  17384. std::string etag = res1->get_header_value("ETag");
  17385. Headers h5 = {{"If-None-Match", etag},
  17386. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  17387. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  17388. ASSERT_TRUE(res5);
  17389. EXPECT_EQ(304, res5->status);
  17390. svr.stop();
  17391. t.join();
  17392. std::remove(fname);
  17393. }
  17394. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  17395. using namespace httplib;
  17396. Server svr;
  17397. // Endpoint that returns compressible content
  17398. svr.Get("/compressible", [](const Request &, Response &res) {
  17399. // Return a large enough body to trigger compression
  17400. std::string body(1000, 'a');
  17401. res.set_content(body, "text/plain");
  17402. });
  17403. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17404. svr.wait_until_ready();
  17405. Client cli(HOST, PORT);
  17406. // Request with gzip support: should get Vary header when compressed
  17407. cli.set_compress(true);
  17408. auto res1 = cli.Get("/compressible");
  17409. ASSERT_TRUE(res1);
  17410. EXPECT_EQ(200, res1->status);
  17411. // If Content-Encoding is set, Vary should also be set
  17412. if (res1->has_header("Content-Encoding")) {
  17413. EXPECT_TRUE(res1->has_header("Vary"));
  17414. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  17415. }
  17416. // Request without Accept-Encoding header: should not have compression
  17417. Headers h_no_compress;
  17418. auto res2 = cli.Get("/compressible", h_no_compress);
  17419. ASSERT_TRUE(res2);
  17420. EXPECT_EQ(200, res2->status);
  17421. // Verify Vary header is present when compression is applied
  17422. // (the exact behavior depends on server configuration)
  17423. svr.stop();
  17424. t.join();
  17425. }
  17426. TEST(ETagTest, IfRangeWithETag) {
  17427. using namespace httplib;
  17428. // Create a test file with known content
  17429. const char *fname = "if_range_testfile.txt";
  17430. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  17431. {
  17432. std::ofstream ofs(fname);
  17433. ofs << content;
  17434. ASSERT_TRUE(ofs.good());
  17435. }
  17436. Server svr;
  17437. svr.set_mount_point("/static", ".");
  17438. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17439. svr.wait_until_ready();
  17440. Client cli(HOST, PORT);
  17441. // First request: get ETag
  17442. auto res1 = cli.Get("/static/if_range_testfile.txt");
  17443. ASSERT_TRUE(res1);
  17444. ASSERT_EQ(200, res1->status);
  17445. ASSERT_TRUE(res1->has_header("ETag"));
  17446. std::string etag = res1->get_header_value("ETag");
  17447. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  17448. // Since our server generates weak ETags (W/"..."), If-Range with our
  17449. // ETag should NOT result in partial content - it should return full content.
  17450. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  17451. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  17452. ASSERT_TRUE(res2);
  17453. // Weak ETag in If-Range -> full content (200), not partial (206)
  17454. EXPECT_EQ(200, res2->status);
  17455. EXPECT_EQ(content, res2->body);
  17456. EXPECT_FALSE(res2->has_header("Content-Range"));
  17457. // Range request with non-matching If-Range (ETag): should get 200 (full
  17458. // content)
  17459. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  17460. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  17461. ASSERT_TRUE(res3);
  17462. EXPECT_EQ(200, res3->status);
  17463. EXPECT_EQ(content, res3->body);
  17464. EXPECT_FALSE(res3->has_header("Content-Range"));
  17465. // Range request with strong ETag (hypothetical - our server doesn't generate
  17466. // strong ETags, but if client sends a strong ETag that doesn't match, it
  17467. // should return full content)
  17468. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  17469. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  17470. ASSERT_TRUE(res4);
  17471. EXPECT_EQ(200, res4->status);
  17472. EXPECT_EQ(content, res4->body);
  17473. EXPECT_FALSE(res4->has_header("Content-Range"));
  17474. svr.stop();
  17475. t.join();
  17476. std::remove(fname);
  17477. }
  17478. TEST(ETagTest, IfRangeWithDate) {
  17479. using namespace httplib;
  17480. // Create a test file
  17481. const char *fname = "if_range_date_testfile.txt";
  17482. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  17483. {
  17484. std::ofstream ofs(fname);
  17485. ofs << content;
  17486. ASSERT_TRUE(ofs.good());
  17487. }
  17488. Server svr;
  17489. svr.set_mount_point("/static", ".");
  17490. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17491. svr.wait_until_ready();
  17492. Client cli(HOST, PORT);
  17493. // First request: get Last-Modified
  17494. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  17495. ASSERT_TRUE(res1);
  17496. ASSERT_EQ(200, res1->status);
  17497. ASSERT_TRUE(res1->has_header("Last-Modified"));
  17498. std::string last_modified = res1->get_header_value("Last-Modified");
  17499. // Range request with matching If-Range (date): should get 206
  17500. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  17501. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  17502. ASSERT_TRUE(res2);
  17503. EXPECT_EQ(206, res2->status);
  17504. EXPECT_EQ("FGHIJ", res2->body);
  17505. // Range request with old If-Range date: should get 200 (full content)
  17506. Headers h3 = {{"Range", "bytes=5-9"},
  17507. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  17508. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  17509. ASSERT_TRUE(res3);
  17510. EXPECT_EQ(200, res3->status);
  17511. EXPECT_EQ(content, res3->body);
  17512. // Range request with future If-Range date: should get 206
  17513. Headers h4 = {{"Range", "bytes=0-4"},
  17514. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  17515. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  17516. ASSERT_TRUE(res4);
  17517. EXPECT_EQ(206, res4->status);
  17518. EXPECT_EQ("ABCDE", res4->body);
  17519. svr.stop();
  17520. t.join();
  17521. std::remove(fname);
  17522. }
  17523. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  17524. using namespace httplib;
  17525. const char *fname = "etag_malformed.txt";
  17526. const char *content = "malformed-etag";
  17527. {
  17528. std::ofstream ofs(fname);
  17529. ofs << content;
  17530. ASSERT_TRUE(ofs.good());
  17531. }
  17532. Server svr;
  17533. svr.set_mount_point("/static", ".");
  17534. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17535. svr.wait_until_ready();
  17536. Client cli(HOST, PORT);
  17537. // baseline: should get 200 and an ETag
  17538. auto res1 = cli.Get("/static/etag_malformed.txt");
  17539. ASSERT_TRUE(res1);
  17540. ASSERT_EQ(200, res1->status);
  17541. ASSERT_TRUE(res1->has_header("ETag"));
  17542. // Malformed ETag value (missing quotes) should be treated as non-matching
  17543. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  17544. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  17545. ASSERT_TRUE(res_bad);
  17546. EXPECT_EQ(200, res_bad->status);
  17547. // Whitespace-only header value should be considered invalid / non-matching
  17548. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  17549. "Host: localhost\r\n"
  17550. "If-None-Match: \r\n"
  17551. "Connection: close\r\n"
  17552. "\r\n";
  17553. std::string out;
  17554. ASSERT_TRUE(send_request(5, raw_req, &out));
  17555. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17556. svr.stop();
  17557. t.join();
  17558. std::remove(fname);
  17559. }
  17560. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  17561. using namespace httplib;
  17562. const char *fname = "ims_invalid_format.txt";
  17563. const char *content = "ims-bad-format";
  17564. {
  17565. std::ofstream ofs(fname);
  17566. ofs << content;
  17567. ASSERT_TRUE(ofs.good());
  17568. }
  17569. Server svr;
  17570. svr.set_mount_point("/static", ".");
  17571. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17572. svr.wait_until_ready();
  17573. Client cli(HOST, PORT);
  17574. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  17575. ASSERT_TRUE(res1);
  17576. ASSERT_EQ(200, res1->status);
  17577. ASSERT_TRUE(res1->has_header("Last-Modified"));
  17578. // If-Modified-Since with invalid format should not result in 304
  17579. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  17580. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  17581. ASSERT_TRUE(res_bad);
  17582. EXPECT_EQ(200, res_bad->status);
  17583. // If-Range with invalid date format should be treated as mismatch -> full
  17584. // content (200)
  17585. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  17586. {"If-Range", "invalid-date"}};
  17587. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  17588. ASSERT_TRUE(res_ifrange);
  17589. EXPECT_EQ(200, res_ifrange->status);
  17590. svr.stop();
  17591. t.join();
  17592. std::remove(fname);
  17593. }
  17594. TEST(ETagTest, IfRangeWithMalformedETag) {
  17595. using namespace httplib;
  17596. const char *fname = "ifrange_malformed.txt";
  17597. const std::string content = "0123456789";
  17598. {
  17599. std::ofstream ofs(fname);
  17600. ofs << content;
  17601. ASSERT_TRUE(ofs.good());
  17602. }
  17603. Server svr;
  17604. svr.set_mount_point("/static", ".");
  17605. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17606. svr.wait_until_ready();
  17607. Client cli(HOST, PORT);
  17608. // First request: get ETag
  17609. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  17610. ASSERT_TRUE(res1);
  17611. ASSERT_EQ(200, res1->status);
  17612. ASSERT_TRUE(res1->has_header("ETag"));
  17613. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  17614. // full content (200)
  17615. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  17616. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  17617. ASSERT_TRUE(res2);
  17618. EXPECT_EQ(200, res2->status);
  17619. EXPECT_EQ(content, res2->body);
  17620. svr.stop();
  17621. t.join();
  17622. std::remove(fname);
  17623. }
  17624. TEST(ETagTest, ExtremeLargeDateValues) {
  17625. using namespace httplib;
  17626. const char *fname = "ims_extreme_date.txt";
  17627. const char *content = "ims-extreme-date";
  17628. {
  17629. std::ofstream ofs(fname);
  17630. ofs << content;
  17631. ASSERT_TRUE(ofs.good());
  17632. }
  17633. Server svr;
  17634. svr.set_mount_point("/static", ".");
  17635. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17636. svr.wait_until_ready();
  17637. Client cli(HOST, PORT);
  17638. auto res1 = cli.Get(std::string("/static/") + fname);
  17639. ASSERT_TRUE(res1);
  17640. ASSERT_EQ(200, res1->status);
  17641. ASSERT_TRUE(res1->has_header("Last-Modified"));
  17642. // Extremely large year that may overflow date parsing routines.
  17643. Headers h_large_date = {
  17644. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  17645. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  17646. ASSERT_TRUE(res_bad);
  17647. // Expect server to treat this as invalid/mismatch and return full content
  17648. EXPECT_EQ(200, res_bad->status);
  17649. // If-Range with extremely large date should be treated as mismatch -> full
  17650. // content (200)
  17651. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  17652. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  17653. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  17654. ASSERT_TRUE(res_ifrange);
  17655. EXPECT_EQ(200, res_ifrange->status);
  17656. svr.stop();
  17657. t.join();
  17658. std::remove(fname);
  17659. }
  17660. TEST(ETagTest, NegativeFileModificationTime) {
  17661. using namespace httplib;
  17662. const char *fname = "ims_negative_mtime.txt";
  17663. const std::string content = "negative-mtime";
  17664. {
  17665. std::ofstream ofs(fname);
  17666. ofs << content;
  17667. ASSERT_TRUE(ofs.good());
  17668. }
  17669. // Try to set file mtime to a negative value. This may fail on some
  17670. // platforms/filesystems; if it fails, the test will still verify server
  17671. // behaves safely by performing a regular conditional request.
  17672. #if defined(__APPLE__) || defined(__linux__)
  17673. bool set_negative = false;
  17674. do {
  17675. struct timeval times[2];
  17676. // access time: now
  17677. times[0].tv_sec = time(nullptr);
  17678. times[0].tv_usec = 0;
  17679. // modification time: negative (e.g., -1)
  17680. times[1].tv_sec = -1;
  17681. times[1].tv_usec = 0;
  17682. if (utimes(fname, times) == 0) { set_negative = true; }
  17683. } while (0);
  17684. #else
  17685. bool set_negative = false;
  17686. #endif
  17687. Server svr;
  17688. svr.set_mount_point("/static", ".");
  17689. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17690. svr.wait_until_ready();
  17691. Client cli(HOST, PORT);
  17692. auto res1 = cli.Get(std::string("/static/") + fname);
  17693. ASSERT_TRUE(res1);
  17694. ASSERT_EQ(200, res1->status);
  17695. bool has_last_modified = res1->has_header("Last-Modified");
  17696. std::string last_modified;
  17697. if (has_last_modified) {
  17698. last_modified = res1->get_header_value("Last-Modified");
  17699. }
  17700. if (set_negative) {
  17701. // If we successfully set a negative mtime, ensure server returns a
  17702. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  17703. // with an old date and ensure server handles it without crash.
  17704. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  17705. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  17706. ASSERT_TRUE(res2);
  17707. // Behavior may vary; at minimum ensure server responds (200 or 304).
  17708. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  17709. } else {
  17710. // Could not set negative mtime on this platform; fall back to verifying
  17711. // that normal invalid/malformed dates are treated safely (non-304).
  17712. Headers h_bad_date = {
  17713. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  17714. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  17715. ASSERT_TRUE(res_bad);
  17716. EXPECT_EQ(200, res_bad->status);
  17717. }
  17718. svr.stop();
  17719. t.join();
  17720. std::remove(fname);
  17721. }
  17722. //==============================================================================
  17723. // SSE Parsing Tests
  17724. //==============================================================================
  17725. class SSEParsingTest : public ::testing::Test {
  17726. protected:
  17727. // Test helper that mimics SSE parsing behavior
  17728. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  17729. int &retry_ms) {
  17730. // Blank line signals end of event
  17731. if (line.empty() || line == "\r") { return true; }
  17732. // Lines starting with ':' are comments (ignored)
  17733. if (!line.empty() && line[0] == ':') { return false; }
  17734. // Find the colon separator
  17735. auto colon_pos = line.find(':');
  17736. if (colon_pos == std::string::npos) {
  17737. // Line with no colon is treated as field name with empty value
  17738. return false;
  17739. }
  17740. std::string field = line.substr(0, colon_pos);
  17741. std::string value;
  17742. // Value starts after colon, skip optional single space
  17743. if (colon_pos + 1 < line.size()) {
  17744. size_t value_start = colon_pos + 1;
  17745. if (line[value_start] == ' ') { value_start++; }
  17746. value = line.substr(value_start);
  17747. // Remove trailing \r if present
  17748. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  17749. }
  17750. // Handle known fields
  17751. if (field == "event") {
  17752. msg.event = value;
  17753. } else if (field == "data") {
  17754. // Multiple data lines are concatenated with newlines
  17755. if (!msg.data.empty()) { msg.data += "\n"; }
  17756. msg.data += value;
  17757. } else if (field == "id") {
  17758. // Empty id is valid (clears the last event ID)
  17759. msg.id = value;
  17760. } else if (field == "retry") {
  17761. // Parse retry interval in milliseconds
  17762. {
  17763. int v = 0;
  17764. auto res =
  17765. detail::from_chars(value.data(), value.data() + value.size(), v);
  17766. if (res.ec == std::errc{}) { retry_ms = v; }
  17767. }
  17768. }
  17769. // Unknown fields are ignored per SSE spec
  17770. return false;
  17771. }
  17772. };
  17773. // Test: Single-line data
  17774. TEST_F(SSEParsingTest, SingleLineData) {
  17775. sse::SSEMessage msg;
  17776. int retry_ms = 3000;
  17777. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  17778. EXPECT_EQ(msg.data, "hello");
  17779. EXPECT_EQ(msg.event, "message");
  17780. // Blank line ends event
  17781. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  17782. }
  17783. // Test: Multi-line data
  17784. TEST_F(SSEParsingTest, MultiLineData) {
  17785. sse::SSEMessage msg;
  17786. int retry_ms = 3000;
  17787. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  17788. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  17789. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  17790. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  17791. }
  17792. // Test: Custom event types
  17793. TEST_F(SSEParsingTest, CustomEventType) {
  17794. sse::SSEMessage msg;
  17795. int retry_ms = 3000;
  17796. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  17797. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  17798. EXPECT_EQ(msg.event, "update");
  17799. EXPECT_EQ(msg.data, "payload");
  17800. }
  17801. // Test: Event ID handling
  17802. TEST_F(SSEParsingTest, EventIdHandling) {
  17803. sse::SSEMessage msg;
  17804. int retry_ms = 3000;
  17805. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  17806. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  17807. EXPECT_EQ(msg.id, "12345");
  17808. }
  17809. // Test: Empty event ID (clears last event ID)
  17810. TEST_F(SSEParsingTest, EmptyEventId) {
  17811. sse::SSEMessage msg;
  17812. msg.id = "previous";
  17813. int retry_ms = 3000;
  17814. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  17815. EXPECT_EQ(msg.id, "");
  17816. }
  17817. // Test: Retry field parsing
  17818. TEST_F(SSEParsingTest, RetryFieldParsing) {
  17819. sse::SSEMessage msg;
  17820. int retry_ms = 3000;
  17821. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  17822. EXPECT_EQ(retry_ms, 5000);
  17823. }
  17824. // Test: Invalid retry value
  17825. TEST_F(SSEParsingTest, InvalidRetryValue) {
  17826. sse::SSEMessage msg;
  17827. int retry_ms = 3000;
  17828. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  17829. EXPECT_EQ(retry_ms, 3000); // Unchanged
  17830. }
  17831. // Test: Comments (lines starting with :)
  17832. TEST_F(SSEParsingTest, CommentsIgnored) {
  17833. sse::SSEMessage msg;
  17834. int retry_ms = 3000;
  17835. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  17836. EXPECT_EQ(msg.data, "");
  17837. EXPECT_EQ(msg.event, "message");
  17838. }
  17839. // Test: Colon in value
  17840. TEST_F(SSEParsingTest, ColonInValue) {
  17841. sse::SSEMessage msg;
  17842. int retry_ms = 3000;
  17843. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  17844. EXPECT_EQ(msg.data, "hello:world:test");
  17845. }
  17846. // Test: Line with no colon (field name only)
  17847. TEST_F(SSEParsingTest, FieldNameOnly) {
  17848. sse::SSEMessage msg;
  17849. int retry_ms = 3000;
  17850. // According to SSE spec, this is treated as field name with empty value
  17851. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  17852. // Since we don't recognize "data" without colon, data should be empty
  17853. EXPECT_EQ(msg.data, "");
  17854. }
  17855. // Test: Trailing \r handling
  17856. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  17857. sse::SSEMessage msg;
  17858. int retry_ms = 3000;
  17859. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  17860. EXPECT_EQ(msg.data, "hello");
  17861. }
  17862. // Test: Unknown fields ignored
  17863. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  17864. sse::SSEMessage msg;
  17865. int retry_ms = 3000;
  17866. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  17867. EXPECT_EQ(msg.data, "");
  17868. EXPECT_EQ(msg.event, "message");
  17869. }
  17870. // Test: Space after colon is optional
  17871. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  17872. sse::SSEMessage msg1, msg2;
  17873. int retry_ms = 3000;
  17874. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  17875. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  17876. EXPECT_EQ(msg1.data, "hello");
  17877. EXPECT_EQ(msg2.data, "hello");
  17878. }
  17879. // Test: SSEMessage clear
  17880. TEST_F(SSEParsingTest, MessageClear) {
  17881. sse::SSEMessage msg;
  17882. msg.event = "custom";
  17883. msg.data = "some data";
  17884. msg.id = "123";
  17885. msg.clear();
  17886. EXPECT_EQ(msg.event, "message");
  17887. EXPECT_EQ(msg.data, "");
  17888. EXPECT_EQ(msg.id, "");
  17889. }
  17890. // Test: Complete event parsing
  17891. TEST_F(SSEParsingTest, CompleteEventParsing) {
  17892. sse::SSEMessage msg;
  17893. int retry_ms = 3000;
  17894. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  17895. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  17896. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  17897. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  17898. // Blank line ends event
  17899. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  17900. EXPECT_EQ(msg.event, "notification");
  17901. EXPECT_EQ(msg.id, "evt-42");
  17902. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  17903. EXPECT_EQ(retry_ms, 1000);
  17904. }
  17905. //==============================================================================
  17906. // Integration Tests with Server
  17907. //==============================================================================
  17908. class SSEIntegrationTest : public ::testing::Test {
  17909. protected:
  17910. void SetUp() override {
  17911. stop_server_.store(false);
  17912. events_.clear();
  17913. server_ = httplib::detail::make_unique<Server>();
  17914. setup_server();
  17915. start_server();
  17916. }
  17917. void TearDown() override {
  17918. stop_server_.store(true);
  17919. event_cv_.notify_all();
  17920. server_->stop();
  17921. if (server_thread_.joinable()) { server_thread_.join(); }
  17922. }
  17923. void setup_server() {
  17924. // Simple SSE endpoint
  17925. server_->Get("/events", [this](const Request &req, Response &res) {
  17926. auto last_id = req.get_header_value("Last-Event-ID");
  17927. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  17928. res.set_chunked_content_provider(
  17929. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  17930. std::unique_lock<std::mutex> lock(event_mutex_);
  17931. if (event_cv_.wait_for(
  17932. lock, std::chrono::milliseconds(200), [this] {
  17933. return !events_.empty() || stop_server_.load();
  17934. })) {
  17935. if (stop_server_.load()) { return false; }
  17936. if (!events_.empty()) {
  17937. std::string event = events_.front();
  17938. events_.erase(events_.begin());
  17939. sink.write(event.data(), event.size());
  17940. return true;
  17941. }
  17942. }
  17943. return !stop_server_.load();
  17944. });
  17945. });
  17946. // Endpoint that returns error
  17947. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  17948. res.status = 500;
  17949. res.set_content("Internal Server Error", "text/plain");
  17950. });
  17951. // Endpoint for custom event types
  17952. server_->Get("/custom-events", [](const Request &, Response &res) {
  17953. res.set_chunked_content_provider(
  17954. "text/event-stream", [](size_t offset, DataSink &sink) {
  17955. if (offset == 0) {
  17956. std::string event = "event: update\ndata: updated\n\n"
  17957. "event: delete\ndata: deleted\n\n";
  17958. sink.write(event.data(), event.size());
  17959. }
  17960. return false; // End stream after sending
  17961. });
  17962. });
  17963. }
  17964. void start_server() {
  17965. port_ = server_->bind_to_any_port(HOST);
  17966. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  17967. // Wait for server to start
  17968. while (!server_->is_running()) {
  17969. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  17970. }
  17971. }
  17972. int get_port() const { return port_; }
  17973. void send_event(const std::string &event) {
  17974. std::lock_guard<std::mutex> lock(event_mutex_);
  17975. events_.push_back(event);
  17976. event_cv_.notify_all();
  17977. }
  17978. std::unique_ptr<Server> server_;
  17979. std::thread server_thread_;
  17980. std::mutex event_mutex_;
  17981. std::condition_variable event_cv_;
  17982. std::vector<std::string> events_;
  17983. std::atomic<bool> stop_server_{false};
  17984. std::string last_received_event_id_;
  17985. int port_ = 0;
  17986. };
  17987. // Test: Successful connection and on_open callback
  17988. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  17989. // Add a simple endpoint that sends one event and closes
  17990. server_->Get("/simple-event", [](const Request &, Response &res) {
  17991. res.set_chunked_content_provider(
  17992. "text/event-stream", [](size_t offset, DataSink &sink) {
  17993. if (offset == 0) {
  17994. std::string event = "data: hello\n\n";
  17995. sink.write(event.data(), event.size());
  17996. }
  17997. return false; // Close stream after sending
  17998. });
  17999. });
  18000. Client client("localhost", get_port());
  18001. sse::SSEClient sse(client, "/simple-event");
  18002. std::atomic<bool> open_called{false};
  18003. std::atomic<bool> message_received{false};
  18004. sse.on_open([&open_called]() { open_called.store(true); });
  18005. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  18006. if (msg.data == "hello") { message_received.store(true); }
  18007. });
  18008. sse.set_reconnect_interval(100);
  18009. sse.set_max_reconnect_attempts(1);
  18010. // Start async
  18011. sse.start_async();
  18012. // Wait for message to be processed
  18013. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  18014. sse.stop();
  18015. EXPECT_TRUE(open_called.load());
  18016. EXPECT_TRUE(message_received.load());
  18017. }
  18018. // Test: on_message callback
  18019. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  18020. // Endpoint that sends multiple events then closes
  18021. server_->Get("/multi-event", [](const Request &, Response &res) {
  18022. res.set_chunked_content_provider(
  18023. "text/event-stream", [](size_t offset, DataSink &sink) {
  18024. if (offset == 0) {
  18025. std::string events = "data: message1\n\ndata: message2\n\n";
  18026. sink.write(events.data(), events.size());
  18027. }
  18028. return false;
  18029. });
  18030. });
  18031. Client client("localhost", get_port());
  18032. sse::SSEClient sse(client, "/multi-event");
  18033. std::vector<std::string> received_messages;
  18034. std::mutex messages_mutex;
  18035. sse.on_message([&](const sse::SSEMessage &msg) {
  18036. std::lock_guard<std::mutex> lock(messages_mutex);
  18037. received_messages.push_back(msg.data);
  18038. });
  18039. sse.set_reconnect_interval(100);
  18040. sse.set_max_reconnect_attempts(1);
  18041. sse.start_async();
  18042. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  18043. sse.stop();
  18044. std::lock_guard<std::mutex> lock(messages_mutex);
  18045. EXPECT_GE(received_messages.size(), 2u);
  18046. if (received_messages.size() >= 2) {
  18047. EXPECT_EQ(received_messages[0], "message1");
  18048. EXPECT_EQ(received_messages[1], "message2");
  18049. }
  18050. }
  18051. // Test: on_event for specific types
  18052. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  18053. Client client("localhost", get_port());
  18054. sse::SSEClient sse(client, "/custom-events");
  18055. std::atomic<bool> update_received{false};
  18056. std::atomic<bool> delete_received{false};
  18057. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  18058. if (msg.data == "updated") { update_received.store(true); }
  18059. });
  18060. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  18061. if (msg.data == "deleted") { delete_received.store(true); }
  18062. });
  18063. sse.set_max_reconnect_attempts(1);
  18064. sse.start_async();
  18065. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  18066. sse.stop();
  18067. EXPECT_TRUE(update_received.load());
  18068. EXPECT_TRUE(delete_received.load());
  18069. }
  18070. // Test: on_error callback on connection failure
  18071. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  18072. // Connect to a non-existent port
  18073. Client client("localhost", 59999);
  18074. sse::SSEClient sse(client, "/events");
  18075. std::atomic<bool> error_called{false};
  18076. Error received_error = Error::Success;
  18077. sse.on_error([&](Error err) {
  18078. error_called.store(true);
  18079. received_error = err;
  18080. });
  18081. sse.set_reconnect_interval(50);
  18082. sse.set_max_reconnect_attempts(1);
  18083. sse.start_async();
  18084. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  18085. sse.stop();
  18086. EXPECT_TRUE(error_called.load());
  18087. EXPECT_NE(received_error, Error::Success);
  18088. }
  18089. // Test: Last-Event-ID header sent on reconnect
  18090. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  18091. // Endpoint that sends event with ID
  18092. server_->Get("/event-with-id", [](const Request &, Response &res) {
  18093. res.set_chunked_content_provider(
  18094. "text/event-stream", [](size_t offset, DataSink &sink) {
  18095. if (offset == 0) {
  18096. std::string event = "id: evt-123\ndata: test\n\n";
  18097. sink.write(event.data(), event.size());
  18098. }
  18099. return false;
  18100. });
  18101. });
  18102. Client client("localhost", get_port());
  18103. sse::SSEClient sse(client, "/event-with-id");
  18104. std::atomic<bool> id_received{false};
  18105. sse.on_message([&](const sse::SSEMessage &msg) {
  18106. if (!msg.id.empty()) { id_received.store(true); }
  18107. });
  18108. sse.set_reconnect_interval(100);
  18109. sse.set_max_reconnect_attempts(1);
  18110. sse.start_async();
  18111. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  18112. sse.stop();
  18113. EXPECT_TRUE(id_received.load());
  18114. EXPECT_EQ(sse.last_event_id(), "evt-123");
  18115. }
  18116. // Test: Manual stop
  18117. TEST_F(SSEIntegrationTest, ManualStop) {
  18118. // Endpoint that sends one event and stays open briefly
  18119. std::atomic<bool> handler_running{true};
  18120. server_->Get("/stay-open", [&handler_running](const Request &,
  18121. Response &res) {
  18122. res.set_chunked_content_provider(
  18123. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  18124. if (offset == 0) {
  18125. std::string event = "data: connected\n\n";
  18126. sink.write(event.data(), event.size());
  18127. }
  18128. // Keep connection open while handler_running is true
  18129. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  18130. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  18131. }
  18132. return false;
  18133. });
  18134. });
  18135. Client client("localhost", get_port());
  18136. sse::SSEClient sse(client, "/stay-open");
  18137. std::atomic<bool> connected{false};
  18138. sse.on_open([&connected]() { connected.store(true); });
  18139. sse.set_reconnect_interval(100);
  18140. sse.set_max_reconnect_attempts(1);
  18141. sse.start_async();
  18142. // Wait for connection to establish
  18143. for (int i = 0; i < 20 && !connected.load(); ++i) {
  18144. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  18145. }
  18146. EXPECT_TRUE(connected.load());
  18147. EXPECT_TRUE(sse.is_connected());
  18148. // Signal handler to stop
  18149. handler_running.store(false);
  18150. // Stop SSE client
  18151. sse.stop();
  18152. EXPECT_FALSE(sse.is_connected());
  18153. }
  18154. // Test: SSEClient with custom headers
  18155. TEST_F(SSEIntegrationTest, CustomHeaders) {
  18156. // Setup a server endpoint that checks for custom header
  18157. std::atomic<bool> header_received{false};
  18158. server_->Get("/header-check", [&](const Request &req, Response &res) {
  18159. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  18160. header_received.store(true);
  18161. }
  18162. res.set_chunked_content_provider("text/event-stream",
  18163. [](size_t, DataSink &) { return false; });
  18164. });
  18165. Client client("localhost", get_port());
  18166. Headers headers = {{"X-Custom-Header", "custom-value"}};
  18167. sse::SSEClient sse(client, "/header-check", headers);
  18168. sse.set_max_reconnect_attempts(1);
  18169. sse.start_async();
  18170. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  18171. sse.stop();
  18172. EXPECT_TRUE(header_received.load());
  18173. }
  18174. // Test: Reconnect interval configuration
  18175. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  18176. Client client("localhost", get_port());
  18177. sse::SSEClient sse(client, "/events");
  18178. auto &result = sse.set_reconnect_interval(500);
  18179. // Builder pattern should return reference to self
  18180. EXPECT_EQ(&result, &sse);
  18181. }
  18182. // Test: Max reconnect attempts
  18183. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  18184. // Connect to non-existent port to force reconnects
  18185. Client client("localhost", 59998);
  18186. sse::SSEClient sse(client, "/events");
  18187. std::atomic<int> error_count{0};
  18188. sse.on_error([&](Error) { error_count.fetch_add(1); });
  18189. sse.set_reconnect_interval(50);
  18190. sse.set_max_reconnect_attempts(2);
  18191. auto start = std::chrono::steady_clock::now();
  18192. sse.start(); // Blocking call
  18193. auto end = std::chrono::steady_clock::now();
  18194. // Should have stopped after 2 failed attempts
  18195. EXPECT_GE(error_count.load(), 2);
  18196. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  18197. auto duration =
  18198. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  18199. #ifdef _WIN32
  18200. // Windows is much slower for socket connection failures
  18201. EXPECT_LT(duration.count(), 7000);
  18202. #else
  18203. EXPECT_LT(duration.count(), 1000);
  18204. #endif
  18205. }
  18206. // Test: Multi-line data in integration
  18207. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  18208. // Endpoint with multi-line data
  18209. server_->Get("/multiline-data", [](const Request &, Response &res) {
  18210. res.set_chunked_content_provider(
  18211. "text/event-stream", [](size_t offset, DataSink &sink) {
  18212. if (offset == 0) {
  18213. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  18214. sink.write(event.data(), event.size());
  18215. }
  18216. return false;
  18217. });
  18218. });
  18219. Client client("localhost", get_port());
  18220. sse::SSEClient sse(client, "/multiline-data");
  18221. std::string received_data;
  18222. std::mutex data_mutex;
  18223. sse.on_message([&](const sse::SSEMessage &msg) {
  18224. std::lock_guard<std::mutex> lock(data_mutex);
  18225. received_data = msg.data;
  18226. });
  18227. sse.set_reconnect_interval(100);
  18228. sse.set_max_reconnect_attempts(1);
  18229. sse.start_async();
  18230. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  18231. sse.stop();
  18232. std::lock_guard<std::mutex> lock(data_mutex);
  18233. EXPECT_EQ(received_data, "line1\nline2\nline3");
  18234. }
  18235. // Test: Auto-reconnect after server disconnection
  18236. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  18237. std::atomic<int> connection_count{0};
  18238. std::atomic<int> message_count{0};
  18239. // Endpoint that sends one event and closes, forcing reconnect
  18240. server_->Get("/reconnect-test",
  18241. [&connection_count](const Request &, Response &res) {
  18242. connection_count.fetch_add(1);
  18243. res.set_chunked_content_provider(
  18244. "text/event-stream", [](size_t offset, DataSink &sink) {
  18245. if (offset == 0) {
  18246. std::string event = "data: hello\n\n";
  18247. sink.write(event.data(), event.size());
  18248. }
  18249. return false; // Close connection after sending
  18250. });
  18251. });
  18252. Client client("localhost", get_port());
  18253. sse::SSEClient sse(client, "/reconnect-test");
  18254. sse.on_message([&message_count](const sse::SSEMessage &) {
  18255. message_count.fetch_add(1);
  18256. });
  18257. sse.set_reconnect_interval(100);
  18258. sse.set_max_reconnect_attempts(3);
  18259. sse.start_async();
  18260. // Wait long enough for multiple reconnects
  18261. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  18262. sse.stop();
  18263. // Should have connected multiple times (initial + reconnects)
  18264. EXPECT_GE(connection_count.load(), 2);
  18265. // Should have received messages from multiple connections
  18266. EXPECT_GE(message_count.load(), 2);
  18267. }
  18268. // Test: Last-Event-ID sent on reconnect
  18269. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  18270. std::atomic<int> connection_count{0};
  18271. std::vector<std::string> received_last_event_ids;
  18272. std::mutex id_mutex;
  18273. // Endpoint that checks Last-Event-ID header and sends event with ID
  18274. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  18275. int conn = connection_count.fetch_add(1);
  18276. // Capture the Last-Event-ID header from each connection
  18277. {
  18278. std::lock_guard<std::mutex> lock(id_mutex);
  18279. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  18280. }
  18281. res.set_chunked_content_provider(
  18282. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  18283. if (offset == 0) {
  18284. std::string event =
  18285. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  18286. sink.write(event.data(), event.size());
  18287. }
  18288. return false;
  18289. });
  18290. });
  18291. Client client("localhost", get_port());
  18292. sse::SSEClient sse(client, "/reconnect-with-id");
  18293. sse.set_reconnect_interval(100);
  18294. sse.set_max_reconnect_attempts(3);
  18295. sse.start_async();
  18296. // Wait for at least 2 connections
  18297. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  18298. sse.stop();
  18299. // Verify behavior
  18300. std::lock_guard<std::mutex> lock(id_mutex);
  18301. EXPECT_GE(received_last_event_ids.size(), 2u);
  18302. // First connection should have no Last-Event-ID
  18303. if (!received_last_event_ids.empty()) {
  18304. EXPECT_EQ(received_last_event_ids[0], "");
  18305. }
  18306. // Second connection should have Last-Event-ID from first connection
  18307. if (received_last_event_ids.size() >= 2) {
  18308. EXPECT_EQ(received_last_event_ids[1], "event-0");
  18309. }
  18310. }
  18311. // Test: set_headers updates headers used on reconnect
  18312. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  18313. std::vector<std::string> received_tokens;
  18314. std::mutex token_mutex;
  18315. // Endpoint that captures Authorization header
  18316. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  18317. {
  18318. std::lock_guard<std::mutex> lock(token_mutex);
  18319. received_tokens.push_back(req.get_header_value("Authorization"));
  18320. }
  18321. res.set_chunked_content_provider(
  18322. "text/event-stream", [](size_t offset, DataSink &sink) {
  18323. if (offset == 0) {
  18324. std::string event = "data: hello\n\n";
  18325. sink.write(event.data(), event.size());
  18326. }
  18327. return false; // Close connection to trigger reconnect
  18328. });
  18329. });
  18330. Client client("localhost", get_port());
  18331. Headers headers = {{"Authorization", "Bearer old-token"}};
  18332. sse::SSEClient sse(client, "/auth-check", headers);
  18333. // Update headers on each successful connection
  18334. sse.on_open(
  18335. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  18336. sse.set_reconnect_interval(100);
  18337. sse.set_max_reconnect_attempts(3);
  18338. sse.start_async();
  18339. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  18340. sse.stop();
  18341. std::lock_guard<std::mutex> lock(token_mutex);
  18342. ASSERT_GE(received_tokens.size(), 2u);
  18343. // First connection uses original header
  18344. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  18345. // Second connection uses updated header from set_headers
  18346. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  18347. }
  18348. // Test: 401 allows reconnection (so on_error can refresh headers)
  18349. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  18350. std::atomic<int> connection_count{0};
  18351. // Endpoint: returns 401 on first attempt, 200 on second
  18352. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  18353. int conn = connection_count.fetch_add(1);
  18354. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  18355. res.status = StatusCode::Unauthorized_401;
  18356. res.set_content("Unauthorized", "text/plain");
  18357. return;
  18358. }
  18359. res.set_chunked_content_provider(
  18360. "text/event-stream", [](size_t offset, DataSink &sink) {
  18361. if (offset == 0) {
  18362. std::string event = "data: authenticated\n\n";
  18363. sink.write(event.data(), event.size());
  18364. }
  18365. return false;
  18366. });
  18367. });
  18368. Client client("localhost", get_port());
  18369. Headers headers = {{"Authorization", "Bearer expired"}};
  18370. sse::SSEClient sse(client, "/auth-retry", headers);
  18371. std::atomic<bool> message_received{false};
  18372. // Refresh token on error
  18373. sse.on_error(
  18374. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  18375. sse.on_message([&](const sse::SSEMessage &msg) {
  18376. if (msg.data == "authenticated") { message_received.store(true); }
  18377. });
  18378. sse.set_reconnect_interval(100);
  18379. sse.set_max_reconnect_attempts(3);
  18380. sse.start_async();
  18381. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  18382. sse.stop();
  18383. // Should have reconnected after 401 and succeeded with new token
  18384. EXPECT_GE(connection_count.load(), 2);
  18385. EXPECT_TRUE(message_received.load());
  18386. }
  18387. TEST(Issue2318Test, EmptyHostString) {
  18388. {
  18389. httplib::Client cli_empty("", PORT);
  18390. auto res = cli_empty.Get("/");
  18391. ASSERT_FALSE(res);
  18392. EXPECT_EQ(httplib::Error::Connection, res.error());
  18393. }
  18394. {
  18395. httplib::Client cli(" ", PORT);
  18396. auto res = cli.Get("/");
  18397. ASSERT_FALSE(res);
  18398. EXPECT_EQ(httplib::Error::Connection, res.error());
  18399. }
  18400. }
  18401. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18402. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  18403. Server svr;
  18404. // Set a small payload limit (1KB)
  18405. svr.set_payload_max_length(1024);
  18406. svr.Post("/test", [&](const Request &req, Response &res) {
  18407. res.set_content("Body size: " + std::to_string(req.body.size()),
  18408. "text/plain");
  18409. });
  18410. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18411. auto se = detail::scope_exit([&] {
  18412. svr.stop();
  18413. listen_thread.join();
  18414. });
  18415. svr.wait_until_ready();
  18416. // Create data that compresses well but exceeds limit when decompressed
  18417. // 8KB of repeated null bytes compresses to a very small size
  18418. std::string original_data(8 * 1024, '\0');
  18419. // Compress the data using gzip
  18420. std::string compressed_data;
  18421. detail::gzip_compressor compressor;
  18422. compressor.compress(original_data.data(), original_data.size(), true,
  18423. [&](const char *data, size_t size) {
  18424. compressed_data.append(data, size);
  18425. return true;
  18426. });
  18427. // Verify compression worked (compressed should be much smaller)
  18428. ASSERT_LT(compressed_data.size(), original_data.size());
  18429. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  18430. // Send compressed data with Content-Encoding: gzip
  18431. Client cli(HOST, PORT);
  18432. Headers headers = {{"Content-Encoding", "gzip"}};
  18433. auto res =
  18434. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  18435. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  18436. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18437. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  18438. }
  18439. #endif
  18440. // ============================================================================
  18441. // OpenSSL-Specific Tests
  18442. // ============================================================================
  18443. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  18444. X509 *readCertificate(const std::string &strFileName) {
  18445. std::ifstream inStream(strFileName);
  18446. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  18447. std::istreambuf_iterator<char>());
  18448. if (strCertPEM.empty()) return (nullptr);
  18449. BIO *pbCert = BIO_new(BIO_s_mem());
  18450. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  18451. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  18452. BIO_free(pbCert);
  18453. return (pCert);
  18454. }
  18455. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  18456. std::ifstream inStream(strFileName);
  18457. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  18458. std::istreambuf_iterator<char>());
  18459. if (strPrivateKeyPEM.empty()) return (nullptr);
  18460. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  18461. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  18462. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  18463. BIO_free(pbPrivKey);
  18464. return (pPrivateKey);
  18465. }
  18466. TEST(BindServerTest, UpdateCerts) {
  18467. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  18468. int port = svr.bind_to_any_port("0.0.0.0");
  18469. ASSERT_TRUE(svr.is_valid());
  18470. ASSERT_TRUE(port > 0);
  18471. X509 *cert = readCertificate(SERVER_CERT_FILE);
  18472. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  18473. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  18474. ASSERT_TRUE(cert != nullptr);
  18475. ASSERT_TRUE(ca_cert != nullptr);
  18476. ASSERT_TRUE(key != nullptr);
  18477. X509_STORE *cert_store = X509_STORE_new();
  18478. X509_STORE_add_cert(cert_store, ca_cert);
  18479. // svr.update_certs(cert, key, cert_store); // deprecated
  18480. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  18481. CLIENT_CA_CERT_FILE);
  18482. ASSERT_TRUE(svr.is_valid());
  18483. svr.stop();
  18484. X509_STORE_free(cert_store);
  18485. X509_free(cert);
  18486. X509_free(ca_cert);
  18487. EVP_PKEY_free(key);
  18488. }
  18489. // Test that update_certs() updates client CA list correctly
  18490. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  18491. // Start with file-based constructor
  18492. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18493. ASSERT_TRUE(svr.is_valid());
  18494. // Initially no client CA list should be set
  18495. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  18496. ASSERT_TRUE(ssl_ctx != nullptr);
  18497. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  18498. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  18499. EXPECT_EQ(0, count_before);
  18500. // Now update with client CA (PEM string)
  18501. std::string cert_pem, key_pem, ca_pem;
  18502. read_file(SERVER_CERT_FILE, cert_pem);
  18503. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  18504. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  18505. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  18506. ASSERT_TRUE(svr.is_valid());
  18507. // Now client CA list should be set
  18508. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  18509. ASSERT_TRUE(ca_list_after != nullptr);
  18510. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  18511. }
  18512. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  18513. // Test that the file-path SSLServer constructor properly sets the client CA
  18514. // list that is sent to clients during the TLS handshake (CertificateRequest)
  18515. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  18516. ASSERT_TRUE(svr.is_valid());
  18517. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  18518. ASSERT_TRUE(ssl_ctx != nullptr);
  18519. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  18520. ASSERT_TRUE(ca_list != nullptr);
  18521. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  18522. }
  18523. #endif
  18524. // ============================================================================
  18525. // MbedTLS-Specific Tests
  18526. // ============================================================================
  18527. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  18528. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  18529. using namespace httplib::tls;
  18530. // Track if callback was invoked
  18531. bool callback_invoked = false;
  18532. // The callback receives void* ctx which is actually MbedTlsContext*
  18533. // We can access the mbedtls_ssl_config via the context
  18534. auto setup_callback = [&callback_invoked](void *ctx) {
  18535. callback_invoked = true;
  18536. // Cast to MbedTlsContext* to access the ssl config
  18537. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  18538. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  18539. // Use static variables to hold certificate data (simplified for test)
  18540. static mbedtls_x509_crt own_cert;
  18541. static mbedtls_pk_context own_key;
  18542. static mbedtls_x509_crt ca_chain;
  18543. static bool initialized = false;
  18544. if (!initialized) {
  18545. mbedtls_x509_crt_init(&own_cert);
  18546. mbedtls_pk_init(&own_key);
  18547. mbedtls_x509_crt_init(&ca_chain);
  18548. // Load server certificate
  18549. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  18550. return false;
  18551. }
  18552. // Load server private key.
  18553. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  18554. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  18555. #if MBEDTLS_VERSION_MAJOR == 3
  18556. ,
  18557. mbedtls_ctr_drbg_random, nullptr
  18558. #endif
  18559. ) != 0) {
  18560. return false;
  18561. }
  18562. // Load CA chain for client verification
  18563. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  18564. return false;
  18565. }
  18566. initialized = true;
  18567. }
  18568. // Configure the SSL config
  18569. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  18570. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  18571. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  18572. // Set minimum TLS version using mbedTLS native API
  18573. #if MBEDTLS_VERSION_MAJOR >= 3
  18574. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  18575. #else
  18576. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  18577. MBEDTLS_SSL_MINOR_VERSION_3);
  18578. #endif
  18579. return true;
  18580. };
  18581. SSLServer svr(setup_callback);
  18582. ASSERT_TRUE(svr.is_valid());
  18583. ASSERT_TRUE(callback_invoked);
  18584. svr.Get("/test", [&](const Request &req, Response &res) {
  18585. res.set_content("test", "text/plain");
  18586. auto cert = req.peer_cert();
  18587. ASSERT_TRUE(static_cast<bool>(cert));
  18588. auto common_name = cert.subject_cn();
  18589. EXPECT_EQ("Common Name", common_name);
  18590. });
  18591. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  18592. auto se = detail::scope_exit([&] {
  18593. svr.stop();
  18594. t.join();
  18595. ASSERT_FALSE(svr.is_running());
  18596. });
  18597. svr.wait_until_ready();
  18598. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  18599. cli.enable_server_certificate_verification(false);
  18600. cli.set_connection_timeout(30);
  18601. auto res = cli.Get("/test");
  18602. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18603. ASSERT_EQ(StatusCode::OK_200, res->status);
  18604. }
  18605. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  18606. // context (owning mbedtls_ssl_config) before shutting down a still-open
  18607. // keep-alive SSL session, which reads through that config in
  18608. // mbedtls_ssl_close_notify.
  18609. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  18610. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18611. ASSERT_TRUE(svr.is_valid());
  18612. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  18613. res.set_content("test", "text/plain");
  18614. });
  18615. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  18616. auto se = detail::scope_exit([&] {
  18617. svr.stop();
  18618. t.join();
  18619. ASSERT_FALSE(svr.is_running());
  18620. });
  18621. svr.wait_until_ready();
  18622. {
  18623. SSLClient cli(HOST, PORT);
  18624. cli.enable_server_certificate_verification(false);
  18625. cli.set_keep_alive(true);
  18626. auto res = cli.Get("/test");
  18627. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18628. ASSERT_EQ(StatusCode::OK_200, res->status);
  18629. // cli is destructed here with the keep-alive SSL session still open.
  18630. }
  18631. }
  18632. #endif
  18633. // WebSocket Tests
  18634. TEST(WebSocketTest, RSVBitsMustBeZero) {
  18635. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  18636. // defining the meaning of these bits has been negotiated.
  18637. auto make_frame = [](uint8_t first_byte) {
  18638. std::string frame;
  18639. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  18640. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  18641. frame += "Hello";
  18642. return frame;
  18643. };
  18644. // RSV1 set (0x40)
  18645. {
  18646. detail::BufferStream strm;
  18647. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  18648. ws::Opcode opcode;
  18649. std::string payload;
  18650. bool fin;
  18651. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  18652. false, 1024));
  18653. }
  18654. // RSV2 set (0x20)
  18655. {
  18656. detail::BufferStream strm;
  18657. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  18658. ws::Opcode opcode;
  18659. std::string payload;
  18660. bool fin;
  18661. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  18662. false, 1024));
  18663. }
  18664. // RSV3 set (0x10)
  18665. {
  18666. detail::BufferStream strm;
  18667. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  18668. ws::Opcode opcode;
  18669. std::string payload;
  18670. bool fin;
  18671. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  18672. false, 1024));
  18673. }
  18674. // No RSV bits set - should succeed
  18675. {
  18676. detail::BufferStream strm;
  18677. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  18678. ws::Opcode opcode;
  18679. std::string payload;
  18680. bool fin;
  18681. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  18682. false, 1024));
  18683. EXPECT_EQ(ws::Opcode::Text, opcode);
  18684. EXPECT_EQ("Hello", payload);
  18685. EXPECT_TRUE(fin);
  18686. }
  18687. }
  18688. TEST(WebSocketTest, ControlFrameValidation) {
  18689. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  18690. // payload length <= 125.
  18691. // Ping with FIN=0 - must be rejected
  18692. {
  18693. detail::BufferStream strm;
  18694. std::string frame;
  18695. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  18696. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  18697. strm.write(frame.data(), frame.size());
  18698. ws::Opcode opcode;
  18699. std::string payload;
  18700. bool fin;
  18701. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  18702. false, 1024));
  18703. }
  18704. // Close with FIN=0 - must be rejected
  18705. {
  18706. detail::BufferStream strm;
  18707. std::string frame;
  18708. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  18709. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  18710. strm.write(frame.data(), frame.size());
  18711. ws::Opcode opcode;
  18712. std::string payload;
  18713. bool fin;
  18714. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  18715. false, 1024));
  18716. }
  18717. // Ping with payload_len=126 (extended length) - must be rejected
  18718. {
  18719. detail::BufferStream strm;
  18720. std::string frame;
  18721. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  18722. frame += static_cast<char>(126); // payload_len=126 (>125)
  18723. frame += static_cast<char>(0x00); // extended length high byte
  18724. frame += static_cast<char>(126); // extended length low byte
  18725. frame += std::string(126, 'x');
  18726. strm.write(frame.data(), frame.size());
  18727. ws::Opcode opcode;
  18728. std::string payload;
  18729. bool fin;
  18730. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  18731. false, 1024));
  18732. }
  18733. // Ping with FIN=1 and payload_len=125 - should succeed
  18734. {
  18735. detail::BufferStream strm;
  18736. std::string frame;
  18737. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  18738. frame += static_cast<char>(125); // payload_len=125
  18739. frame += std::string(125, 'x');
  18740. strm.write(frame.data(), frame.size());
  18741. ws::Opcode opcode;
  18742. std::string payload;
  18743. bool fin;
  18744. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  18745. false, 1024));
  18746. EXPECT_EQ(ws::Opcode::Ping, opcode);
  18747. EXPECT_EQ(125u, payload.size());
  18748. EXPECT_TRUE(fin);
  18749. }
  18750. }
  18751. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  18752. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  18753. // length MUST be 0.
  18754. // MSB set - must be rejected
  18755. {
  18756. detail::BufferStream strm;
  18757. std::string frame;
  18758. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  18759. frame += static_cast<char>(127); // 64-bit extended length
  18760. frame += static_cast<char>(0x80); // MSB set (invalid)
  18761. frame += std::string(7, '\0'); // remaining 7 bytes of length
  18762. strm.write(frame.data(), frame.size());
  18763. ws::Opcode opcode;
  18764. std::string payload;
  18765. bool fin;
  18766. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  18767. false, 1024));
  18768. }
  18769. // MSB clear - should pass length parsing (will be rejected by max_len,
  18770. // but that's a different check; use a small length to verify)
  18771. {
  18772. detail::BufferStream strm;
  18773. std::string frame;
  18774. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  18775. frame += static_cast<char>(127); // 64-bit extended length
  18776. frame += std::string(7, '\0'); // high bytes = 0
  18777. frame += static_cast<char>(0x03); // length = 3
  18778. frame += "abc";
  18779. strm.write(frame.data(), frame.size());
  18780. ws::Opcode opcode;
  18781. std::string payload;
  18782. bool fin;
  18783. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  18784. false, 1024));
  18785. EXPECT_EQ(ws::Opcode::Text, opcode);
  18786. EXPECT_EQ("abc", payload);
  18787. }
  18788. }
  18789. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  18790. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  18791. // Valid UTF-8
  18792. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  18793. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  18794. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  18795. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  18796. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  18797. // Invalid UTF-8
  18798. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  18799. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  18800. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  18801. EXPECT_FALSE(
  18802. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  18803. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  18804. }
  18805. TEST(WebSocketTest, ConnectAndDisconnect) {
  18806. Server svr;
  18807. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  18808. std::string msg;
  18809. while (ws.read(msg)) {}
  18810. });
  18811. auto port = svr.bind_to_any_port(HOST);
  18812. std::thread t([&]() { svr.listen_after_bind(); });
  18813. svr.wait_until_ready();
  18814. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  18815. auto res = client.connect();
  18816. ASSERT_TRUE(res);
  18817. EXPECT_EQ(Error::Success, res.error());
  18818. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  18819. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  18820. EXPECT_TRUE(client.is_open());
  18821. client.close();
  18822. EXPECT_FALSE(client.is_open());
  18823. svr.stop();
  18824. t.join();
  18825. }
  18826. TEST(WebSocketTest, ValidURL) {
  18827. ws::WebSocketClient ws1("ws://localhost:8080/path");
  18828. EXPECT_TRUE(ws1.is_valid());
  18829. ws::WebSocketClient ws2("ws://example.com/path");
  18830. EXPECT_TRUE(ws2.is_valid());
  18831. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  18832. EXPECT_TRUE(ws3.is_valid());
  18833. #ifdef CPPHTTPLIB_SSL_ENABLED
  18834. ws::WebSocketClient wss1("wss://example.com/path");
  18835. EXPECT_TRUE(wss1.is_valid());
  18836. ws::WebSocketClient wss2("wss://example.com:443/path");
  18837. EXPECT_TRUE(wss2.is_valid());
  18838. #endif
  18839. }
  18840. TEST(WebSocketTest, InvalidURL) {
  18841. // No scheme
  18842. ws::WebSocketClient ws1("localhost:8080/path");
  18843. EXPECT_FALSE(ws1.is_valid());
  18844. // No path
  18845. ws::WebSocketClient ws2("ws://localhost:8080");
  18846. EXPECT_FALSE(ws2.is_valid());
  18847. // Empty string
  18848. ws::WebSocketClient ws3("");
  18849. EXPECT_FALSE(ws3.is_valid());
  18850. // Missing host
  18851. ws::WebSocketClient ws4("ws://:8080/path");
  18852. EXPECT_FALSE(ws4.is_valid());
  18853. // Port number overflow — should not crash
  18854. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  18855. EXPECT_FALSE(ws5.is_valid());
  18856. // Port out of range
  18857. ws::WebSocketClient ws6("ws://localhost:99999/path");
  18858. EXPECT_FALSE(ws6.is_valid());
  18859. }
  18860. TEST(WebSocketTest, UnsupportedScheme) {
  18861. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  18862. ws::WebSocketClient ws1("http://localhost:8080/path");
  18863. EXPECT_FALSE(ws1.is_valid());
  18864. ws::WebSocketClient ws2("https://localhost:8080/path");
  18865. EXPECT_FALSE(ws2.is_valid());
  18866. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  18867. EXPECT_FALSE(ws3.is_valid());
  18868. #else
  18869. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  18870. std::invalid_argument);
  18871. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  18872. std::invalid_argument);
  18873. #endif
  18874. }
  18875. TEST(WebSocketTest, ConnectWhenInvalid) {
  18876. ws::WebSocketClient ws("not a valid url");
  18877. EXPECT_FALSE(ws.is_valid());
  18878. auto res = ws.connect();
  18879. EXPECT_FALSE(res);
  18880. EXPECT_EQ(Error::Connection, res.error());
  18881. EXPECT_EQ(-1, res.status());
  18882. }
  18883. TEST(WebSocketTest, ConnectRefusedReportsError) {
  18884. // Grab a port that is free, then close it again so nothing listens there
  18885. Server svr;
  18886. auto port = svr.bind_to_any_port(HOST);
  18887. svr.stop();
  18888. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  18889. auto res = client.connect();
  18890. ASSERT_FALSE(res);
  18891. EXPECT_EQ(Error::Connection, res.error());
  18892. EXPECT_EQ(-1, res.status());
  18893. }
  18894. TEST(WebSocketTest, DefaultPort) {
  18895. ws::WebSocketClient ws1("ws://example.com/path");
  18896. EXPECT_TRUE(ws1.is_valid());
  18897. // ws:// defaults to port 80 (verified by successful parse)
  18898. #ifdef CPPHTTPLIB_SSL_ENABLED
  18899. ws::WebSocketClient ws2("wss://example.com/path");
  18900. EXPECT_TRUE(ws2.is_valid());
  18901. // wss:// defaults to port 443 (verified by successful parse)
  18902. #endif
  18903. }
  18904. TEST(WebSocketTest, IPv6LiteralAddress) {
  18905. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  18906. EXPECT_TRUE(ws1.is_valid());
  18907. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  18908. EXPECT_TRUE(ws2.is_valid());
  18909. }
  18910. TEST(WebSocketTest, ComplexPath) {
  18911. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  18912. EXPECT_TRUE(ws1.is_valid());
  18913. ws::WebSocketClient ws2("ws://localhost:8080/");
  18914. EXPECT_TRUE(ws2.is_valid());
  18915. }
  18916. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  18917. Server svr;
  18918. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  18919. std::string msg;
  18920. while (ws.read(msg)) {}
  18921. });
  18922. auto port = svr.bind_to_any_port(HOST);
  18923. std::thread t([&]() { svr.listen_after_bind(); });
  18924. svr.wait_until_ready();
  18925. auto another_host = "example.com";
  18926. auto wrong_ip = "192.0.2.1";
  18927. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  18928. client.set_hostname_addr_map({{another_host, wrong_ip}});
  18929. ASSERT_TRUE(client.connect());
  18930. EXPECT_TRUE(client.is_open());
  18931. client.close();
  18932. svr.stop();
  18933. t.join();
  18934. }
  18935. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  18936. Server svr;
  18937. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  18938. std::string msg;
  18939. while (ws.read(msg)) {}
  18940. });
  18941. auto port = svr.bind_to_any_port(HOST);
  18942. std::thread t([&]() { svr.listen_after_bind(); });
  18943. svr.wait_until_ready();
  18944. auto wrong_ip = "192.0.2.1";
  18945. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  18946. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  18947. client.set_connection_timeout(1);
  18948. client.set_read_timeout(1);
  18949. client.set_write_timeout(1);
  18950. EXPECT_FALSE(client.connect());
  18951. EXPECT_FALSE(client.is_open());
  18952. svr.stop();
  18953. t.join();
  18954. }
  18955. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  18956. // A mapped value that is not an IP literal must be resolved. HOST resolves
  18957. // from the hosts file, so this test needs no external DNS. "target.invalid"
  18958. // (RFC 6761) is only a map key and the Host header value.
  18959. auto host = "target.invalid";
  18960. Server svr;
  18961. std::string received_host;
  18962. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  18963. received_host = req.get_header_value("Host");
  18964. std::string msg;
  18965. while (ws.read(msg)) {}
  18966. });
  18967. auto port = svr.bind_to_any_port(HOST);
  18968. std::thread t([&]() { svr.listen_after_bind(); });
  18969. // ASSERT_* below returns from the test body, which would leave t joinable
  18970. // and make ~thread call std::terminate.
  18971. auto se = detail::scope_exit([&] {
  18972. svr.stop();
  18973. if (t.joinable()) { t.join(); }
  18974. });
  18975. svr.wait_until_ready();
  18976. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  18977. std::to_string(port) + "/ws");
  18978. client.set_hostname_addr_map({{host, HOST}});
  18979. ASSERT_TRUE(client.connect());
  18980. EXPECT_TRUE(client.is_open());
  18981. client.close();
  18982. svr.stop();
  18983. t.join();
  18984. // The mapping only redirects the connection; the identity stays host_.
  18985. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  18986. }
  18987. class WebSocketIntegrationTest : public ::testing::Test {
  18988. protected:
  18989. void SetUp() override {
  18990. server_ = httplib::detail::make_unique<Server>();
  18991. setup_server();
  18992. start_server();
  18993. }
  18994. void TearDown() override {
  18995. server_->stop();
  18996. if (server_thread_.joinable()) { server_thread_.join(); }
  18997. }
  18998. void setup_server() {
  18999. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  19000. std::string msg;
  19001. ws::ReadResult ret;
  19002. while ((ret = ws.read(msg))) {
  19003. if (ret == ws::Binary) {
  19004. ws.send(msg.data(), msg.size());
  19005. } else {
  19006. ws.send(msg);
  19007. }
  19008. }
  19009. });
  19010. server_->WebSocket("/ws-echo-string",
  19011. [](const Request &, ws::WebSocket &ws) {
  19012. std::string msg;
  19013. while (ws.read(msg)) {
  19014. ws.send("echo: " + msg);
  19015. }
  19016. });
  19017. server_->WebSocket(
  19018. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  19019. // Echo back request metadata
  19020. ws.send("path:" + req.path);
  19021. ws.send("header:" + req.get_header_value("X-Test-Header"));
  19022. std::string msg;
  19023. while (ws.read(msg)) {}
  19024. });
  19025. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  19026. std::string msg;
  19027. ws.read(msg); // wait for a message
  19028. ws.close();
  19029. });
  19030. server_->WebSocket("/ws-close-status",
  19031. [](const Request &, ws::WebSocket &ws) {
  19032. std::string msg;
  19033. ws.read(msg); // wait for a message
  19034. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  19035. });
  19036. server_->WebSocket(
  19037. "/ws-subprotocol",
  19038. [](const Request &, ws::WebSocket &ws) {
  19039. std::string msg;
  19040. while (ws.read(msg)) {
  19041. ws.send(msg);
  19042. }
  19043. },
  19044. [](const std::vector<std::string> &protocols) -> std::string {
  19045. for (const auto &p : protocols) {
  19046. if (p == "graphql-ws") { return p; }
  19047. }
  19048. return "";
  19049. });
  19050. }
  19051. void start_server() {
  19052. port_ = server_->bind_to_any_port(HOST);
  19053. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  19054. server_->wait_until_ready();
  19055. }
  19056. std::unique_ptr<Server> server_;
  19057. std::thread server_thread_;
  19058. int port_ = 0;
  19059. };
  19060. TEST_F(WebSocketIntegrationTest, TextEcho) {
  19061. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19062. "/ws-echo");
  19063. ASSERT_TRUE(client.connect());
  19064. ASSERT_TRUE(client.is_open());
  19065. ASSERT_TRUE(client.send("Hello WebSocket"));
  19066. std::string msg;
  19067. EXPECT_EQ(ws::Text, client.read(msg));
  19068. EXPECT_EQ("Hello WebSocket", msg);
  19069. client.close();
  19070. }
  19071. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  19072. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19073. "/ws-echo");
  19074. ASSERT_TRUE(client.connect());
  19075. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  19076. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  19077. std::string msg;
  19078. EXPECT_EQ(ws::Binary, client.read(msg));
  19079. EXPECT_EQ(binary_data, msg);
  19080. client.close();
  19081. }
  19082. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  19083. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19084. "/ws-echo");
  19085. ASSERT_TRUE(client.connect());
  19086. for (int i = 0; i < 10; i++) {
  19087. auto text = "message " + std::to_string(i);
  19088. ASSERT_TRUE(client.send(text));
  19089. std::string msg;
  19090. ASSERT_TRUE(client.read(msg));
  19091. EXPECT_EQ(text, msg);
  19092. }
  19093. client.close();
  19094. }
  19095. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  19096. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19097. "/ws-close");
  19098. ASSERT_TRUE(client.connect());
  19099. // Send a message to trigger the server to close
  19100. ASSERT_TRUE(client.send("trigger close"));
  19101. // The server will close, so read should return false
  19102. std::string msg;
  19103. EXPECT_FALSE(client.read(msg));
  19104. EXPECT_FALSE(client.is_open());
  19105. }
  19106. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  19107. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19108. "/ws-echo");
  19109. ASSERT_TRUE(client.connect());
  19110. // 128KB message
  19111. std::string large_data(128 * 1024, 'X');
  19112. ASSERT_TRUE(client.send(large_data));
  19113. std::string msg;
  19114. ASSERT_TRUE(client.read(msg));
  19115. EXPECT_EQ(large_data, msg);
  19116. client.close();
  19117. }
  19118. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  19119. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19120. "/ws-echo");
  19121. ASSERT_TRUE(client.connect());
  19122. const int num_threads = 4;
  19123. std::vector<std::thread> threads;
  19124. std::atomic<int> send_count{0};
  19125. for (int t = 0; t < num_threads; t++) {
  19126. threads.emplace_back([&client, &send_count, t]() {
  19127. for (int i = 0; i < 5; i++) {
  19128. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  19129. if (client.send(text)) { send_count++; }
  19130. }
  19131. });
  19132. }
  19133. for (auto &th : threads) {
  19134. th.join();
  19135. }
  19136. int received = 0;
  19137. std::string msg;
  19138. while (received < send_count.load()) {
  19139. if (!client.read(msg)) { break; }
  19140. received++;
  19141. }
  19142. EXPECT_EQ(send_count.load(), received);
  19143. client.close();
  19144. }
  19145. TEST_F(WebSocketIntegrationTest, ReadString) {
  19146. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19147. "/ws-echo-string");
  19148. ASSERT_TRUE(client.connect());
  19149. ASSERT_TRUE(client.send("hello"));
  19150. std::string msg;
  19151. ASSERT_TRUE(client.read(msg));
  19152. EXPECT_EQ("echo: hello", msg);
  19153. ASSERT_TRUE(client.send("world"));
  19154. ASSERT_TRUE(client.read(msg));
  19155. EXPECT_EQ("echo: world", msg);
  19156. client.close();
  19157. }
  19158. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  19159. Headers headers = {{"X-Test-Header", "test-value"}};
  19160. ws::WebSocketClient client(
  19161. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  19162. ASSERT_TRUE(client.connect());
  19163. std::string msg;
  19164. ASSERT_TRUE(client.read(msg));
  19165. EXPECT_EQ("path:/ws-request-info", msg);
  19166. ASSERT_TRUE(client.read(msg));
  19167. EXPECT_EQ("header:test-value", msg);
  19168. client.close();
  19169. }
  19170. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  19171. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19172. "/ws-echo");
  19173. client.set_read_timeout(1, 0); // 1 second
  19174. ASSERT_TRUE(client.connect());
  19175. // Don't send anything — server echo handler waits for a message,
  19176. // so read() should time out and return false.
  19177. std::string msg;
  19178. EXPECT_FALSE(client.read(msg));
  19179. }
  19180. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  19181. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19182. "/ws-echo");
  19183. client.set_read_timeout(5, 0);
  19184. ASSERT_TRUE(client.connect());
  19185. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  19186. // The server should reject it and close the connection.
  19187. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  19188. client.send(oversized);
  19189. // The server's read() should have failed due to payload limit,
  19190. // so our read() should return false (connection closed).
  19191. std::string msg;
  19192. EXPECT_FALSE(client.read(msg));
  19193. }
  19194. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  19195. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19196. "/ws-echo");
  19197. client.set_read_timeout(10, 0);
  19198. ASSERT_TRUE(client.connect());
  19199. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  19200. // This should succeed.
  19201. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  19202. ASSERT_TRUE(client.send(at_limit));
  19203. std::string msg;
  19204. ASSERT_TRUE(client.read(msg));
  19205. EXPECT_EQ(at_limit.size(), msg.size());
  19206. client.close();
  19207. }
  19208. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  19209. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19210. "/nonexistent");
  19211. auto res = client.connect();
  19212. EXPECT_FALSE(res);
  19213. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  19214. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  19215. EXPECT_FALSE(client.is_open());
  19216. }
  19217. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  19218. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19219. "/ws-echo");
  19220. ASSERT_TRUE(client.connect());
  19221. ASSERT_TRUE(client.send(""));
  19222. std::string msg;
  19223. EXPECT_EQ(ws::Text, client.read(msg));
  19224. EXPECT_EQ("", msg);
  19225. client.close();
  19226. }
  19227. TEST_F(WebSocketIntegrationTest, Reconnect) {
  19228. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19229. "/ws-echo");
  19230. // First connection
  19231. ASSERT_TRUE(client.connect());
  19232. ASSERT_TRUE(client.send("first"));
  19233. std::string msg;
  19234. ASSERT_TRUE(client.read(msg));
  19235. EXPECT_EQ("first", msg);
  19236. client.close();
  19237. EXPECT_FALSE(client.is_open());
  19238. // Reconnect using the same client object
  19239. ASSERT_TRUE(client.connect());
  19240. ASSERT_TRUE(client.is_open());
  19241. ASSERT_TRUE(client.send("second"));
  19242. ASSERT_TRUE(client.read(msg));
  19243. EXPECT_EQ("second", msg);
  19244. client.close();
  19245. }
  19246. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  19247. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19248. "/ws-close-status");
  19249. ASSERT_TRUE(client.connect());
  19250. // Trigger the server to close with GoingAway status
  19251. ASSERT_TRUE(client.send("trigger"));
  19252. // read() should return false after receiving the close frame
  19253. std::string msg;
  19254. EXPECT_FALSE(client.read(msg));
  19255. EXPECT_FALSE(client.is_open());
  19256. }
  19257. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  19258. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19259. "/ws-echo");
  19260. ASSERT_TRUE(client.connect());
  19261. client.close(ws::CloseStatus::GoingAway, "client leaving");
  19262. EXPECT_FALSE(client.is_open());
  19263. }
  19264. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  19265. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  19266. ws::WebSocketClient client(
  19267. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  19268. ASSERT_TRUE(client.connect());
  19269. // Server should have selected graphql-ws
  19270. EXPECT_EQ("graphql-ws", client.subprotocol());
  19271. client.close();
  19272. }
  19273. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  19274. Headers headers;
  19275. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  19276. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  19277. ws::WebSocketClient client(
  19278. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  19279. ASSERT_TRUE(client.connect());
  19280. // The offer on the second field line counts too, so graphql-ws is selected
  19281. EXPECT_EQ("graphql-ws", client.subprotocol());
  19282. client.close();
  19283. }
  19284. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  19285. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  19286. ws::WebSocketClient client(
  19287. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  19288. ASSERT_TRUE(client.connect());
  19289. // Server should not have selected any subprotocol
  19290. EXPECT_TRUE(client.subprotocol().empty());
  19291. client.close();
  19292. }
  19293. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  19294. // Connect without requesting any subprotocol
  19295. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19296. "/ws-subprotocol");
  19297. ASSERT_TRUE(client.connect());
  19298. EXPECT_TRUE(client.subprotocol().empty());
  19299. client.close();
  19300. }
  19301. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  19302. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19303. "/ws-echo");
  19304. client.set_tcp_nodelay(true);
  19305. client.set_connection_timeout(3, 0);
  19306. bool socket_options_called = false;
  19307. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  19308. ASSERT_TRUE(client.connect());
  19309. ASSERT_TRUE(client.is_open());
  19310. EXPECT_TRUE(socket_options_called);
  19311. ASSERT_TRUE(client.send("hello"));
  19312. std::string msg;
  19313. auto result = client.read(msg);
  19314. EXPECT_EQ(result, ws::ReadResult::Text);
  19315. EXPECT_EQ(msg, "hello");
  19316. client.close();
  19317. }
  19318. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  19319. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19320. "/ws-echo");
  19321. client.set_connection_timeout(std::chrono::seconds(3));
  19322. client.set_write_timeout(std::chrono::seconds(3));
  19323. // A sub-second remainder exercises the seconds/microseconds split.
  19324. client.set_read_timeout(std::chrono::milliseconds(1500));
  19325. ASSERT_TRUE(client.connect());
  19326. auto start = std::chrono::steady_clock::now();
  19327. std::string msg;
  19328. EXPECT_EQ(client.read(msg), ws::ReadResult::Fail);
  19329. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  19330. std::chrono::steady_clock::now() - start)
  19331. .count();
  19332. // Above 1s so that dropping the microseconds half of the split fails here,
  19333. // and well under the 300s default so that ignoring the setter fails too.
  19334. EXPECT_GE(elapsed, 1400);
  19335. EXPECT_LT(elapsed, 30000);
  19336. }
  19337. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  19338. Server svr;
  19339. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  19340. if (!req.has_header("Authorization")) {
  19341. res.status = StatusCode::Unauthorized_401;
  19342. res.set_content("Unauthorized", "text/plain");
  19343. return Server::HandlerResponse::Handled;
  19344. }
  19345. return Server::HandlerResponse::Unhandled;
  19346. });
  19347. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  19348. std::string msg;
  19349. while (ws.read(msg)) {
  19350. ws.send(msg);
  19351. }
  19352. });
  19353. auto port = svr.bind_to_any_port("localhost");
  19354. std::thread t([&]() { svr.listen_after_bind(); });
  19355. svr.wait_until_ready();
  19356. // Without Authorization header - should be rejected before upgrade
  19357. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  19358. EXPECT_FALSE(client1.connect());
  19359. // With Authorization header - should succeed
  19360. Headers headers = {{"Authorization", "Bearer token123"}};
  19361. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  19362. headers);
  19363. ASSERT_TRUE(client2.connect());
  19364. ASSERT_TRUE(client2.send("hello"));
  19365. std::string msg;
  19366. ASSERT_TRUE(client2.read(msg));
  19367. EXPECT_EQ("hello", msg);
  19368. client2.close();
  19369. svr.stop();
  19370. t.join();
  19371. }
  19372. TEST(WebSocketTest, QueryStringInHandshake) {
  19373. Server svr;
  19374. std::mutex mtx;
  19375. std::string received_target;
  19376. std::string received_token;
  19377. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  19378. {
  19379. std::lock_guard<std::mutex> lock(mtx);
  19380. received_target = req.target;
  19381. if (req.has_param("token")) {
  19382. received_token = req.get_param_value("token");
  19383. }
  19384. }
  19385. std::string msg;
  19386. while (ws.read(msg)) {
  19387. ws.send(msg);
  19388. }
  19389. });
  19390. auto port = svr.bind_to_any_port("localhost");
  19391. std::thread t([&]() { svr.listen_after_bind(); });
  19392. svr.wait_until_ready();
  19393. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  19394. "/ws?token=ABC&session=123");
  19395. ASSERT_TRUE(client.connect());
  19396. // Round-trip ensures the handler has run and captured the request.
  19397. ASSERT_TRUE(client.send("hello"));
  19398. std::string msg;
  19399. ASSERT_TRUE(client.read(msg));
  19400. EXPECT_EQ("hello", msg);
  19401. client.close();
  19402. {
  19403. std::lock_guard<std::mutex> lock(mtx);
  19404. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  19405. EXPECT_EQ("ABC", received_token);
  19406. }
  19407. svr.stop();
  19408. t.join();
  19409. }
  19410. // Run a handshake against a throwaway server and hand the request the server
  19411. // received back to the caller, so tests can assert on the headers the client
  19412. // actually put on the wire.
  19413. static void capture_websocket_handshake_request(
  19414. const Headers &client_headers,
  19415. std::function<void(const Request &, int port)> verify) {
  19416. Server svr;
  19417. std::mutex mtx;
  19418. Request received;
  19419. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  19420. {
  19421. std::lock_guard<std::mutex> lock(mtx);
  19422. received = req;
  19423. }
  19424. std::string msg;
  19425. while (ws.read(msg)) {
  19426. ws.send(msg);
  19427. }
  19428. });
  19429. auto port = svr.bind_to_any_port("localhost");
  19430. std::thread t([&]() { svr.listen_after_bind(); });
  19431. auto se = detail::scope_exit([&] {
  19432. svr.stop();
  19433. t.join();
  19434. });
  19435. svr.wait_until_ready();
  19436. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  19437. client_headers);
  19438. ASSERT_TRUE(client.connect());
  19439. ASSERT_TRUE(client.send("hello"));
  19440. std::string msg;
  19441. ASSERT_TRUE(client.read(msg));
  19442. client.close();
  19443. {
  19444. std::lock_guard<std::mutex> lock(mtx);
  19445. verify(received, port);
  19446. }
  19447. }
  19448. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  19449. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  19450. // Non-default port must be present in the Host header. Default ports
  19451. // (80/443) are omitted; that logic is covered by
  19452. // MakeHostAndPortStringTest.
  19453. EXPECT_EQ("localhost:" + std::to_string(port),
  19454. req.get_header_value("Host"));
  19455. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  19456. req.get_header_value("User-Agent"));
  19457. EXPECT_FALSE(req.has_header("Accept"));
  19458. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  19459. EXPECT_FALSE(req.has_header("Content-Length"));
  19460. });
  19461. }
  19462. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  19463. capture_websocket_handshake_request(
  19464. {{"Host", "example.com"},
  19465. {"User-Agent", "custom-agent"},
  19466. {"X-Custom", "value"}},
  19467. [](const Request &req, int) {
  19468. EXPECT_EQ("example.com", req.get_header_value("Host"));
  19469. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  19470. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  19471. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  19472. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  19473. });
  19474. }
  19475. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  19476. capture_websocket_handshake_request(
  19477. {{"Upgrade", "bogus"},
  19478. {"Connection", "close"},
  19479. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  19480. {"Sec-WebSocket-Version", "8"}},
  19481. [](const Request &req, int) {
  19482. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  19483. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  19484. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  19485. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  19486. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  19487. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  19488. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  19489. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  19490. req.get_header_value("Sec-WebSocket-Key"));
  19491. });
  19492. }
  19493. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  19494. // A header the client refuses to send must abort the handshake before any
  19495. // part of it reaches the wire; a lone request line would otherwise sit in
  19496. // the peer's buffer as a truncated request.
  19497. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  19498. ASSERT_NE(INVALID_SOCKET, srv);
  19499. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  19500. sockaddr_in addr{};
  19501. addr.sin_family = AF_INET;
  19502. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  19503. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  19504. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  19505. ASSERT_EQ(0, ::listen(srv, 1));
  19506. sockaddr_in bound{};
  19507. socklen_t bound_len = sizeof(bound);
  19508. ASSERT_EQ(
  19509. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  19510. auto port = ntohs(bound.sin_port);
  19511. ssize_t received = -1;
  19512. std::thread t([&] {
  19513. // Bound every blocking call so a regression fails the test with a bad
  19514. // value instead of hanging the suite.
  19515. fd_set rfds;
  19516. FD_ZERO(&rfds);
  19517. FD_SET(srv, &rfds);
  19518. timeval tv{5, 0};
  19519. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  19520. 0) {
  19521. return;
  19522. }
  19523. sockaddr_in cli_addr{};
  19524. socklen_t cli_len = sizeof(cli_addr);
  19525. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  19526. if (cli == INVALID_SOCKET) { return; }
  19527. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  19528. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  19529. char buf[4096];
  19530. received = ::recv(cli, buf, sizeof(buf), 0);
  19531. });
  19532. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  19533. // connect() has already shut the socket down by the time it returns false,
  19534. // so the peer sees EOF without waiting for the client to be destroyed.
  19535. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  19536. {{"X-Bad", "a\r\nInjected: 1"}});
  19537. EXPECT_FALSE(client.connect());
  19538. t.join();
  19539. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  19540. EXPECT_EQ(0, received);
  19541. }
  19542. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  19543. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  19544. // contains "upgrade" as a substring is a different token and must not
  19545. // start a WebSocket handshake.
  19546. auto make_request = [](const std::vector<std::string> &connection_values) {
  19547. Request req;
  19548. req.method = "GET";
  19549. req.headers.emplace("Upgrade", "websocket");
  19550. for (const auto &value : connection_values) {
  19551. req.headers.emplace("Connection", value);
  19552. }
  19553. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  19554. req.headers.emplace("Sec-WebSocket-Version", "13");
  19555. return req;
  19556. };
  19557. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  19558. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  19559. EXPECT_TRUE(
  19560. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  19561. EXPECT_TRUE(
  19562. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  19563. EXPECT_TRUE(
  19564. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  19565. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  19566. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  19567. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  19568. EXPECT_FALSE(
  19569. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  19570. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  19571. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  19572. }
  19573. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  19574. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  19575. // asks recipients to match each protocol-name case-insensitively, and RFC
  19576. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  19577. // client naming websocket alongside another protocol, or on a second field
  19578. // line, is offering websocket; a value that merely contains "websocket" as a
  19579. // substring is a different protocol name and is not.
  19580. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  19581. Request req;
  19582. req.method = "GET";
  19583. for (const auto &value : upgrade_values) {
  19584. req.headers.emplace("Upgrade", value);
  19585. }
  19586. req.headers.emplace("Connection", "Upgrade");
  19587. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  19588. req.headers.emplace("Sec-WebSocket-Version", "13");
  19589. return req;
  19590. };
  19591. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  19592. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  19593. EXPECT_TRUE(
  19594. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  19595. EXPECT_TRUE(
  19596. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  19597. EXPECT_TRUE(
  19598. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  19599. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  19600. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  19601. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  19602. EXPECT_FALSE(
  19603. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  19604. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  19605. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  19606. }
  19607. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  19608. Server svr;
  19609. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  19610. auto port = svr.bind_to_any_port("localhost");
  19611. std::thread t([&]() { svr.listen_after_bind(); });
  19612. auto se = detail::scope_exit([&] {
  19613. svr.stop();
  19614. t.join();
  19615. });
  19616. svr.wait_until_ready();
  19617. Headers headers = {{"Upgrade", "websocket"},
  19618. {"Connection", "notupgrade"},
  19619. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  19620. {"Sec-WebSocket-Version", "13"}};
  19621. Client cli("localhost", port);
  19622. auto res = cli.Get("/ws", headers);
  19623. // The route exists only as a WebSocket route, so a request that fails the
  19624. // handshake check falls through to ordinary routing.
  19625. ASSERT_TRUE(res);
  19626. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  19627. }
  19628. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  19629. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  19630. // Connection value is the only thing left for the client to reject.
  19631. Server svr;
  19632. svr.Get("/ws", [](const Request &req, Response &res) {
  19633. res.status = StatusCode::SwitchingProtocol_101;
  19634. res.set_header("Upgrade", "websocket");
  19635. res.set_header("Connection", "notupgrade");
  19636. res.set_header("Sec-WebSocket-Accept",
  19637. detail::websocket_accept_key(
  19638. req.get_header_value("Sec-WebSocket-Key")));
  19639. });
  19640. auto port = svr.bind_to_any_port("localhost");
  19641. std::thread t([&]() { svr.listen_after_bind(); });
  19642. auto se = detail::scope_exit([&] {
  19643. svr.stop();
  19644. t.join();
  19645. });
  19646. svr.wait_until_ready();
  19647. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  19648. auto res = client.connect();
  19649. EXPECT_FALSE(res);
  19650. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  19651. EXPECT_FALSE(client.is_open());
  19652. }
  19653. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  19654. // The socket path doubles as the URL host, so it must not contain '/'.
  19655. const char *shard = getenv("GTEST_SHARD_INDEX");
  19656. const std::string sock_path =
  19657. shard ? std::string("httplib-ws-") + shard + ".sock"
  19658. : std::string("httplib-ws.sock");
  19659. std::remove(sock_path.c_str());
  19660. Server svr;
  19661. std::mutex mtx;
  19662. std::string received_host;
  19663. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  19664. {
  19665. std::lock_guard<std::mutex> lock(mtx);
  19666. received_host = req.get_header_value("Host");
  19667. }
  19668. std::string msg;
  19669. while (ws.read(msg)) {
  19670. ws.send(msg);
  19671. }
  19672. });
  19673. svr.set_address_family(AF_UNIX);
  19674. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  19675. auto se = detail::scope_exit([&] {
  19676. svr.stop();
  19677. t.join();
  19678. std::remove(sock_path.c_str());
  19679. });
  19680. svr.wait_until_ready();
  19681. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  19682. client.set_address_family(AF_UNIX);
  19683. ASSERT_TRUE(client.connect());
  19684. ASSERT_TRUE(client.send("hello"));
  19685. std::string msg;
  19686. ASSERT_TRUE(client.read(msg));
  19687. client.close();
  19688. {
  19689. std::lock_guard<std::mutex> lock(mtx);
  19690. // There is no host:port for a Unix socket, so the same "localhost"
  19691. // placeholder the HTTP client uses is expected.
  19692. EXPECT_EQ("localhost", received_host);
  19693. }
  19694. }
  19695. // Two threads must never parse WebSocket frames from the same stream.
  19696. // close() used to read the peer's Close reply with its own frame read, so it
  19697. // raced a reader thread that was in the middle of a payload: the payload loop
  19698. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  19699. // so bytes taken by close() were replaced with bytes from further along the
  19700. // stream. The message kept its length and silently changed content.
  19701. //
  19702. // The raw peer below sends a frame header plus part of the payload, waits for
  19703. // the handler to call close(), and only then sends the rest. Whichever thread
  19704. // would win the race for those bytes, the message must arrive intact, because
  19705. // close() must not touch the stream while read() owns it.
  19706. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  19707. #ifndef _WIN32
  19708. signal(SIGPIPE, SIG_IGN);
  19709. #endif
  19710. const size_t payload_len = 120; // fits the 7-bit length field
  19711. const size_t prefix_len = 8;
  19712. const int attempts = 8;
  19713. std::string expected(payload_len, '\0');
  19714. for (size_t i = 0; i < payload_len; i++) {
  19715. expected[i] = static_cast<char>('a' + i % 26);
  19716. }
  19717. std::atomic<bool> peer_stalled{false};
  19718. std::atomic<bool> handler_done{false};
  19719. std::mutex received_mutex;
  19720. std::vector<std::string> received;
  19721. // Bound every wait, so a regression fails the test instead of hanging the
  19722. // suite.
  19723. auto wait_for = [](const std::atomic<bool> &flag) {
  19724. for (int i = 0; i < 500 && !flag; i++) {
  19725. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  19726. }
  19727. };
  19728. Server svr;
  19729. svr.set_websocket_ping_interval(0);
  19730. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  19731. std::thread reader([&]() {
  19732. std::string msg;
  19733. while (ws.read(msg)) {
  19734. std::lock_guard<std::mutex> guard(received_mutex);
  19735. received.push_back(msg);
  19736. }
  19737. });
  19738. // Wait until the peer stalls mid-payload, so the reader thread is parked
  19739. // inside read_websocket_frame() when close() runs.
  19740. wait_for(peer_stalled);
  19741. ws.close();
  19742. reader.join();
  19743. handler_done = true;
  19744. });
  19745. auto port = svr.bind_to_any_port("127.0.0.1");
  19746. std::thread t([&]() { svr.listen_after_bind(); });
  19747. auto se = detail::scope_exit([&] {
  19748. svr.stop();
  19749. t.join();
  19750. });
  19751. svr.wait_until_ready();
  19752. auto send_bytes = [](socket_t s, const std::string &data) {
  19753. #ifdef _WIN32
  19754. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  19755. #else
  19756. auto n = ::send(s, data.data(), data.size(), 0);
  19757. #endif
  19758. return n == static_cast<decltype(n)>(data.size());
  19759. };
  19760. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  19761. // Every length used here fits the 7-bit length field.
  19762. auto masked_header = [](uint8_t first_byte, size_t len) {
  19763. std::string h;
  19764. h += static_cast<char>(first_byte);
  19765. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  19766. h.append(4, '\0'); // mask key
  19767. return h;
  19768. };
  19769. for (int attempt = 0; attempt < attempts; attempt++) {
  19770. peer_stalled = false;
  19771. handler_done = false;
  19772. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  19773. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  19774. auto se_sock = detail::scope_exit([&] {
  19775. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  19776. });
  19777. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  19778. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  19779. sockaddr_in addr{};
  19780. addr.sin_family = AF_INET;
  19781. addr.sin_port = htons(static_cast<uint16_t>(port));
  19782. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  19783. ASSERT_EQ(
  19784. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  19785. << "attempt " << attempt;
  19786. ASSERT_TRUE(send_bytes(sock,
  19787. "GET /ws HTTP/1.1\r\n"
  19788. "Host: 127.0.0.1\r\n"
  19789. "Upgrade: websocket\r\n"
  19790. "Connection: Upgrade\r\n"
  19791. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  19792. "Sec-WebSocket-Version: 13\r\n"
  19793. "\r\n"))
  19794. << "attempt " << attempt;
  19795. std::string response;
  19796. while (response.find("\r\n\r\n") == std::string::npos) {
  19797. char buf[512];
  19798. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  19799. if (n <= 0) { break; }
  19800. response.append(buf, static_cast<size_t>(n));
  19801. }
  19802. ASSERT_NE(std::string::npos, response.find(" 101 "))
  19803. << "attempt " << attempt;
  19804. // Send the header of a Binary message but only the first prefix_len bytes
  19805. // of its payload, leaving the reader thread stalled inside the payload.
  19806. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  19807. expected.substr(0, prefix_len)))
  19808. << "attempt " << attempt;
  19809. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  19810. peer_stalled = true;
  19811. // Let close() send its Close frame and park in its own read before the
  19812. // rest of the payload arrives, so both threads are waiting for it.
  19813. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  19814. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  19815. close_frame += static_cast<char>(0x03); // status 1000
  19816. close_frame += static_cast<char>(0xE8);
  19817. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  19818. << "attempt " << attempt;
  19819. // Closing the peer releases the reader thread even on the buggy path,
  19820. // where it waits for bytes another thread already consumed.
  19821. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  19822. detail::close_socket(sock);
  19823. sock = INVALID_SOCKET;
  19824. wait_for(handler_done);
  19825. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  19826. }
  19827. std::lock_guard<std::mutex> guard(received_mutex);
  19828. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  19829. << "a message in flight when close() ran was dropped";
  19830. for (size_t i = 0; i < received.size(); i++) {
  19831. EXPECT_EQ(expected, received[i]) << "message " << i;
  19832. }
  19833. }
  19834. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  19835. class WebSocketSSLIntegrationTest : public ::testing::Test {
  19836. protected:
  19837. void SetUp() override {
  19838. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  19839. SERVER_PRIVATE_KEY_FILE);
  19840. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  19841. std::string msg;
  19842. ws::ReadResult ret;
  19843. while ((ret = ws.read(msg))) {
  19844. if (ret == ws::Binary) {
  19845. ws.send(msg.data(), msg.size());
  19846. } else {
  19847. ws.send(msg);
  19848. }
  19849. }
  19850. });
  19851. port_ = server_->bind_to_any_port(HOST);
  19852. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  19853. server_->wait_until_ready();
  19854. }
  19855. void TearDown() override {
  19856. server_->stop();
  19857. if (server_thread_.joinable()) { server_thread_.join(); }
  19858. }
  19859. std::unique_ptr<SSLServer> server_;
  19860. std::thread server_thread_;
  19861. int port_ = 0;
  19862. };
  19863. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  19864. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  19865. "/ws-echo");
  19866. client.enable_server_certificate_verification(false);
  19867. ASSERT_TRUE(client.connect());
  19868. ASSERT_TRUE(client.is_open());
  19869. ASSERT_TRUE(client.send("Hello WSS"));
  19870. std::string msg;
  19871. EXPECT_EQ(ws::Text, client.read(msg));
  19872. EXPECT_EQ("Hello WSS", msg);
  19873. client.close();
  19874. }
  19875. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  19876. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  19877. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  19878. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  19879. // client (without calling close() first) is the only path that runs
  19880. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  19881. // bug exactly.
  19882. //
  19883. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  19884. // when linked against an instrumented libssl; run under Valgrind to catch it
  19885. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  19886. // suite (the freed session otherwise stalls on the close handshake) — this test
  19887. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  19888. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  19889. {
  19890. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  19891. "/ws-echo");
  19892. client.enable_server_certificate_verification(false);
  19893. client.set_read_timeout(2, 0);
  19894. client.set_write_timeout(2, 0);
  19895. ASSERT_TRUE(client.connect());
  19896. ASSERT_TRUE(client.is_open());
  19897. ASSERT_TRUE(client.send("still open"));
  19898. // Intentionally do NOT call client.close(): leaving scope runs
  19899. // shutdown_and_close() with the WebSocket still open, which must send the
  19900. // close frame while the TLS session is still alive.
  19901. }
  19902. }
  19903. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  19904. // shutdown_and_close() at the start of connect(), reproducing the same
  19905. // use-after-free within the test body rather than at scope exit. The second
  19906. // connect must succeed and echo, proving the close handshake ran over a live
  19907. // session. See the note above about memory-tool requirements.
  19908. TEST_F(WebSocketSSLIntegrationTest,
  19909. ReconnectWhileOpenSendsCloseOverLiveSession) {
  19910. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  19911. "/ws-echo");
  19912. client.enable_server_certificate_verification(false);
  19913. client.set_read_timeout(2, 0);
  19914. client.set_write_timeout(2, 0);
  19915. ASSERT_TRUE(client.connect());
  19916. ASSERT_TRUE(client.is_open());
  19917. ASSERT_TRUE(client.send("still open"));
  19918. // Reconnect without closing first: connect() calls shutdown_and_close() on
  19919. // the still-open connection, which must not touch a freed TLS session.
  19920. ASSERT_TRUE(client.connect());
  19921. ASSERT_TRUE(client.is_open());
  19922. ASSERT_TRUE(client.send("after reconnect"));
  19923. std::string msg;
  19924. EXPECT_EQ(ws::Text, client.read(msg));
  19925. EXPECT_EQ("after reconnect", msg);
  19926. client.close();
  19927. }
  19928. #endif
  19929. #ifdef CPPHTTPLIB_SSL_ENABLED
  19930. class WebSocketSSLCATest : public ::testing::Test {
  19931. protected:
  19932. void SetUp() override {
  19933. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  19934. SERVER_PRIVATE_KEY_FILE);
  19935. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  19936. std::string msg;
  19937. while (ws.read(msg)) {
  19938. ws.send(msg);
  19939. }
  19940. });
  19941. port_ = server_->bind_to_any_port("127.0.0.1");
  19942. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  19943. server_->wait_until_ready();
  19944. }
  19945. void TearDown() override {
  19946. server_->stop();
  19947. if (server_thread_.joinable()) { server_thread_.join(); }
  19948. }
  19949. std::string url() const {
  19950. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  19951. }
  19952. std::unique_ptr<SSLServer> server_;
  19953. std::thread server_thread_;
  19954. int port_ = 0;
  19955. };
  19956. // A custom CA loaded as PEM verifies the server with full certificate
  19957. // verification enabled
  19958. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  19959. ws::WebSocketClient client(url());
  19960. std::string cert;
  19961. read_file(SERVER_CERT2_FILE, cert);
  19962. client.load_ca_cert_store(cert.c_str(), cert.size());
  19963. ASSERT_TRUE(client.connect());
  19964. ASSERT_TRUE(client.send("hello"));
  19965. std::string msg;
  19966. EXPECT_EQ(ws::Text, client.read(msg));
  19967. EXPECT_EQ("hello", msg);
  19968. client.close();
  19969. }
  19970. // A custom CA that does not cover the server must fail verification (the
  19971. // custom CA is exclusive; system certs are not loaded alongside it)
  19972. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  19973. ws::WebSocketClient client(url());
  19974. std::string cert;
  19975. read_file(CLIENT_CA_CERT_FILE, cert);
  19976. client.load_ca_cert_store(cert.c_str(), cert.size());
  19977. auto res = client.connect();
  19978. ASSERT_FALSE(res);
  19979. EXPECT_EQ(Error::SSLServerVerification, res.error());
  19980. EXPECT_EQ(-1, res.status());
  19981. EXPECT_NE(0u, res.ssl_backend_error());
  19982. }
  19983. // The same CA as a file path rather than PEM in memory
  19984. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  19985. ws::WebSocketClient client(url());
  19986. client.set_ca_cert_path(SERVER_CERT2_FILE);
  19987. ASSERT_TRUE(client.connect());
  19988. ASSERT_TRUE(client.send("hello"));
  19989. std::string msg;
  19990. EXPECT_EQ(ws::Text, client.read(msg));
  19991. EXPECT_EQ("hello", msg);
  19992. client.close();
  19993. }
  19994. // ...and a CA file that does not cover the server still fails, so it is the
  19995. // path above that decides the outcome
  19996. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  19997. ws::WebSocketClient client(url());
  19998. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  19999. ASSERT_FALSE(client.connect());
  20000. }
  20001. // Regression test: reconnecting with a native custom CA store used to reuse
  20002. // a store handle the previous TLS context had already freed (use-after-free
  20003. // under the OpenSSL backend). The context now lives as long as the client.
  20004. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  20005. ws::WebSocketClient client(url());
  20006. std::string cert;
  20007. read_file(SERVER_CERT2_FILE, cert);
  20008. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  20009. ASSERT_TRUE(client.connect());
  20010. client.close();
  20011. ASSERT_TRUE(client.connect());
  20012. ASSERT_TRUE(client.send("again"));
  20013. std::string msg;
  20014. EXPECT_EQ(ws::Text, client.read(msg));
  20015. EXPECT_EQ("again", msg);
  20016. client.close();
  20017. }
  20018. // Regression test: a certificate with a trusted chain but no identity match
  20019. // for the server IP must be rejected. The Mbed TLS backend used to skip
  20020. // verification entirely for IP hosts, so this connection succeeded there.
  20021. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  20022. // chain verification while the identity check must still fail.
  20023. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  20024. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20025. ASSERT_TRUE(svr.is_valid());
  20026. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  20027. std::string msg;
  20028. while (ws.read(msg)) {
  20029. ws.send(msg);
  20030. }
  20031. });
  20032. auto port = svr.bind_to_any_port("127.0.0.1");
  20033. auto t = std::thread([&]() { svr.listen_after_bind(); });
  20034. auto se = detail::scope_exit([&] {
  20035. svr.stop();
  20036. t.join();
  20037. });
  20038. svr.wait_until_ready();
  20039. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  20040. "/echo");
  20041. std::string cert;
  20042. read_file(SERVER_CERT_FILE, cert);
  20043. client.load_ca_cert_store(cert.c_str(), cert.size());
  20044. ASSERT_FALSE(client.connect());
  20045. }
  20046. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  20047. // SNI, so nothing binds the host name to the TLS session. These bind the
  20048. // server to "localhost" instead, the only shape that exercises the SNI and
  20049. // hostname-verification path with certificate verification left enabled.
  20050. class WebSocketSSLDnsHostTest : public ::testing::Test {
  20051. protected:
  20052. void Start(const char *cert_file) {
  20053. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  20054. SERVER_PRIVATE_KEY_FILE);
  20055. ASSERT_TRUE(server_->is_valid());
  20056. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  20057. std::string msg;
  20058. while (ws.read(msg)) {
  20059. ws.send(msg);
  20060. }
  20061. });
  20062. port_ = server_->bind_to_any_port("localhost");
  20063. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  20064. server_->wait_until_ready();
  20065. }
  20066. void TearDown() override {
  20067. if (server_) { server_->stop(); }
  20068. if (server_thread_.joinable()) { server_thread_.join(); }
  20069. }
  20070. std::string url() const {
  20071. return "wss://localhost:" + std::to_string(port_) + "/echo";
  20072. }
  20073. std::unique_ptr<SSLServer> server_;
  20074. std::thread server_thread_;
  20075. int port_ = 0;
  20076. };
  20077. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  20078. // out and the connection is usable
  20079. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  20080. Start(SERVER_CERT2_FILE);
  20081. ws::WebSocketClient client(url());
  20082. client.set_ca_cert_path(SERVER_CERT2_FILE);
  20083. ASSERT_TRUE(client.connect());
  20084. ASSERT_TRUE(client.send("hello"));
  20085. std::string msg;
  20086. EXPECT_EQ(ws::Text, client.read(msg));
  20087. EXPECT_EQ("hello", msg);
  20088. client.close();
  20089. }
  20090. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  20091. // while the identity check must still reject "localhost"
  20092. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  20093. Start(SERVER_CERT_FILE);
  20094. ws::WebSocketClient client(url());
  20095. client.set_ca_cert_path(SERVER_CERT_FILE);
  20096. auto res = client.connect();
  20097. ASSERT_FALSE(res);
  20098. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  20099. EXPECT_EQ(-1, res.status());
  20100. }
  20101. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  20102. // disabled: the chain is still checked, only the identity check is skipped
  20103. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  20104. Start(SERVER_CERT_FILE);
  20105. ws::WebSocketClient client(url());
  20106. client.set_ca_cert_path(SERVER_CERT_FILE);
  20107. client.enable_server_hostname_verification(false);
  20108. ASSERT_TRUE(client.connect());
  20109. ASSERT_TRUE(client.send("hello"));
  20110. std::string msg;
  20111. EXPECT_EQ(ws::Text, client.read(msg));
  20112. EXPECT_EQ("hello", msg);
  20113. client.close();
  20114. }
  20115. // A CA that did not sign the server certificate fails the chain, even though
  20116. // the name would match
  20117. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  20118. Start(SERVER_CERT2_FILE);
  20119. ws::WebSocketClient client(url());
  20120. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  20121. ASSERT_FALSE(client.connect());
  20122. }
  20123. // With verification disabled, neither the chain nor the name is checked
  20124. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  20125. Start(SERVER_CERT_FILE);
  20126. ws::WebSocketClient client(url());
  20127. client.enable_server_certificate_verification(false);
  20128. ASSERT_TRUE(client.connect());
  20129. ASSERT_TRUE(client.send("hello"));
  20130. std::string msg;
  20131. EXPECT_EQ(ws::Text, client.read(msg));
  20132. EXPECT_EQ("hello", msg);
  20133. client.close();
  20134. }
  20135. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  20136. protected:
  20137. void SetUp() override {
  20138. server_ = httplib::detail::make_unique<SSLServer>(
  20139. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  20140. ASSERT_TRUE(server_->is_valid());
  20141. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  20142. std::string msg;
  20143. while (ws.read(msg)) {
  20144. ws.send(msg);
  20145. }
  20146. });
  20147. port_ = server_->bind_to_any_port("localhost");
  20148. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  20149. server_->wait_until_ready();
  20150. }
  20151. void TearDown() override {
  20152. server_->stop();
  20153. if (server_thread_.joinable()) { server_thread_.join(); }
  20154. }
  20155. std::string url() const {
  20156. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  20157. }
  20158. void ConnectWithClientCert(const std::string &client_cert_file,
  20159. const std::string &client_private_key_file,
  20160. const char *private_key_password) {
  20161. std::string cert_pem, key_pem;
  20162. read_file(client_cert_file, cert_pem);
  20163. read_file(client_private_key_file, key_pem);
  20164. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  20165. key_pem.c_str(), key_pem.size(),
  20166. private_key_password};
  20167. ws::WebSocketClient client(url(), pem);
  20168. ASSERT_TRUE(client.is_valid());
  20169. client.enable_server_certificate_verification(false);
  20170. ASSERT_TRUE(client.connect());
  20171. ASSERT_TRUE(client.send("hello"));
  20172. std::string msg;
  20173. EXPECT_EQ(ws::Text, client.read(msg));
  20174. EXPECT_EQ("hello", msg);
  20175. client.close();
  20176. }
  20177. std::unique_ptr<SSLServer> server_;
  20178. std::thread server_thread_;
  20179. int port_ = 0;
  20180. };
  20181. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  20182. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  20183. }
  20184. // Control for the tests above: the fixture's server really does require a
  20185. // client certificate, so it is the PEM the constructor installed that decides
  20186. // the outcome.
  20187. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  20188. ws::WebSocketClient client(url());
  20189. ASSERT_TRUE(client.is_valid());
  20190. client.enable_server_certificate_verification(false);
  20191. EXPECT_FALSE(client.connect());
  20192. }
  20193. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  20194. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  20195. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  20196. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  20197. }
  20198. #endif
  20199. #if !defined(_WIN32)
  20200. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  20201. auto secret_dir = std::string("./symlink_test_secret");
  20202. auto served_dir = std::string("./symlink_test_served");
  20203. auto secret_file = secret_dir + "/secret.txt";
  20204. auto symlink_path = served_dir + "/escape";
  20205. // Setup: create directories and files
  20206. mkdir(secret_dir.c_str(), 0755);
  20207. mkdir(served_dir.c_str(), 0755);
  20208. {
  20209. std::ofstream ofs(secret_file);
  20210. ofs << "SECRET_DATA";
  20211. }
  20212. // Create symlink using absolute path so it resolves correctly
  20213. #ifdef PATH_MAX
  20214. char abs_secret[PATH_MAX];
  20215. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  20216. #else
  20217. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  20218. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  20219. ASSERT_NE(nullptr, abs_secret);
  20220. #endif
  20221. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  20222. auto se = detail::scope_exit([&] {
  20223. unlink(symlink_path.c_str());
  20224. unlink(secret_file.c_str());
  20225. rmdir(served_dir.c_str());
  20226. rmdir(secret_dir.c_str());
  20227. });
  20228. Server svr;
  20229. svr.set_mount_point("/", served_dir);
  20230. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  20231. auto se2 = detail::scope_exit([&] {
  20232. svr.stop();
  20233. listen_thread.join();
  20234. });
  20235. svr.wait_until_ready();
  20236. Client cli("localhost", PORT);
  20237. // Symlink pointing outside base dir should be blocked
  20238. auto res = cli.Get("/escape/secret.txt");
  20239. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20240. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  20241. }
  20242. #endif
  20243. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  20244. // A GET request with Content-Length to a static file handler must have its
  20245. // body drained before the keep-alive connection is reused. Otherwise the
  20246. // unread body bytes are interpreted as the next HTTP request.
  20247. //
  20248. // The body is sent AFTER receiving the first response (as in the original
  20249. // PoC) so that the stream_line_reader cannot buffer it together with the
  20250. // headers of the first request.
  20251. Server svr;
  20252. svr.set_mount_point("/", "./www");
  20253. std::atomic<int> smuggled_count(0);
  20254. svr.Get("/smuggled", [&](const Request &, Response &res) {
  20255. smuggled_count++;
  20256. res.set_content("oops", "text/plain");
  20257. });
  20258. auto port = svr.bind_to_any_port("localhost");
  20259. thread t = thread([&] { svr.listen_after_bind(); });
  20260. auto se = detail::scope_exit([&] {
  20261. svr.stop();
  20262. t.join();
  20263. });
  20264. svr.wait_until_ready();
  20265. auto error = Error::Success;
  20266. auto sock = detail::create_client_socket(
  20267. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  20268. /*connection_timeout_sec=*/2, 0,
  20269. /*read_timeout_sec=*/2, 0,
  20270. /*write_timeout_sec=*/2, 0, std::string(), error);
  20271. ASSERT_NE(INVALID_SOCKET, sock);
  20272. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  20273. // The "smuggled" request will be sent as the body of the outer GET
  20274. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  20275. "Host: localhost\r\n"
  20276. "Connection: close\r\n"
  20277. "\r\n";
  20278. // Step 1: Send only the outer request headers (no body yet)
  20279. std::string outer_headers = "GET /file HTTP/1.1\r\n"
  20280. "Host: localhost\r\n"
  20281. "Content-Length: " +
  20282. std::to_string(smuggled.size()) +
  20283. "\r\n"
  20284. "\r\n";
  20285. auto sent = send(sock, outer_headers.data(), outer_headers.size(), 0);
  20286. ASSERT_EQ(static_cast<ssize_t>(outer_headers.size()), sent);
  20287. // Step 2: Read the first response (server serves file without reading body)
  20288. std::string first_response;
  20289. char buf[4096];
  20290. for (;;) {
  20291. auto n = recv(sock, buf, sizeof(buf), 0);
  20292. if (n <= 0) break;
  20293. first_response.append(buf, static_cast<size_t>(n));
  20294. // Stop once we have a complete response (headers + body)
  20295. auto hdr_end = first_response.find("\r\n\r\n");
  20296. if (hdr_end != std::string::npos) {
  20297. // Check for Content-Length to know when the body is complete
  20298. auto cl_pos = first_response.find("Content-Length:");
  20299. if (cl_pos != std::string::npos) {
  20300. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  20301. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  20302. auto cl = std::stoul(
  20303. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  20304. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  20305. } else {
  20306. break; // No Content-Length, assume headers-only response
  20307. }
  20308. }
  20309. }
  20310. ASSERT_TRUE(first_response.find("HTTP/1.1 200") != std::string::npos);
  20311. // Step 3: Now send the body, which looks like a new HTTP request.
  20312. // On a vulnerable server the keep-alive loop reads this as a second request.
  20313. sent = send(sock, smuggled.data(), smuggled.size(), 0);
  20314. ASSERT_EQ(static_cast<ssize_t>(smuggled.size()), sent);
  20315. // Step 4: Try to read a second response (should NOT exist after fix)
  20316. std::string second_response;
  20317. for (;;) {
  20318. auto n = recv(sock, buf, sizeof(buf), 0);
  20319. if (n <= 0) break;
  20320. second_response.append(buf, static_cast<size_t>(n));
  20321. }
  20322. // The smuggled request must NOT have been processed
  20323. EXPECT_EQ(0, smuggled_count.load());
  20324. }
  20325. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  20326. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  20327. // must be rejected with 400 Bad Request.
  20328. Server svr;
  20329. svr.Post("/test", [&](const Request &, Response &res) {
  20330. res.set_content("ok", "text/plain");
  20331. });
  20332. thread t = thread([&] { svr.listen(HOST, PORT); });
  20333. auto se = detail::scope_exit([&] {
  20334. svr.stop();
  20335. t.join();
  20336. ASSERT_FALSE(svr.is_running());
  20337. });
  20338. svr.wait_until_ready();
  20339. // Exact "chunked"
  20340. {
  20341. auto req = "POST /test HTTP/1.1\r\n"
  20342. "Host: localhost\r\n"
  20343. "Content-Length: 5\r\n"
  20344. "Transfer-Encoding: chunked\r\n"
  20345. "Connection: close\r\n"
  20346. "\r\n"
  20347. "hello";
  20348. std::string response;
  20349. ASSERT_TRUE(send_request(1, req, &response));
  20350. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  20351. response.substr(0, response.find("\r\n")));
  20352. }
  20353. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  20354. {
  20355. auto req = "POST /test HTTP/1.1\r\n"
  20356. "Host: localhost\r\n"
  20357. "Content-Length: 5\r\n"
  20358. "Transfer-Encoding: gzip, chunked\r\n"
  20359. "Connection: close\r\n"
  20360. "\r\n"
  20361. "hello";
  20362. std::string response;
  20363. ASSERT_TRUE(send_request(1, req, &response));
  20364. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  20365. response.substr(0, response.find("\r\n")));
  20366. }
  20367. }
  20368. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  20369. Server svr;
  20370. svr.Post("/test", [&](const Request &, Response &res) {
  20371. res.set_content("ok", "text/plain");
  20372. });
  20373. thread t = thread([&] { svr.listen(HOST, PORT); });
  20374. auto se = detail::scope_exit([&] {
  20375. svr.stop();
  20376. t.join();
  20377. ASSERT_FALSE(svr.is_running());
  20378. });
  20379. svr.wait_until_ready();
  20380. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  20381. // length cannot be determined, so the server must answer 400 and close
  20382. // rather than treat the request as bodyless and leave the body in the
  20383. // socket for the next request to pick up.
  20384. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  20385. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  20386. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  20387. std::string response;
  20388. ASSERT_TRUE(send_request(1, req, &response));
  20389. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  20390. response.substr(0, response.find("\r\n")))
  20391. << transfer_encoding;
  20392. }
  20393. // RFC 9110 5.3: the codings may also be split across several
  20394. // Transfer-Encoding lines, which combine in the order they were received.
  20395. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  20396. // just like the single-line "chunked, gzip" above.
  20397. {
  20398. auto req = "POST /test HTTP/1.1\r\n"
  20399. "Host: localhost\r\n"
  20400. "Transfer-Encoding: chunked\r\n"
  20401. "Transfer-Encoding: gzip\r\n"
  20402. "\r\n"
  20403. "0\r\n\r\n";
  20404. std::string response;
  20405. ASSERT_TRUE(send_request(1, req, &response));
  20406. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  20407. response.substr(0, response.find("\r\n")));
  20408. }
  20409. // A sequence ending in chunked stays valid.
  20410. auto req = "POST /test HTTP/1.1\r\n"
  20411. "Host: localhost\r\n"
  20412. "Transfer-Encoding: gzip, chunked\r\n"
  20413. "Connection: close\r\n"
  20414. "\r\n"
  20415. "0\r\n\r\n";
  20416. std::string response;
  20417. ASSERT_TRUE(send_request(1, req, &response));
  20418. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  20419. // ...including when it is spread over several lines.
  20420. auto split_req = "POST /test HTTP/1.1\r\n"
  20421. "Host: localhost\r\n"
  20422. "Transfer-Encoding: gzip\r\n"
  20423. "Transfer-Encoding: chunked\r\n"
  20424. "Connection: close\r\n"
  20425. "\r\n"
  20426. "0\r\n\r\n";
  20427. std::string split_response;
  20428. ASSERT_TRUE(send_request(1, split_req, &split_response));
  20429. EXPECT_EQ("HTTP/1.1 200 OK",
  20430. split_response.substr(0, split_response.find("\r\n")));
  20431. }
  20432. // Regression for issue #2450: a DELETE without Content-Length on a
  20433. // keep-alive connection must not let the post-response drain consume the
  20434. // next request's bytes.
  20435. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  20436. Server svr;
  20437. std::atomic<int> delete_count(0);
  20438. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  20439. delete_count++;
  20440. res.status = StatusCode::NoContent_204;
  20441. });
  20442. auto port = svr.bind_to_any_port(HOST);
  20443. thread t = thread([&] { svr.listen_after_bind(); });
  20444. auto se = detail::scope_exit([&] {
  20445. svr.stop();
  20446. t.join();
  20447. });
  20448. svr.wait_until_ready();
  20449. auto error = Error::Success;
  20450. auto sock = detail::create_client_socket(
  20451. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  20452. /*connection_timeout_sec=*/2, 0,
  20453. /*read_timeout_sec=*/2, 0,
  20454. /*write_timeout_sec=*/2, 0, std::string(), error);
  20455. ASSERT_NE(INVALID_SOCKET, sock);
  20456. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  20457. auto send_request_and_read_response = [&](const std::string &req,
  20458. std::string &out) -> bool {
  20459. auto sent = send(sock, req.data(), req.size(), 0);
  20460. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  20461. char buf[4096];
  20462. for (;;) {
  20463. auto n = recv(sock, buf, sizeof(buf), 0);
  20464. if (n <= 0) { return !out.empty(); }
  20465. out.append(buf, static_cast<size_t>(n));
  20466. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  20467. }
  20468. };
  20469. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  20470. "Host: localhost\r\n"
  20471. "\r\n";
  20472. std::string resp1;
  20473. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  20474. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  20475. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  20476. "Host: localhost\r\n"
  20477. "Connection: close\r\n"
  20478. "\r\n";
  20479. std::string resp2;
  20480. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  20481. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  20482. EXPECT_EQ(2, delete_count.load());
  20483. }
  20484. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  20485. Server svr;
  20486. svr.Post("/ingest", [&](const Request &, Response &res,
  20487. const ContentReader &content_reader) {
  20488. auto consumed = content_reader([](const char *, size_t) { return false; });
  20489. EXPECT_FALSE(consumed);
  20490. res.status = StatusCode::Conflict_409;
  20491. res.set_header("Connection", "close");
  20492. });
  20493. auto port = svr.bind_to_any_port(HOST);
  20494. thread t = thread([&] { svr.listen_after_bind(); });
  20495. auto se = detail::scope_exit([&] {
  20496. svr.stop();
  20497. t.join();
  20498. });
  20499. svr.wait_until_ready();
  20500. auto error = Error::Success;
  20501. auto sock = detail::create_client_socket(
  20502. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  20503. /*connection_timeout_sec=*/2, 0,
  20504. /*read_timeout_sec=*/1, 0,
  20505. /*write_timeout_sec=*/2, 0, std::string(), error);
  20506. ASSERT_NE(INVALID_SOCKET, sock);
  20507. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  20508. std::string request = "POST /ingest HTTP/1.1\r\n"
  20509. "Host: localhost\r\n"
  20510. "Transfer-Encoding: chunked\r\n"
  20511. "\r\n"
  20512. "4\r\n"
  20513. "data\r\n";
  20514. auto sent = send(sock, request.data(), request.size(), 0);
  20515. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  20516. std::string response;
  20517. ssize_t received = 0;
  20518. do {
  20519. char buf[4096];
  20520. received = recv(sock, buf, sizeof(buf), 0);
  20521. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  20522. } while (received > 0);
  20523. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  20524. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  20525. EXPECT_EQ(0, received);
  20526. }
  20527. namespace no_proxy_test {
  20528. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  20529. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  20530. // calling listen().
  20531. class ScopedServer {
  20532. public:
  20533. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  20534. ~ScopedServer() {
  20535. svr_.stop();
  20536. if (th_.joinable()) { th_.join(); }
  20537. }
  20538. Server &svr() { return svr_; }
  20539. int port() const { return port_; }
  20540. void listen() {
  20541. th_ = std::thread([this] { svr_.listen_after_bind(); });
  20542. svr_.wait_until_ready();
  20543. }
  20544. private:
  20545. Server svr_;
  20546. std::thread th_;
  20547. int port_ = 0;
  20548. };
  20549. class ProxyAndTargetServers {
  20550. public:
  20551. ProxyAndTargetServers() {
  20552. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  20553. proxy_hits_++;
  20554. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  20555. res.set_content("via-proxy", "text/plain");
  20556. });
  20557. target_.Get(".*", [this](const Request &req, Response &res) {
  20558. target_hits_++;
  20559. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  20560. res.set_content("direct", "text/plain");
  20561. });
  20562. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  20563. target_port_ = target_.bind_to_any_port("127.0.0.1");
  20564. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  20565. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  20566. proxy_mock_.wait_until_ready();
  20567. target_.wait_until_ready();
  20568. }
  20569. ~ProxyAndTargetServers() {
  20570. proxy_mock_.stop();
  20571. target_.stop();
  20572. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  20573. if (target_thread_.joinable()) { target_thread_.join(); }
  20574. }
  20575. Server &proxy_mock() { return proxy_mock_; }
  20576. Server &target() { return target_; }
  20577. int proxy_port() const { return proxy_port_; }
  20578. int target_port() const { return target_port_; }
  20579. int proxy_hits() const { return proxy_hits_.load(); }
  20580. int target_hits() const { return target_hits_.load(); }
  20581. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  20582. void reset_counters() {
  20583. proxy_hits_ = 0;
  20584. target_hits_ = 0;
  20585. last_had_proxy_authz_ = false;
  20586. }
  20587. private:
  20588. Server proxy_mock_;
  20589. Server target_;
  20590. std::thread proxy_thread_;
  20591. std::thread target_thread_;
  20592. int proxy_port_ = 0;
  20593. int target_port_ = 0;
  20594. std::atomic<int> proxy_hits_{0};
  20595. std::atomic<int> target_hits_{0};
  20596. std::atomic<bool> last_had_proxy_authz_{false};
  20597. };
  20598. inline std::unique_ptr<Client> make_client(const std::string &host,
  20599. ProxyAndTargetServers &s) {
  20600. auto cli = detail::make_unique<Client>(host, s.target_port());
  20601. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  20602. cli->set_proxy("127.0.0.1", s.proxy_port());
  20603. return cli;
  20604. }
  20605. } // namespace no_proxy_test
  20606. using no_proxy_test::make_client;
  20607. using no_proxy_test::ProxyAndTargetServers;
  20608. TEST(NoProxyTest, ExactHostnameBypasses) {
  20609. ProxyAndTargetServers s;
  20610. auto cli = make_client("example.com", s);
  20611. cli->set_no_proxy({"example.com"});
  20612. auto res = cli->Get("/");
  20613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20614. EXPECT_EQ(0, s.proxy_hits());
  20615. EXPECT_EQ(1, s.target_hits());
  20616. }
  20617. TEST(NoProxyTest, SubdomainBypasses) {
  20618. ProxyAndTargetServers s;
  20619. auto cli = make_client("foo.example.com", s);
  20620. cli->set_no_proxy({"example.com"});
  20621. auto res = cli->Get("/");
  20622. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20623. EXPECT_EQ(0, s.proxy_hits());
  20624. EXPECT_EQ(1, s.target_hits());
  20625. }
  20626. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  20627. // Regression guard: "evilexample.com" must not be considered a subdomain
  20628. // of "example.com". Without the dot-boundary rule, a naive endsWith
  20629. // check would let traffic bypass the proxy and leak credentials direct
  20630. // to the attacker host.
  20631. ProxyAndTargetServers s;
  20632. auto cli = make_client("evilexample.com", s);
  20633. cli->set_no_proxy({"example.com"});
  20634. auto res = cli->Get("/");
  20635. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20636. EXPECT_GE(s.proxy_hits(), 1);
  20637. EXPECT_EQ(0, s.target_hits());
  20638. }
  20639. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  20640. ProxyAndTargetServers s;
  20641. auto cli = make_client("example.com.evil.com", s);
  20642. cli->set_no_proxy({"example.com"});
  20643. auto res = cli->Get("/");
  20644. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20645. EXPECT_GE(s.proxy_hits(), 1);
  20646. EXPECT_EQ(0, s.target_hits());
  20647. }
  20648. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  20649. ProxyAndTargetServers s;
  20650. auto cli = make_client("example.com", s);
  20651. cli->set_no_proxy({".example.com"});
  20652. auto res = cli->Get("/");
  20653. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20654. EXPECT_EQ(0, s.proxy_hits());
  20655. EXPECT_EQ(1, s.target_hits());
  20656. }
  20657. TEST(NoProxyTest, CaseInsensitiveHostname) {
  20658. ProxyAndTargetServers s;
  20659. auto cli = make_client("Example.COM", s);
  20660. cli->set_no_proxy({"EXAMPLE.com"});
  20661. auto res = cli->Get("/");
  20662. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20663. EXPECT_EQ(0, s.proxy_hits());
  20664. EXPECT_EQ(1, s.target_hits());
  20665. }
  20666. TEST(NoProxyTest, TrailingDotIsNormalized) {
  20667. ProxyAndTargetServers s;
  20668. auto cli = make_client("example.com.", s);
  20669. cli->set_no_proxy({"example.com"});
  20670. auto res = cli->Get("/");
  20671. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20672. EXPECT_EQ(0, s.proxy_hits());
  20673. EXPECT_EQ(1, s.target_hits());
  20674. }
  20675. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  20676. // Trailing dots must be normalized on BOTH sides — host and entry.
  20677. // An implementation that only strips the host-side trailing dot would
  20678. // fail to match host "example.com" against entry "example.com." because
  20679. // a literal substring search would compare 11 chars against 12.
  20680. ProxyAndTargetServers s;
  20681. auto cli = make_client("example.com", s);
  20682. cli->set_no_proxy({"example.com."});
  20683. auto res = cli->Get("/");
  20684. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20685. EXPECT_EQ(0, s.proxy_hits());
  20686. EXPECT_EQ(1, s.target_hits());
  20687. }
  20688. TEST(NoProxyTest, WildcardBypassesEverything) {
  20689. ProxyAndTargetServers s;
  20690. auto cli = make_client("anything.invalid.test", s);
  20691. cli->set_no_proxy({"*"});
  20692. auto res = cli->Get("/");
  20693. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20694. EXPECT_EQ(0, s.proxy_hits());
  20695. EXPECT_EQ(1, s.target_hits());
  20696. }
  20697. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  20698. ProxyAndTargetServers s;
  20699. Client cli("127.0.0.1", s.target_port());
  20700. cli.set_proxy("127.0.0.1", s.proxy_port());
  20701. cli.set_no_proxy({"127.0.0.1"});
  20702. auto res = cli.Get("/");
  20703. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20704. EXPECT_EQ(0, s.proxy_hits());
  20705. EXPECT_EQ(1, s.target_hits());
  20706. }
  20707. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  20708. ProxyAndTargetServers s;
  20709. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  20710. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  20711. cli.set_proxy("127.0.0.1", s.proxy_port());
  20712. cli.set_no_proxy({"::1"});
  20713. auto res = cli.Get("/");
  20714. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20715. EXPECT_EQ(0, s.proxy_hits());
  20716. EXPECT_EQ(1, s.target_hits());
  20717. }
  20718. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  20719. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  20720. // must still be recognized as IPv6 for CIDR matching. Implementations
  20721. // that detect IPv6 only when the host begins with '[' would parse the
  20722. // host as a hostname and miss the match.
  20723. ProxyAndTargetServers s;
  20724. Client cli("fe80::1", s.target_port());
  20725. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  20726. cli.set_proxy("127.0.0.1", s.proxy_port());
  20727. cli.set_no_proxy({"fe80::/10"});
  20728. auto res = cli.Get("/");
  20729. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20730. EXPECT_EQ(0, s.proxy_hits());
  20731. EXPECT_EQ(1, s.target_hits());
  20732. }
  20733. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  20734. ProxyAndTargetServers s;
  20735. Client cli("::1", s.target_port());
  20736. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  20737. cli.set_proxy("127.0.0.1", s.proxy_port());
  20738. cli.set_no_proxy({"[::1]"});
  20739. auto res = cli.Get("/");
  20740. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20741. EXPECT_EQ(0, s.proxy_hits());
  20742. EXPECT_EQ(1, s.target_hits());
  20743. }
  20744. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  20745. ProxyAndTargetServers s;
  20746. Client cli("fe80::1", s.target_port());
  20747. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  20748. cli.set_proxy("127.0.0.1", s.proxy_port());
  20749. cli.set_no_proxy({"[fe80::]/10"});
  20750. auto res = cli.Get("/");
  20751. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20752. EXPECT_EQ(0, s.proxy_hits());
  20753. EXPECT_EQ(1, s.target_hits());
  20754. }
  20755. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  20756. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  20757. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  20758. // tricks via address-family conversion.
  20759. ProxyAndTargetServers s;
  20760. Client cli("::ffff:127.0.0.1", s.target_port());
  20761. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  20762. cli.set_proxy("127.0.0.1", s.proxy_port());
  20763. cli.set_no_proxy({"127.0.0.1"});
  20764. auto res = cli.Get("/");
  20765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20766. EXPECT_GE(s.proxy_hits(), 1);
  20767. EXPECT_EQ(0, s.target_hits());
  20768. }
  20769. TEST(NoProxyTest, IPv4CidrMatch) {
  20770. ProxyAndTargetServers s;
  20771. Client cli("127.0.0.1", s.target_port());
  20772. cli.set_proxy("127.0.0.1", s.proxy_port());
  20773. cli.set_no_proxy({"127.0.0.0/8"});
  20774. auto res = cli.Get("/");
  20775. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20776. EXPECT_EQ(0, s.proxy_hits());
  20777. EXPECT_EQ(1, s.target_hits());
  20778. }
  20779. TEST(NoProxyTest, IPv4CidrNonMatch) {
  20780. ProxyAndTargetServers s;
  20781. Client cli("127.0.0.1", s.target_port());
  20782. cli.set_proxy("127.0.0.1", s.proxy_port());
  20783. cli.set_no_proxy({"10.0.0.0/8"});
  20784. auto res = cli.Get("/");
  20785. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20786. EXPECT_GE(s.proxy_hits(), 1);
  20787. EXPECT_EQ(0, s.target_hits());
  20788. }
  20789. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  20790. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  20791. // IPv4 target matches.
  20792. ProxyAndTargetServers s;
  20793. Client cli("127.0.0.1", s.target_port());
  20794. cli.set_proxy("127.0.0.1", s.proxy_port());
  20795. cli.set_no_proxy({"0.0.0.0/0"});
  20796. auto res = cli.Get("/");
  20797. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20798. EXPECT_EQ(0, s.proxy_hits());
  20799. EXPECT_EQ(1, s.target_hits());
  20800. }
  20801. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  20802. ProxyAndTargetServers s;
  20803. Client cli("127.0.0.1", s.target_port());
  20804. cli.set_proxy("127.0.0.1", s.proxy_port());
  20805. cli.set_no_proxy({"127.0.0.1"});
  20806. auto res = cli.Get("/");
  20807. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20808. EXPECT_EQ(0, s.proxy_hits());
  20809. EXPECT_EQ(1, s.target_hits());
  20810. }
  20811. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  20812. ProxyAndTargetServers s;
  20813. Client cli("127.0.0.1", s.target_port());
  20814. cli.set_proxy("127.0.0.1", s.proxy_port());
  20815. cli.set_no_proxy({"127.0.0.0/33"});
  20816. auto res = cli.Get("/");
  20817. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20818. EXPECT_GE(s.proxy_hits(), 1);
  20819. EXPECT_EQ(0, s.target_hits());
  20820. }
  20821. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  20822. // Empty prefix after the slash must be rejected, not silently treated as /32.
  20823. ProxyAndTargetServers s;
  20824. Client cli("127.0.0.1", s.target_port());
  20825. cli.set_proxy("127.0.0.1", s.proxy_port());
  20826. cli.set_no_proxy({"127.0.0.1/"});
  20827. auto res = cli.Get("/");
  20828. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20829. EXPECT_GE(s.proxy_hits(), 1);
  20830. EXPECT_EQ(0, s.target_hits());
  20831. }
  20832. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  20833. ProxyAndTargetServers s;
  20834. auto cli = make_client("internal.corp", s);
  20835. cli->set_proxy_basic_auth("u", "p");
  20836. cli->set_no_proxy({"internal.corp"});
  20837. auto res = cli->Get("/");
  20838. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20839. EXPECT_EQ(1, s.target_hits());
  20840. EXPECT_EQ(0, s.proxy_hits());
  20841. EXPECT_FALSE(s.last_had_proxy_authz())
  20842. << "Proxy-Authorization must not be sent direct to the target";
  20843. }
  20844. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  20845. ProxyAndTargetServers s;
  20846. auto cli = make_client("public.example", s);
  20847. cli->set_proxy_basic_auth("u", "p");
  20848. cli->set_no_proxy({"internal.corp"}); // does not match
  20849. auto res = cli->Get("/");
  20850. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20851. EXPECT_GE(s.proxy_hits(), 1);
  20852. EXPECT_TRUE(s.last_had_proxy_authz());
  20853. }
  20854. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  20855. ProxyAndTargetServers s;
  20856. auto cli = make_client("anything.test", s);
  20857. auto res = cli->Get("/");
  20858. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20859. EXPECT_GE(s.proxy_hits(), 1);
  20860. EXPECT_EQ(0, s.target_hits());
  20861. }
  20862. TEST(NoProxyTest, PortSpecificEntryRejected) {
  20863. ProxyAndTargetServers s;
  20864. auto cli = make_client("example.com", s);
  20865. cli->set_no_proxy({"example.com:8080"});
  20866. auto res = cli->Get("/");
  20867. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20868. EXPECT_GE(s.proxy_hits(), 1);
  20869. EXPECT_EQ(0, s.target_hits());
  20870. }
  20871. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  20872. ProxyAndTargetServers s;
  20873. auto cli = make_client("anything.test", s);
  20874. cli->set_no_proxy({"", " ", "\t"});
  20875. auto res = cli->Get("/");
  20876. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20877. EXPECT_GE(s.proxy_hits(), 1);
  20878. EXPECT_EQ(0, s.target_hits());
  20879. }
  20880. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  20881. // An entry with leading/trailing whitespace must still match — env-style
  20882. // values are commonly pasted with stray spaces and an implementation
  20883. // that feeds the raw token directly to inet_pton would fail to match
  20884. // valid CIDRs because of the spaces.
  20885. ProxyAndTargetServers s;
  20886. Client cli("127.0.0.1", s.target_port());
  20887. cli.set_proxy("127.0.0.1", s.proxy_port());
  20888. cli.set_no_proxy({" 127.0.0.0/8 "});
  20889. auto res = cli.Get("/");
  20890. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20891. EXPECT_EQ(0, s.proxy_hits());
  20892. EXPECT_EQ(1, s.target_hits());
  20893. }
  20894. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  20895. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  20896. // go direct and must NOT carry Proxy-Authorization.
  20897. std::atomic<int> proxy_hits{0};
  20898. std::atomic<int> target_hits{0};
  20899. std::atomic<bool> target_saw_authz{false};
  20900. no_proxy_test::ScopedServer proxy_mock, target;
  20901. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  20902. proxy_hits++;
  20903. res.status = 302;
  20904. res.set_header("Location", "http://127.0.0.1:" +
  20905. std::to_string(target.port()) + "/landed");
  20906. });
  20907. target.svr().Get(".*", [&](const Request &req, Response &res) {
  20908. target_hits++;
  20909. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  20910. res.set_content("direct", "text/plain");
  20911. });
  20912. proxy_mock.listen();
  20913. target.listen();
  20914. Client cli("public.example", target.port());
  20915. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  20916. cli.set_proxy("127.0.0.1", proxy_mock.port());
  20917. cli.set_proxy_basic_auth("u", "p");
  20918. cli.set_no_proxy({"127.0.0.1"});
  20919. cli.set_follow_location(true);
  20920. auto res = cli.Get("/redir");
  20921. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20922. EXPECT_GE(proxy_hits.load(), 1);
  20923. EXPECT_GE(target_hits.load(), 1);
  20924. EXPECT_FALSE(target_saw_authz.load());
  20925. }
  20926. #ifdef CPPHTTPLIB_SSL_ENABLED
  20927. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  20928. // Direct origin replying 407 must not trigger the digest retry; otherwise
  20929. // proxy creds would be sent to the (possibly hostile) origin.
  20930. std::atomic<int> target_hits{0};
  20931. std::atomic<bool> target_saw_proxy_authz{false};
  20932. no_proxy_test::ScopedServer target;
  20933. target.svr().Get(".*", [&](const Request &req, Response &res) {
  20934. target_hits++;
  20935. if (req.has_header("Proxy-Authorization")) {
  20936. target_saw_proxy_authz = true;
  20937. }
  20938. res.status = StatusCode::ProxyAuthenticationRequired_407;
  20939. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  20940. "nonce=\"abc\", algorithm=MD5");
  20941. });
  20942. target.listen();
  20943. // The proxy address is set to the target's port: the bypass MUST kick in;
  20944. // if it doesn't, the test still routes "via proxy" to the same server and
  20945. // the Proxy-Authorization assertion below catches the leak.
  20946. Client cli("evil.example", target.port());
  20947. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  20948. cli.set_proxy("127.0.0.1", target.port());
  20949. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  20950. cli.set_no_proxy({"evil.example"});
  20951. auto res = cli.Get("/x");
  20952. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20953. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  20954. EXPECT_EQ(1, target_hits.load());
  20955. EXPECT_FALSE(target_saw_proxy_authz.load());
  20956. }
  20957. #endif
  20958. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  20959. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  20960. std::atomic<int> proxy_hits{0};
  20961. std::atomic<int> bypass_hits{0};
  20962. std::atomic<bool> proxy_saw_c_url{false};
  20963. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  20964. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  20965. proxy_hits++;
  20966. if (req.path.find("/start") != std::string::npos) {
  20967. res.status = 302;
  20968. res.set_header("Location", "http://127.0.0.1:" +
  20969. std::to_string(bypass_server.port()) +
  20970. "/middle");
  20971. return;
  20972. }
  20973. if (req.path.find("/end") != std::string::npos) {
  20974. proxy_saw_c_url = true;
  20975. res.set_content("c-via-proxy", "text/plain");
  20976. return;
  20977. }
  20978. res.set_content("unexpected", "text/plain");
  20979. });
  20980. // public.example's "advertised" port is arbitrary (the request never lands
  20981. // there — it goes through the proxy), but use a dynamic value to stay
  20982. // friendly with sharded parallel runs.
  20983. int public_port = bypass_server.port();
  20984. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  20985. bypass_hits++;
  20986. res.status = 302;
  20987. res.set_header("Location", "http://public.example:" +
  20988. std::to_string(public_port) + "/end");
  20989. });
  20990. proxy_mock.listen();
  20991. bypass_server.listen();
  20992. Client cli("public.example", public_port);
  20993. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  20994. cli.set_proxy("127.0.0.1", proxy_mock.port());
  20995. cli.set_no_proxy({"127.0.0.1"});
  20996. cli.set_follow_location(true);
  20997. auto res = cli.Get("/start");
  20998. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20999. EXPECT_EQ(StatusCode::OK_200, res->status);
  21000. EXPECT_EQ("c-via-proxy", res->body);
  21001. EXPECT_GE(proxy_hits.load(), 2);
  21002. EXPECT_GE(bypass_hits.load(), 1);
  21003. EXPECT_TRUE(proxy_saw_c_url.load());
  21004. }
  21005. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  21006. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  21007. // request reconnects to the correct endpoint.
  21008. std::atomic<int> proxy_hits{0};
  21009. std::atomic<int> target_hits{0};
  21010. no_proxy_test::ScopedServer proxy_mock, target;
  21011. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  21012. proxy_hits++;
  21013. res.set_content("via-proxy", "text/plain");
  21014. });
  21015. target.svr().Get(".*", [&](const Request &, Response &res) {
  21016. target_hits++;
  21017. res.set_content("direct", "text/plain");
  21018. });
  21019. proxy_mock.listen();
  21020. target.listen();
  21021. Client cli("public.example", target.port());
  21022. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  21023. cli.set_proxy("127.0.0.1", proxy_mock.port());
  21024. cli.set_keep_alive(true);
  21025. auto res1 = cli.Get("/a");
  21026. ASSERT_TRUE(res1);
  21027. EXPECT_EQ("via-proxy", res1->body);
  21028. EXPECT_EQ(1, proxy_hits.load());
  21029. EXPECT_EQ(0, target_hits.load());
  21030. cli.set_no_proxy({"public.example"});
  21031. auto res2 = cli.Get("/b");
  21032. ASSERT_TRUE(res2);
  21033. EXPECT_EQ("direct", res2->body);
  21034. EXPECT_EQ(1, proxy_hits.load());
  21035. EXPECT_EQ(1, target_hits.load());
  21036. }
  21037. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  21038. namespace proxy_tunnel_test {
  21039. // SSLServer counterpart to no_proxy_test::ScopedServer.
  21040. class ScopedSSLServer {
  21041. public:
  21042. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  21043. port_ = svr_.bind_to_any_port("127.0.0.1");
  21044. }
  21045. ~ScopedSSLServer() {
  21046. svr_.stop();
  21047. if (th_.joinable()) { th_.join(); }
  21048. }
  21049. SSLServer &svr() { return svr_; }
  21050. int port() const { return port_; }
  21051. void listen() {
  21052. th_ = std::thread([this] { svr_.listen_after_bind(); });
  21053. svr_.wait_until_ready();
  21054. }
  21055. private:
  21056. SSLServer svr_;
  21057. std::thread th_;
  21058. int port_ = 0;
  21059. };
  21060. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  21061. class ScopedConnectProxy {
  21062. public:
  21063. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  21064. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  21065. if (listen_fd_ < 0) { return; }
  21066. int yes = 1;
  21067. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  21068. sockaddr_in a{};
  21069. a.sin_family = AF_INET;
  21070. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  21071. a.sin_port = 0;
  21072. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  21073. return;
  21074. }
  21075. socklen_t alen = sizeof(a);
  21076. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  21077. 0) {
  21078. return;
  21079. }
  21080. port_ = ntohs(a.sin_port);
  21081. if (::listen(listen_fd_, 1) != 0) { return; }
  21082. th_ = std::thread([this] { run(); });
  21083. }
  21084. ~ScopedConnectProxy() {
  21085. stop_ = true;
  21086. if (listen_fd_ >= 0) {
  21087. ::shutdown(listen_fd_, SHUT_RDWR);
  21088. ::close(listen_fd_);
  21089. }
  21090. if (th_.joinable()) { th_.join(); }
  21091. }
  21092. int port() const { return port_; }
  21093. int connect_hits() const { return connect_hits_.load(); }
  21094. private:
  21095. void run() {
  21096. while (!stop_.load()) {
  21097. fd_set rfds;
  21098. FD_ZERO(&rfds);
  21099. FD_SET(listen_fd_, &rfds);
  21100. timeval tv{0, 100 * 1000};
  21101. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  21102. if (sel <= 0) { continue; }
  21103. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  21104. if (client_fd < 0) { continue; }
  21105. std::string req;
  21106. char buf[2048];
  21107. while (req.find("\r\n\r\n") == std::string::npos) {
  21108. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  21109. if (n <= 0) { break; }
  21110. req.append(buf, static_cast<size_t>(n));
  21111. }
  21112. if (req.compare(0, 7, "CONNECT") != 0) {
  21113. ::close(client_fd);
  21114. continue;
  21115. }
  21116. connect_hits_++;
  21117. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  21118. ::send(client_fd, ok, std::strlen(ok), 0);
  21119. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  21120. sockaddr_in o{};
  21121. o.sin_family = AF_INET;
  21122. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  21123. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  21124. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  21125. 0) {
  21126. ::close(client_fd);
  21127. ::close(origin_fd);
  21128. continue;
  21129. }
  21130. auto forward = [](int from, int to) {
  21131. char b[8192];
  21132. for (;;) {
  21133. ssize_t n = ::recv(from, b, sizeof(b), 0);
  21134. if (n <= 0) { break; }
  21135. ssize_t off = 0;
  21136. while (off < n) {
  21137. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  21138. if (s <= 0) {
  21139. off = n;
  21140. break;
  21141. }
  21142. off += s;
  21143. }
  21144. }
  21145. ::shutdown(to, SHUT_WR);
  21146. };
  21147. std::thread t1([&] { forward(client_fd, origin_fd); });
  21148. std::thread t2([&] { forward(origin_fd, client_fd); });
  21149. t1.join();
  21150. t2.join();
  21151. ::close(client_fd);
  21152. ::close(origin_fd);
  21153. }
  21154. }
  21155. int forward_port_ = -1;
  21156. int listen_fd_ = -1;
  21157. int port_ = 0;
  21158. std::thread th_;
  21159. std::atomic<bool> stop_{false};
  21160. std::atomic<int> connect_hits_{0};
  21161. };
  21162. } // namespace proxy_tunnel_test
  21163. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  21164. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  21165. // retry; otherwise proxy creds would be sent to the origin.
  21166. std::atomic<int> origin_hits{0};
  21167. std::atomic<bool> origin_saw_proxy_authz{false};
  21168. proxy_tunnel_test::ScopedSSLServer origin;
  21169. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  21170. origin_hits++;
  21171. if (req.has_header("Proxy-Authorization")) {
  21172. origin_saw_proxy_authz = true;
  21173. }
  21174. res.status = StatusCode::ProxyAuthenticationRequired_407;
  21175. res.set_header("Proxy-Authenticate",
  21176. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  21177. "algorithm=MD5");
  21178. });
  21179. origin.listen();
  21180. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  21181. ASSERT_NE(0, proxy.port());
  21182. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  21183. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  21184. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  21185. // and answer with its own status, making this test flaky.
  21186. SSLClient cli("127.0.0.1", origin.port());
  21187. cli.enable_server_certificate_verification(false);
  21188. cli.set_proxy("127.0.0.1", proxy.port());
  21189. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  21190. auto res = cli.Get("/x");
  21191. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21192. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  21193. EXPECT_EQ(1, origin_hits.load());
  21194. EXPECT_FALSE(origin_saw_proxy_authz.load());
  21195. EXPECT_EQ(1, proxy.connect_hits());
  21196. }
  21197. #endif