test.cc 793 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708
  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(GetHeaderValueTest, DefaultValue) {
  1369. Headers headers = {{"Dummy", "Dummy"}};
  1370. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1371. EXPECT_STREQ("text/plain", val);
  1372. }
  1373. TEST(GetHeaderValueTest, DefaultValueInt) {
  1374. Headers headers = {{"Dummy", "Dummy"}};
  1375. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1376. EXPECT_EQ(100ull, val);
  1377. }
  1378. TEST(GetHeaderValueTest, RegularValue) {
  1379. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1380. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1381. EXPECT_STREQ("text/html", val);
  1382. }
  1383. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1384. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1385. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1386. EXPECT_STREQ("text/html", val);
  1387. }
  1388. TEST(GetHeaderValueTest, SetContent) {
  1389. Response res;
  1390. res.set_content("html", "text/html");
  1391. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1392. res.set_content("text", "text/plain");
  1393. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1394. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1395. }
  1396. TEST(GetHeaderValueTest, RegularValueInt) {
  1397. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1398. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1399. EXPECT_EQ(100ull, val);
  1400. }
  1401. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1402. Headers headers = {{"Content-Length", "x"}};
  1403. auto is_invalid_value = false;
  1404. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1405. is_invalid_value);
  1406. EXPECT_EQ(0ull, val);
  1407. EXPECT_TRUE(is_invalid_value);
  1408. }
  1409. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1410. // An all-digit value that overflows size_t must be reported as invalid, not
  1411. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1412. // a large length to a small one on 32-bit builds, leaving the framing length
  1413. // wrong while is_invalid_value stayed false.
  1414. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1415. auto is_invalid_value = false;
  1416. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1417. is_invalid_value);
  1418. EXPECT_TRUE(is_invalid_value);
  1419. // A well-formed length is unaffected.
  1420. Headers ok = {{"Content-Length", "1234"}};
  1421. is_invalid_value = false;
  1422. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1423. is_invalid_value);
  1424. EXPECT_EQ(1234ull, val);
  1425. EXPECT_FALSE(is_invalid_value);
  1426. }
  1427. TEST(GetHeaderValueTest, Range) {
  1428. {
  1429. Headers headers = {make_range_header({{1, -1}})};
  1430. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1431. EXPECT_STREQ("bytes=1-", val);
  1432. }
  1433. {
  1434. Headers headers = {make_range_header({{-1, 1}})};
  1435. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1436. EXPECT_STREQ("bytes=-1", val);
  1437. }
  1438. {
  1439. Headers headers = {make_range_header({{1, 10}})};
  1440. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1441. EXPECT_STREQ("bytes=1-10", val);
  1442. }
  1443. {
  1444. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1445. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1446. EXPECT_STREQ("bytes=1-10, 100-", val);
  1447. }
  1448. {
  1449. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1450. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1451. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1452. }
  1453. {
  1454. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1455. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1456. EXPECT_STREQ("bytes=0-0, -1", val);
  1457. }
  1458. }
  1459. TEST(BearerTokenAuthTest, SchemeValidation) {
  1460. // A value shorter than "Bearer " must not throw from the fixed-length
  1461. // substr, and a non-Bearer scheme must not be reported as a token.
  1462. struct {
  1463. const char *value;
  1464. const char *expected;
  1465. } cases[] = {
  1466. {"x", ""},
  1467. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1468. {"Bearer abc123", "abc123"},
  1469. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1470. };
  1471. for (const auto &c : cases) {
  1472. Request req;
  1473. req.set_header("Authorization", c.value);
  1474. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1475. }
  1476. }
  1477. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1478. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1479. // to depend on the standard library (libstdc++ handed back duplicates in
  1480. // reverse insertion order, libc++ in insertion order).
  1481. Request req;
  1482. req.set_header("Accept-Encoding", "gzip");
  1483. req.set_header("Accept-Encoding", "deflate");
  1484. req.set_header("Accept-Encoding", "br");
  1485. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1486. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1487. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1488. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1489. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1490. }
  1491. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1492. Request req;
  1493. req.set_header("X-Test", "only");
  1494. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1495. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1496. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1497. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1498. }
  1499. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1500. Headers headers;
  1501. headers.emplace("Host", "example.com");
  1502. headers.emplace("Accept-Encoding", "gzip");
  1503. headers.emplace("User-Agent", "test");
  1504. headers.emplace("Accept-Encoding", "deflate");
  1505. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1506. "Accept-Encoding=deflate ",
  1507. entries_to_string(headers));
  1508. }
  1509. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1510. Headers headers = {{"Content-Type", "text/html"},
  1511. {"CONTENT-TYPE", "text/xml"}};
  1512. EXPECT_EQ(2U, headers.count("content-type"));
  1513. auto it = headers.find("content-type");
  1514. ASSERT_TRUE(it != headers.end());
  1515. EXPECT_EQ("text/html", it->second);
  1516. }
  1517. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1518. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1519. // drop only those fields and leave everything positioned between them.
  1520. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1521. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1522. auto rng = headers.equal_range("a");
  1523. headers.erase(rng.first, rng.second);
  1524. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1525. }
  1526. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1527. Headers headers = {
  1528. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1529. EXPECT_EQ(3U, headers.erase("A"));
  1530. EXPECT_EQ(0U, headers.count("A"));
  1531. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1532. }
  1533. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1534. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1535. headers.emplace_front("Host", "example.com");
  1536. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1537. entries_to_string(headers));
  1538. }
  1539. TEST(ParseHeaderValueTest, Range) {
  1540. {
  1541. Ranges ranges;
  1542. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1543. EXPECT_TRUE(ret);
  1544. EXPECT_EQ(1u, ranges.size());
  1545. EXPECT_EQ(1u, ranges[0].first);
  1546. EXPECT_EQ(-1, ranges[0].second);
  1547. }
  1548. {
  1549. Ranges ranges;
  1550. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1551. EXPECT_TRUE(ret);
  1552. EXPECT_EQ(1u, ranges.size());
  1553. EXPECT_EQ(-1, ranges[0].first);
  1554. EXPECT_EQ(1u, ranges[0].second);
  1555. }
  1556. {
  1557. Ranges ranges;
  1558. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1559. EXPECT_TRUE(ret);
  1560. EXPECT_EQ(1u, ranges.size());
  1561. EXPECT_EQ(1u, ranges[0].first);
  1562. EXPECT_EQ(10u, ranges[0].second);
  1563. }
  1564. {
  1565. Ranges ranges;
  1566. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1567. EXPECT_FALSE(ret);
  1568. }
  1569. {
  1570. Ranges ranges;
  1571. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1572. EXPECT_TRUE(ret);
  1573. EXPECT_EQ(2u, ranges.size());
  1574. EXPECT_EQ(1u, ranges[0].first);
  1575. EXPECT_EQ(10u, ranges[0].second);
  1576. EXPECT_EQ(100u, ranges[1].first);
  1577. EXPECT_EQ(-1, ranges[1].second);
  1578. }
  1579. {
  1580. Ranges ranges;
  1581. auto ret =
  1582. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1583. EXPECT_TRUE(ret);
  1584. EXPECT_EQ(3u, ranges.size());
  1585. EXPECT_EQ(1u, ranges[0].first);
  1586. EXPECT_EQ(10u, ranges[0].second);
  1587. EXPECT_EQ(100u, ranges[1].first);
  1588. EXPECT_EQ(200u, ranges[1].second);
  1589. EXPECT_EQ(300u, ranges[2].first);
  1590. EXPECT_EQ(400u, ranges[2].second);
  1591. }
  1592. {
  1593. Ranges ranges;
  1594. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1595. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1596. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1597. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1598. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1599. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1600. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1601. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1602. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1603. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1604. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1605. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1606. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1607. EXPECT_TRUE(ranges.empty());
  1608. }
  1609. }
  1610. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  1611. Request req;
  1612. req.set_header("Accept-Encoding", "gzip");
  1613. Response res;
  1614. res.set_header("Content-Type", "text/plain");
  1615. auto ret = detail::encoding_type(req, res);
  1616. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1617. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1618. #else
  1619. EXPECT_TRUE(ret == detail::EncodingType::None);
  1620. #endif
  1621. }
  1622. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1623. Request req;
  1624. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  1625. Response res;
  1626. res.set_header("Content-Type", "text/plain");
  1627. auto ret = detail::encoding_type(req, res);
  1628. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1629. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1630. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1631. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1632. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1633. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1634. #else
  1635. EXPECT_TRUE(ret == detail::EncodingType::None);
  1636. #endif
  1637. }
  1638. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  1639. Request req;
  1640. req.set_header("Accept-Encoding",
  1641. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  1642. Response res;
  1643. res.set_header("Content-Type", "text/plain");
  1644. auto ret = detail::encoding_type(req, res);
  1645. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1646. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1647. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1648. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1649. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1650. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1651. #else
  1652. EXPECT_TRUE(ret == detail::EncodingType::None);
  1653. #endif
  1654. }
  1655. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  1656. // All supported encodings rejected with q=0 should return None
  1657. Request req;
  1658. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  1659. Response res;
  1660. res.set_header("Content-Type", "text/plain");
  1661. auto ret = detail::encoding_type(req, res);
  1662. EXPECT_TRUE(ret == detail::EncodingType::None);
  1663. }
  1664. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1665. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1666. Request req;
  1667. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1668. Response res;
  1669. res.set_header("Content-Type", "text/plain");
  1670. auto ret = detail::encoding_type(req, res);
  1671. EXPECT_TRUE(ret == detail::EncodingType::None);
  1672. }
  1673. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1674. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1675. Request req;
  1676. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1677. Response res;
  1678. res.set_header("Content-Type", "text/plain");
  1679. auto ret = detail::encoding_type(req, res);
  1680. EXPECT_TRUE(ret == detail::EncodingType::None);
  1681. }
  1682. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1683. // RFC 7231: Accept-Encoding values are case-insensitive
  1684. Request req;
  1685. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1686. Response res;
  1687. res.set_header("Content-Type", "text/plain");
  1688. auto ret = detail::encoding_type(req, res);
  1689. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1690. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1691. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1692. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1693. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1694. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1695. #else
  1696. EXPECT_TRUE(ret == detail::EncodingType::None);
  1697. #endif
  1698. }
  1699. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1700. // q value should determine priority, not hardcoded order
  1701. Request req;
  1702. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  1703. Response res;
  1704. res.set_header("Content-Type", "text/plain");
  1705. auto ret = detail::encoding_type(req, res);
  1706. // gzip has highest q=1.0, so it should be selected even though
  1707. // br and zstd are also supported
  1708. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1709. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1710. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1711. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1712. #elif CPPHTTPLIB_BROTLI_SUPPORT
  1713. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1714. #else
  1715. EXPECT_TRUE(ret == detail::EncodingType::None);
  1716. #endif
  1717. }
  1718. TEST(BufferStreamTest, read) {
  1719. detail::BufferStream strm1;
  1720. Stream &strm = strm1;
  1721. EXPECT_EQ(5, strm.write("hello"));
  1722. char buf[512];
  1723. EXPECT_EQ(2, strm.read(buf, 2));
  1724. EXPECT_EQ('h', buf[0]);
  1725. EXPECT_EQ('e', buf[1]);
  1726. EXPECT_EQ(2, strm.read(buf, 2));
  1727. EXPECT_EQ('l', buf[0]);
  1728. EXPECT_EQ('l', buf[1]);
  1729. EXPECT_EQ(1, strm.read(buf, 1));
  1730. EXPECT_EQ('o', buf[0]);
  1731. EXPECT_EQ(0, strm.read(buf, 1));
  1732. }
  1733. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1734. auto host = "www.httpwatch.com";
  1735. auto ip = hosted_at(host);
  1736. EXPECT_EQ("23.96.13.243", ip);
  1737. std::vector<std::string> addrs;
  1738. hosted_at(host, addrs);
  1739. EXPECT_EQ(1u, addrs.size());
  1740. }
  1741. #if 0 // It depends on each test environment...
  1742. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1743. auto host = "www.youtube.com";
  1744. std::vector<std::string> addrs;
  1745. hosted_at(host, addrs);
  1746. EXPECT_EQ(20u, addrs.size());
  1747. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1748. EXPECT_TRUE(it != addrs.end());
  1749. }
  1750. #endif
  1751. class ChunkedEncodingTest : public ::testing::Test {
  1752. protected:
  1753. ChunkedEncodingTest()
  1754. : cli_(HOST, PORT)
  1755. #ifdef CPPHTTPLIB_SSL_ENABLED
  1756. ,
  1757. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1758. #endif
  1759. {
  1760. cli_.set_connection_timeout(2);
  1761. #ifdef CPPHTTPLIB_SSL_ENABLED
  1762. cli_.enable_server_certificate_verification(false);
  1763. #endif
  1764. }
  1765. virtual void SetUp() {
  1766. read_file("./image.jpg", image_data_);
  1767. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1768. res.set_content("Hello World!", "text/plain");
  1769. });
  1770. svr_.Get(
  1771. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1772. res.set_chunked_content_provider(
  1773. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1774. size_t remaining = image_data_.size() - offset;
  1775. if (remaining == 0) {
  1776. sink.done();
  1777. } else {
  1778. constexpr size_t CHUNK_SIZE = 1024;
  1779. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1780. sink.write(&image_data_[offset], send_size);
  1781. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1782. }
  1783. return true;
  1784. });
  1785. });
  1786. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1787. svr_.wait_until_ready();
  1788. }
  1789. virtual void TearDown() {
  1790. svr_.stop();
  1791. if (!request_threads_.empty()) {
  1792. std::this_thread::sleep_for(std::chrono::seconds(1));
  1793. for (auto &t : request_threads_) {
  1794. t.join();
  1795. }
  1796. }
  1797. t_.join();
  1798. }
  1799. #ifdef CPPHTTPLIB_SSL_ENABLED
  1800. SSLClient cli_;
  1801. SSLServer svr_;
  1802. #else
  1803. Client cli_;
  1804. Server svr_;
  1805. #endif
  1806. thread t_;
  1807. std::vector<thread> request_threads_;
  1808. std::string image_data_;
  1809. };
  1810. TEST_F(ChunkedEncodingTest, NormalGet) {
  1811. auto res = cli_.Get("/chunked");
  1812. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1813. std::string out;
  1814. read_file("./image.jpg", out);
  1815. EXPECT_EQ(StatusCode::OK_200, res->status);
  1816. EXPECT_EQ(out, res->body);
  1817. }
  1818. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1819. std::string body;
  1820. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1821. body.append(data, data_length);
  1822. return true;
  1823. });
  1824. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1825. std::string out;
  1826. read_file("./image.jpg", out);
  1827. EXPECT_EQ(StatusCode::OK_200, res->status);
  1828. EXPECT_EQ(out, body);
  1829. }
  1830. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1831. std::string body;
  1832. auto res = cli_.Get(
  1833. "/chunked",
  1834. [&](const Response &response) {
  1835. EXPECT_EQ(StatusCode::OK_200, response.status);
  1836. return true;
  1837. },
  1838. [&](const char *data, size_t data_length) {
  1839. body.append(data, data_length);
  1840. return true;
  1841. });
  1842. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1843. std::string out;
  1844. read_file("./image.jpg", out);
  1845. EXPECT_EQ(StatusCode::OK_200, res->status);
  1846. EXPECT_EQ(out, body);
  1847. }
  1848. TEST(RangeTest, FromHTTPBin_Online) {
  1849. auto host = "httpbingo.org";
  1850. auto path = std::string{"/range/32"};
  1851. #ifdef CPPHTTPLIB_SSL_ENABLED
  1852. auto port = 443;
  1853. SSLClient cli(host, port);
  1854. #else
  1855. auto port = 80;
  1856. Client cli(host, port);
  1857. #endif
  1858. cli.set_connection_timeout(5);
  1859. {
  1860. auto res = cli.Get(path);
  1861. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1862. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1863. EXPECT_EQ(StatusCode::OK_200, res->status);
  1864. }
  1865. {
  1866. Headers headers = {make_range_header({{1, -1}})};
  1867. auto res = cli.Get(path, headers);
  1868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1869. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1870. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1871. }
  1872. {
  1873. Headers headers = {make_range_header({{1, 10}})};
  1874. auto res = cli.Get(path, headers);
  1875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1876. EXPECT_EQ("bcdefghijk", res->body);
  1877. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1878. }
  1879. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  1880. // entire resource, while the original httpbin returned 200. Both are
  1881. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  1882. {
  1883. Headers headers = {make_range_header({{0, 31}})};
  1884. auto res = cli.Get(path, headers);
  1885. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1886. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1887. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1888. res->status == StatusCode::PartialContent_206);
  1889. }
  1890. {
  1891. Headers headers = {make_range_header({{0, -1}})};
  1892. auto res = cli.Get(path, headers);
  1893. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1894. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1895. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1896. res->status == StatusCode::PartialContent_206);
  1897. }
  1898. // go-httpbin returns 206 with clamped range for over-range requests,
  1899. // while the original httpbin returned 416. Both behaviors are observed
  1900. // in real servers, so we only verify the request succeeds.
  1901. {
  1902. Headers headers = {make_range_header({{0, 32}})};
  1903. auto res = cli.Get(path, headers);
  1904. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1905. }
  1906. }
  1907. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1908. auto host = "unresolvableaddress.local";
  1909. auto path = std::string{"/"};
  1910. #ifdef CPPHTTPLIB_SSL_ENABLED
  1911. auto port = 443;
  1912. SSLClient cli(host, port);
  1913. #else
  1914. auto port = 80;
  1915. Client cli(host, port);
  1916. #endif
  1917. cli.set_connection_timeout(1);
  1918. {
  1919. auto res = cli.Get(path);
  1920. ASSERT_FALSE(res);
  1921. }
  1922. std::this_thread::sleep_for(std::chrono::seconds(8));
  1923. }
  1924. #if defined(__linux__) && defined(__GLIBC__) && \
  1925. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  1926. // Forward declaration: in split builds split.py strips `inline` and moves the
  1927. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  1928. // visible from the public httplib.h. Re-declaring it here lets the tests link
  1929. // against the symbol in both header-only and split builds.
  1930. namespace httplib {
  1931. namespace detail {
  1932. int getaddrinfo_with_timeout(const char *node, const char *service,
  1933. const struct addrinfo *hints,
  1934. struct addrinfo **res, time_t timeout_sec);
  1935. } // namespace detail
  1936. } // namespace httplib
  1937. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  1938. //
  1939. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  1940. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  1941. // gai_suspend() call hits the connection timeout the function calls
  1942. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  1943. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  1944. // still alive and still references the now-destroyed stack frame.
  1945. //
  1946. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  1947. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  1948. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  1949. // and runs them in a container.
  1950. namespace {
  1951. bool should_run_issue_2431_tests() {
  1952. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  1953. return v && *v && std::string(v) != "0";
  1954. }
  1955. std::string unique_unresolvable_host(int n) {
  1956. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  1957. // glibc still asks the configured nameserver — which is exactly the path
  1958. // we want to exercise. A unique label per call avoids the resolver cache.
  1959. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  1960. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  1961. std::to_string(n) + ".invalid";
  1962. }
  1963. } // namespace
  1964. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  1965. if (!should_run_issue_2431_tests()) {
  1966. GTEST_SKIP()
  1967. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1968. }
  1969. for (int i = 0; i < 8; ++i) {
  1970. struct addrinfo hints;
  1971. memset(&hints, 0, sizeof(hints));
  1972. hints.ai_family = AF_UNSPEC;
  1973. hints.ai_socktype = SOCK_STREAM;
  1974. auto host = unique_unresolvable_host(i);
  1975. struct addrinfo *result = nullptr;
  1976. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1977. &result, /*timeout_sec=*/1);
  1978. if (rc == 0 && result) { freeaddrinfo(result); }
  1979. }
  1980. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  1981. // stack region they still believe holds their gaicb.
  1982. std::this_thread::sleep_for(std::chrono::seconds(3));
  1983. }
  1984. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  1985. if (!should_run_issue_2431_tests()) {
  1986. GTEST_SKIP()
  1987. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1988. }
  1989. std::atomic<bool> stop{false};
  1990. std::vector<std::thread> threads;
  1991. for (int t = 0; t < 8; ++t) {
  1992. threads.emplace_back([t, &stop] {
  1993. int i = 0;
  1994. while (!stop.load(std::memory_order_relaxed)) {
  1995. struct addrinfo hints;
  1996. memset(&hints, 0, sizeof(hints));
  1997. hints.ai_family = AF_UNSPEC;
  1998. hints.ai_socktype = SOCK_STREAM;
  1999. auto host = unique_unresolvable_host(t * 100000 + i++);
  2000. struct addrinfo *result = nullptr;
  2001. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2002. &result, /*timeout_sec=*/1);
  2003. if (rc == 0 && result) { freeaddrinfo(result); }
  2004. }
  2005. });
  2006. }
  2007. std::this_thread::sleep_for(std::chrono::seconds(8));
  2008. stop.store(true, std::memory_order_relaxed);
  2009. for (auto &th : threads) {
  2010. th.join();
  2011. }
  2012. std::this_thread::sleep_for(std::chrono::seconds(3));
  2013. }
  2014. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2015. if (!should_run_issue_2431_tests()) {
  2016. GTEST_SKIP()
  2017. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2018. }
  2019. std::atomic<bool> stop{false};
  2020. std::vector<std::thread> threads;
  2021. for (int t = 0; t < 8; ++t) {
  2022. threads.emplace_back([t, &stop] {
  2023. int i = 0;
  2024. while (!stop.load(std::memory_order_relaxed)) {
  2025. auto host = unique_unresolvable_host(t * 100000 + i++);
  2026. Client cli(host, 80);
  2027. cli.set_connection_timeout(1, 0);
  2028. cli.set_read_timeout(1, 0);
  2029. cli.set_write_timeout(1, 0);
  2030. (void)cli.Get("/");
  2031. }
  2032. });
  2033. }
  2034. std::this_thread::sleep_for(std::chrono::seconds(8));
  2035. stop.store(true, std::memory_order_relaxed);
  2036. for (auto &th : threads) {
  2037. th.join();
  2038. }
  2039. std::this_thread::sleep_for(std::chrono::seconds(3));
  2040. }
  2041. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2042. TEST(ConnectionErrorTest, InvalidHost) {
  2043. auto host = "-abcde.com";
  2044. #ifdef CPPHTTPLIB_SSL_ENABLED
  2045. auto port = 443;
  2046. SSLClient cli(host, port);
  2047. #else
  2048. auto port = 80;
  2049. Client cli(host, port);
  2050. #endif
  2051. cli.set_connection_timeout(std::chrono::seconds(2));
  2052. auto res = cli.Get("/");
  2053. ASSERT_TRUE(!res);
  2054. EXPECT_EQ(Error::Connection, res.error());
  2055. }
  2056. TEST(ConnectionErrorTest, InvalidHost2) {
  2057. auto host = "httpcan.org/";
  2058. #ifdef CPPHTTPLIB_SSL_ENABLED
  2059. SSLClient cli(host);
  2060. #else
  2061. Client cli(host);
  2062. #endif
  2063. cli.set_connection_timeout(std::chrono::seconds(2));
  2064. auto res = cli.Get("/");
  2065. ASSERT_TRUE(!res);
  2066. EXPECT_EQ(Error::Connection, res.error());
  2067. }
  2068. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2069. auto host = "httpcan.org/";
  2070. #ifdef CPPHTTPLIB_SSL_ENABLED
  2071. SSLClient cli(host);
  2072. #else
  2073. Client cli(host);
  2074. #endif
  2075. cli.set_connection_timeout(std::chrono::seconds(2));
  2076. auto res = cli.Get("/");
  2077. ASSERT_TRUE(!res);
  2078. stringstream s;
  2079. s << "error code: " << res.error();
  2080. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2081. }
  2082. TEST(ConnectionErrorTest, InvalidPort) {
  2083. auto host = "localhost";
  2084. auto port = 44380;
  2085. #ifdef CPPHTTPLIB_SSL_ENABLED
  2086. SSLClient cli(host, port);
  2087. #else
  2088. Client cli(host, port);
  2089. #endif
  2090. cli.set_connection_timeout(std::chrono::seconds(2));
  2091. auto res = cli.Get("/");
  2092. ASSERT_TRUE(!res);
  2093. EXPECT_TRUE(Error::Connection == res.error() ||
  2094. Error::ConnectionTimeout == res.error());
  2095. }
  2096. TEST(ConnectionErrorTest, Timeout_Online) {
  2097. auto host = "google.com";
  2098. #ifdef CPPHTTPLIB_SSL_ENABLED
  2099. auto port = 44380;
  2100. SSLClient cli(host, port);
  2101. #else
  2102. auto port = 8080;
  2103. Client cli(host, port);
  2104. #endif
  2105. cli.set_connection_timeout(std::chrono::seconds(2));
  2106. // only probe one address type so that the error reason
  2107. // correlates to the timed-out IPv4, not the unsupported
  2108. // IPv6 connection attempt
  2109. cli.set_address_family(AF_INET);
  2110. auto res = cli.Get("/");
  2111. ASSERT_TRUE(!res);
  2112. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2113. }
  2114. TEST(CancelTest, NoCancel_Online) {
  2115. auto host = "httpbingo.org";
  2116. auto path = std::string{"/range/32"};
  2117. #ifdef CPPHTTPLIB_SSL_ENABLED
  2118. auto port = 443;
  2119. SSLClient cli(host, port);
  2120. #else
  2121. auto port = 80;
  2122. Client cli(host, port);
  2123. #endif
  2124. cli.set_connection_timeout(std::chrono::seconds(5));
  2125. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2126. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2127. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2128. EXPECT_EQ(StatusCode::OK_200, res->status);
  2129. }
  2130. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2131. // Use /bytes with a large payload so that the DownloadProgress callback
  2132. // (which only fires for Content-Length responses) is invoked before the
  2133. // entire body is received, giving cancellation a chance to fire.
  2134. auto host = "httpbingo.org";
  2135. auto path = std::string{"/bytes/524288"};
  2136. #ifdef CPPHTTPLIB_SSL_ENABLED
  2137. auto port = 443;
  2138. SSLClient cli(host, port);
  2139. #else
  2140. auto port = 80;
  2141. Client cli(host, port);
  2142. #endif
  2143. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2144. cli.set_connection_timeout(std::chrono::seconds(5));
  2145. ASSERT_TRUE(!res);
  2146. EXPECT_EQ(Error::Canceled, res.error());
  2147. }
  2148. TEST(CancelTest, WithCancelLargePayload_Online) {
  2149. auto host = "httpbingo.org";
  2150. auto path = std::string{"/bytes/524288"};
  2151. #ifdef CPPHTTPLIB_SSL_ENABLED
  2152. auto port = 443;
  2153. SSLClient cli(host, port);
  2154. #else
  2155. auto port = 80;
  2156. Client cli(host, port);
  2157. #endif
  2158. cli.set_connection_timeout(std::chrono::seconds(5));
  2159. uint32_t count = 0;
  2160. auto res =
  2161. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2162. ASSERT_TRUE(!res);
  2163. EXPECT_EQ(Error::Canceled, res.error());
  2164. }
  2165. TEST(CancelTest, NoCancelPost) {
  2166. Server svr;
  2167. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2168. res.set_content("Hello World!", "text/plain");
  2169. });
  2170. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2171. auto se = detail::scope_exit([&] {
  2172. svr.stop();
  2173. thread.join();
  2174. ASSERT_FALSE(svr.is_running());
  2175. });
  2176. svr.wait_until_ready();
  2177. Client cli(HOST, PORT);
  2178. cli.set_connection_timeout(std::chrono::seconds(5));
  2179. auto res =
  2180. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2181. "application/json", [](uint64_t, uint64_t) { return true; });
  2182. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2183. EXPECT_EQ("Hello World!", res->body);
  2184. EXPECT_EQ(StatusCode::OK_200, res->status);
  2185. }
  2186. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2187. Server svr;
  2188. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2189. res.set_content("Hello World!", "text/plain");
  2190. });
  2191. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2192. auto se = detail::scope_exit([&] {
  2193. svr.stop();
  2194. thread.join();
  2195. ASSERT_FALSE(svr.is_running());
  2196. });
  2197. svr.wait_until_ready();
  2198. Client cli(HOST, PORT);
  2199. cli.set_connection_timeout(std::chrono::seconds(5));
  2200. auto res =
  2201. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2202. "application/json", [](uint64_t, uint64_t) { return false; });
  2203. ASSERT_TRUE(!res);
  2204. EXPECT_EQ(Error::Canceled, res.error());
  2205. }
  2206. TEST(CancelTest, WithCancelLargePayloadPost) {
  2207. Server svr;
  2208. svr.set_payload_max_length(200 * 1024 * 1024);
  2209. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2210. res.set_content(LARGE_DATA, "text/plain");
  2211. });
  2212. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2213. auto se = detail::scope_exit([&] {
  2214. svr.stop();
  2215. thread.join();
  2216. ASSERT_FALSE(svr.is_running());
  2217. });
  2218. svr.wait_until_ready();
  2219. Client cli(HOST, PORT);
  2220. cli.set_payload_max_length(200 * 1024 * 1024);
  2221. cli.set_connection_timeout(std::chrono::seconds(5));
  2222. auto res =
  2223. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2224. "application/json", [](uint64_t, uint64_t) { return false; });
  2225. ASSERT_TRUE(!res);
  2226. EXPECT_EQ(Error::Canceled, res.error());
  2227. }
  2228. TEST(CancelTest, NoCancelPut) {
  2229. Server svr;
  2230. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2231. res.set_content("Hello World!", "text/plain");
  2232. });
  2233. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2234. auto se = detail::scope_exit([&] {
  2235. svr.stop();
  2236. thread.join();
  2237. ASSERT_FALSE(svr.is_running());
  2238. });
  2239. svr.wait_until_ready();
  2240. Client cli(HOST, PORT);
  2241. cli.set_connection_timeout(std::chrono::seconds(5));
  2242. auto res =
  2243. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2244. "application/json", [](uint64_t, uint64_t) { return true; });
  2245. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2246. EXPECT_EQ("Hello World!", res->body);
  2247. EXPECT_EQ(StatusCode::OK_200, res->status);
  2248. }
  2249. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2250. Server svr;
  2251. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2252. res.set_content("Hello World!", "text/plain");
  2253. });
  2254. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2255. auto se = detail::scope_exit([&] {
  2256. svr.stop();
  2257. thread.join();
  2258. ASSERT_FALSE(svr.is_running());
  2259. });
  2260. svr.wait_until_ready();
  2261. Client cli(HOST, PORT);
  2262. cli.set_connection_timeout(std::chrono::seconds(5));
  2263. auto res =
  2264. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2265. "application/json", [](uint64_t, uint64_t) { return false; });
  2266. ASSERT_TRUE(!res);
  2267. EXPECT_EQ(Error::Canceled, res.error());
  2268. }
  2269. TEST(CancelTest, WithCancelLargePayloadPut) {
  2270. Server svr;
  2271. svr.set_payload_max_length(200 * 1024 * 1024);
  2272. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2273. res.set_content(LARGE_DATA, "text/plain");
  2274. });
  2275. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2276. auto se = detail::scope_exit([&] {
  2277. svr.stop();
  2278. thread.join();
  2279. ASSERT_FALSE(svr.is_running());
  2280. });
  2281. svr.wait_until_ready();
  2282. Client cli(HOST, PORT);
  2283. cli.set_payload_max_length(200 * 1024 * 1024);
  2284. cli.set_connection_timeout(std::chrono::seconds(5));
  2285. auto res =
  2286. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2287. "application/json", [](uint64_t, uint64_t) { return false; });
  2288. ASSERT_TRUE(!res);
  2289. EXPECT_EQ(Error::Canceled, res.error());
  2290. }
  2291. TEST(CancelTest, NoCancelPatch) {
  2292. Server svr;
  2293. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2294. res.set_content("Hello World!", "text/plain");
  2295. });
  2296. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2297. auto se = detail::scope_exit([&] {
  2298. svr.stop();
  2299. thread.join();
  2300. ASSERT_FALSE(svr.is_running());
  2301. });
  2302. svr.wait_until_ready();
  2303. Client cli(HOST, PORT);
  2304. cli.set_connection_timeout(std::chrono::seconds(5));
  2305. auto res =
  2306. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2307. "application/json", [](uint64_t, uint64_t) { return true; });
  2308. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2309. EXPECT_EQ("Hello World!", res->body);
  2310. EXPECT_EQ(StatusCode::OK_200, res->status);
  2311. }
  2312. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2313. Server svr;
  2314. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2315. res.set_content("Hello World!", "text/plain");
  2316. });
  2317. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2318. auto se = detail::scope_exit([&] {
  2319. svr.stop();
  2320. thread.join();
  2321. ASSERT_FALSE(svr.is_running());
  2322. });
  2323. svr.wait_until_ready();
  2324. Client cli(HOST, PORT);
  2325. cli.set_connection_timeout(std::chrono::seconds(5));
  2326. auto res =
  2327. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2328. "application/json", [](uint64_t, uint64_t) { return false; });
  2329. ASSERT_TRUE(!res);
  2330. EXPECT_EQ(Error::Canceled, res.error());
  2331. }
  2332. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2333. Server svr;
  2334. svr.set_payload_max_length(200 * 1024 * 1024);
  2335. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2336. res.set_content(LARGE_DATA, "text/plain");
  2337. });
  2338. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2339. auto se = detail::scope_exit([&] {
  2340. svr.stop();
  2341. thread.join();
  2342. ASSERT_FALSE(svr.is_running());
  2343. });
  2344. svr.wait_until_ready();
  2345. Client cli(HOST, PORT);
  2346. cli.set_payload_max_length(200 * 1024 * 1024);
  2347. cli.set_connection_timeout(std::chrono::seconds(5));
  2348. auto res =
  2349. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2350. "application/json", [](uint64_t, uint64_t) { return false; });
  2351. ASSERT_TRUE(!res);
  2352. EXPECT_EQ(Error::Canceled, res.error());
  2353. }
  2354. TEST(CancelTest, NoCancelDelete) {
  2355. Server svr;
  2356. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2357. res.set_content("Hello World!", "text/plain");
  2358. });
  2359. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2360. auto se = detail::scope_exit([&] {
  2361. svr.stop();
  2362. thread.join();
  2363. ASSERT_FALSE(svr.is_running());
  2364. });
  2365. svr.wait_until_ready();
  2366. Client cli(HOST, PORT);
  2367. cli.set_connection_timeout(std::chrono::seconds(5));
  2368. auto res =
  2369. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2370. "application/json", [](uint64_t, uint64_t) { return true; });
  2371. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2372. EXPECT_EQ("Hello World!", res->body);
  2373. EXPECT_EQ(StatusCode::OK_200, res->status);
  2374. }
  2375. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2376. Server svr;
  2377. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2378. res.set_content("Hello World!", "text/plain");
  2379. });
  2380. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2381. auto se = detail::scope_exit([&] {
  2382. svr.stop();
  2383. thread.join();
  2384. ASSERT_FALSE(svr.is_running());
  2385. });
  2386. svr.wait_until_ready();
  2387. Client cli(HOST, PORT);
  2388. cli.set_connection_timeout(std::chrono::seconds(5));
  2389. auto res =
  2390. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2391. "application/json", [](uint64_t, uint64_t) { return false; });
  2392. ASSERT_TRUE(!res);
  2393. EXPECT_EQ(Error::Canceled, res.error());
  2394. }
  2395. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2396. Server svr;
  2397. svr.set_payload_max_length(200 * 1024 * 1024);
  2398. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2399. res.set_content(LARGE_DATA, "text/plain");
  2400. });
  2401. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2402. auto se = detail::scope_exit([&] {
  2403. svr.stop();
  2404. thread.join();
  2405. ASSERT_FALSE(svr.is_running());
  2406. });
  2407. svr.wait_until_ready();
  2408. Client cli(HOST, PORT);
  2409. cli.set_payload_max_length(200 * 1024 * 1024);
  2410. cli.set_connection_timeout(std::chrono::seconds(5));
  2411. auto res =
  2412. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2413. "application/json", [](uint64_t, uint64_t) { return false; });
  2414. ASSERT_TRUE(!res);
  2415. EXPECT_EQ(Error::Canceled, res.error());
  2416. }
  2417. static std::string remove_whitespace(const std::string &input) {
  2418. std::string output;
  2419. output.reserve(input.size());
  2420. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2421. [](unsigned char c) { return !std::isspace(c); });
  2422. return output;
  2423. }
  2424. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2425. auto host = "httpbingo.org";
  2426. auto path = std::string{"/basic-auth/hello/world"};
  2427. #ifdef CPPHTTPLIB_SSL_ENABLED
  2428. auto port = 443;
  2429. SSLClient cli(host, port);
  2430. #else
  2431. auto port = 80;
  2432. Client cli(host, port);
  2433. #endif
  2434. {
  2435. auto res = cli.Get(path);
  2436. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2437. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2438. }
  2439. {
  2440. auto res = cli.Get(
  2441. path, Headers{make_basic_authentication_header("hello", "world")});
  2442. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2443. auto body = remove_whitespace(res->body);
  2444. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2445. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2446. EXPECT_EQ(StatusCode::OK_200, res->status);
  2447. }
  2448. {
  2449. cli.set_basic_auth("hello", "world");
  2450. auto res = cli.Get(path);
  2451. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2452. auto body = remove_whitespace(res->body);
  2453. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2454. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2455. EXPECT_EQ(StatusCode::OK_200, res->status);
  2456. }
  2457. {
  2458. cli.set_basic_auth("hello", "bad");
  2459. auto res = cli.Get(path);
  2460. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2461. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2462. }
  2463. {
  2464. cli.set_basic_auth("bad", "world");
  2465. auto res = cli.Get(path);
  2466. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2467. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2468. }
  2469. }
  2470. #ifdef CPPHTTPLIB_SSL_ENABLED
  2471. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2472. auto host = "httpbingo.org";
  2473. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2474. auto paths = std::vector<std::string>{
  2475. "/digest-auth/auth/hello/world/MD5",
  2476. "/digest-auth/auth/hello/world/SHA-256",
  2477. };
  2478. auto port = 443;
  2479. SSLClient cli(host, port);
  2480. {
  2481. auto res = cli.Get(unauth_path);
  2482. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2483. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2484. }
  2485. {
  2486. cli.set_digest_auth("hello", "world");
  2487. for (const auto &path : paths) {
  2488. auto res = cli.Get(path.c_str());
  2489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2490. auto body = remove_whitespace(res->body);
  2491. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2492. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2493. EXPECT_EQ(StatusCode::OK_200, res->status);
  2494. }
  2495. cli.set_digest_auth("hello", "bad");
  2496. for (const auto &path : paths) {
  2497. auto res = cli.Get(path.c_str());
  2498. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2499. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2500. }
  2501. }
  2502. }
  2503. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2504. // comma-separated list of challenges, and each challenge may itself carry a
  2505. // comma-separated auth-param list, so a server can legally offer Basic
  2506. // before Digest, either as two field lines or packed into one. Runs one 401
  2507. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2508. // value() joins them in receipt order) and checks that the retry carries a
  2509. // well-formed Digest Authorization header naming expected_realm.
  2510. static void
  2511. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2512. const std::string &expected_realm) {
  2513. std::atomic<int> hits{0};
  2514. Server svr;
  2515. svr.Get("/x", [&](const Request &req, Response &res) {
  2516. if (++hits == 1) {
  2517. res.status = StatusCode::Unauthorized_401;
  2518. for (const auto &challenge : challenges) {
  2519. res.set_header("WWW-Authenticate", challenge);
  2520. }
  2521. } else {
  2522. auto authorization = req.get_header_value("Authorization");
  2523. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2524. EXPECT_NE(std::string::npos,
  2525. authorization.find("realm=\"" + expected_realm + "\""));
  2526. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2527. res.set_content("ok", "text/plain");
  2528. }
  2529. });
  2530. auto port = svr.bind_to_any_port(HOST);
  2531. std::thread t([&]() { svr.listen_after_bind(); });
  2532. auto se = detail::scope_exit([&] {
  2533. svr.stop();
  2534. t.join();
  2535. });
  2536. svr.wait_until_ready();
  2537. Client cli(HOST, port);
  2538. cli.set_digest_auth("hello", "world");
  2539. auto res = cli.Get("/x");
  2540. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2541. EXPECT_EQ(2, hits.load());
  2542. }
  2543. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2544. static const char *kDigestChallenge =
  2545. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2546. "algorithm=MD5";
  2547. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2548. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2549. "testrealm");
  2550. }
  2551. // Same challenge list with the schemes in the opposite order, to make sure
  2552. // the fix above didn't just special-case "Basic first".
  2553. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2554. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2555. "testrealm");
  2556. }
  2557. // A comma inside a quoted auth-param value must not be mistaken for the
  2558. // separator between two challenges (or two auth-params).
  2559. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2560. run_digest_challenge_list_test(
  2561. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  2562. "algorithm=MD5"},
  2563. "test,realm");
  2564. }
  2565. #endif
  2566. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  2567. auto host = "google.com";
  2568. auto another_host = "example.com";
  2569. auto wrong_ip = "0.0.0.0";
  2570. #ifdef CPPHTTPLIB_SSL_ENABLED
  2571. SSLClient cli(host);
  2572. #else
  2573. Client cli(host);
  2574. #endif
  2575. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  2576. auto res = cli.Get("/");
  2577. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2578. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  2579. }
  2580. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  2581. auto host = "google.com";
  2582. auto wrong_ip = "0.0.0.0";
  2583. #ifdef CPPHTTPLIB_SSL_ENABLED
  2584. SSLClient cli(host);
  2585. #else
  2586. Client cli(host);
  2587. #endif
  2588. cli.set_hostname_addr_map({{host, wrong_ip}});
  2589. auto res = cli.Get("/");
  2590. ASSERT_TRUE(!res);
  2591. EXPECT_EQ(Error::Connection, res.error());
  2592. }
  2593. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  2594. // A mapped value that is not an IP literal must be resolved. "localhost"
  2595. // resolves from the hosts file, so this test needs no external DNS.
  2596. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  2597. auto host = "target.invalid";
  2598. Server svr;
  2599. std::string received_host;
  2600. svr.Get("/hi", [&](const Request &req, Response &res) {
  2601. received_host = req.get_header_value("Host");
  2602. res.set_content("Hello World!", "text/plain");
  2603. });
  2604. auto port = svr.bind_to_any_port(HOST);
  2605. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2606. auto se = detail::scope_exit([&] {
  2607. svr.stop();
  2608. thread.join();
  2609. ASSERT_FALSE(svr.is_running());
  2610. });
  2611. svr.wait_until_ready();
  2612. Client cli(host, port);
  2613. cli.set_hostname_addr_map({{host, HOST}});
  2614. auto res = cli.Get("/hi");
  2615. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2616. EXPECT_EQ(StatusCode::OK_200, res->status);
  2617. // The mapping only redirects the connection; the identity stays host_.
  2618. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  2619. }
  2620. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  2621. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  2622. auto host = "target.invalid";
  2623. Server svr;
  2624. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2625. res.set_content("Hello World!", "text/plain");
  2626. });
  2627. auto port = svr.bind_to_any_port("127.0.0.1");
  2628. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2629. auto se = detail::scope_exit([&] {
  2630. svr.stop();
  2631. thread.join();
  2632. ASSERT_FALSE(svr.is_running());
  2633. });
  2634. svr.wait_until_ready();
  2635. Client cli(host, port);
  2636. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  2637. auto res = cli.Get("/hi");
  2638. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2639. EXPECT_EQ(StatusCode::OK_200, res->status);
  2640. }
  2641. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  2642. // An empty mapped value must leave host_ as the connection target. Without
  2643. // that guard the empty value would become the host argument, getaddrinfo
  2644. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  2645. // loopback - silently connecting somewhere the caller never asked for.
  2646. // The server listens on loopback, so such a fallback would succeed and is
  2647. // therefore observable as a failure of this test.
  2648. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  2649. Server svr;
  2650. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2651. res.set_content("Hello World!", "text/plain");
  2652. });
  2653. auto port = svr.bind_to_any_port(HOST);
  2654. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2655. auto se = detail::scope_exit([&] {
  2656. svr.stop();
  2657. thread.join();
  2658. ASSERT_FALSE(svr.is_running());
  2659. });
  2660. svr.wait_until_ready();
  2661. Client cli(blackhole, port);
  2662. cli.set_hostname_addr_map({{blackhole, ""}});
  2663. cli.set_connection_timeout(1);
  2664. auto res = cli.Get("/hi");
  2665. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  2666. }
  2667. TEST(AbsoluteRedirectTest, Redirect_Online) {
  2668. auto host = "httpbingo.org";
  2669. auto path = std::string{"/absolute-redirect/3"};
  2670. #ifdef CPPHTTPLIB_SSL_ENABLED
  2671. SSLClient cli(host);
  2672. #else
  2673. Client cli(host);
  2674. #endif
  2675. cli.set_follow_location(true);
  2676. auto res = cli.Get(path);
  2677. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2678. EXPECT_EQ(StatusCode::OK_200, res->status);
  2679. }
  2680. TEST(RedirectTest, Redirect_Online) {
  2681. auto host = "httpbingo.org";
  2682. auto path = std::string{"/redirect/3"};
  2683. #ifdef CPPHTTPLIB_SSL_ENABLED
  2684. SSLClient cli(host);
  2685. #else
  2686. Client cli(host);
  2687. #endif
  2688. cli.set_follow_location(true);
  2689. auto res = cli.Get(path);
  2690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2691. EXPECT_EQ(StatusCode::OK_200, res->status);
  2692. }
  2693. TEST(RelativeRedirectTest, Redirect_Online) {
  2694. auto host = "httpbingo.org";
  2695. auto path = std::string{"/relative-redirect/3"};
  2696. #ifdef CPPHTTPLIB_SSL_ENABLED
  2697. SSLClient cli(host);
  2698. #else
  2699. Client cli(host);
  2700. #endif
  2701. cli.set_follow_location(true);
  2702. auto res = cli.Get(path);
  2703. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2704. EXPECT_EQ(StatusCode::OK_200, res->status);
  2705. }
  2706. TEST(TooManyRedirectTest, Redirect_Online) {
  2707. auto host = "httpbingo.org";
  2708. auto path = std::string{"/redirect/21"};
  2709. #ifdef CPPHTTPLIB_SSL_ENABLED
  2710. SSLClient cli(host);
  2711. #else
  2712. Client cli(host);
  2713. #endif
  2714. cli.set_follow_location(true);
  2715. auto res = cli.Get(path);
  2716. ASSERT_TRUE(!res);
  2717. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  2718. }
  2719. #ifdef CPPHTTPLIB_SSL_ENABLED
  2720. TEST(YahooRedirectTest, Redirect_Online) {
  2721. Client cli("yahoo.com");
  2722. auto res = cli.Get("/");
  2723. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2724. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  2725. cli.set_follow_location(true);
  2726. res = cli.Get("/");
  2727. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2728. EXPECT_EQ(StatusCode::OK_200, res->status);
  2729. EXPECT_EQ("https://www.yahoo.com/", res->location);
  2730. }
  2731. // Previously "nghttp2.org" "/httpbin/redirect-to"
  2732. #define REDIR_HOST "httpbingo.org"
  2733. #define REDIR_PATH "/redirect-to"
  2734. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  2735. SSLClient cli(REDIR_HOST);
  2736. cli.set_follow_location(true);
  2737. auto res =
  2738. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  2739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2740. EXPECT_EQ(StatusCode::OK_200, res->status);
  2741. }
  2742. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  2743. SSLClient cli(REDIR_HOST);
  2744. cli.set_follow_location(true);
  2745. Params params;
  2746. params.emplace("url", "http://example.com");
  2747. params.emplace("status_code", "302");
  2748. auto res = cli.Get(REDIR_PATH, params, Headers{});
  2749. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2750. EXPECT_EQ(StatusCode::OK_200, res->status);
  2751. }
  2752. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  2753. SSLClient cli(REDIR_HOST);
  2754. cli.set_follow_location(true);
  2755. Params params;
  2756. params.emplace("url", "http://example.com");
  2757. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  2758. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2759. EXPECT_EQ(StatusCode::OK_200, res->status);
  2760. }
  2761. TEST(UrlWithSpace, Redirect_Online) {
  2762. SSLClient cli("edge.forgecdn.net");
  2763. cli.set_follow_location(true);
  2764. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  2765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2766. EXPECT_EQ(StatusCode::OK_200, res->status);
  2767. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  2768. }
  2769. #endif
  2770. #if !defined(_WIN32) && !defined(_WIN64)
  2771. TEST(ReceiveSignals, Signal) {
  2772. auto setupSignalHandlers = []() {
  2773. struct sigaction act;
  2774. sigemptyset(&act.sa_mask);
  2775. act.sa_flags = SA_SIGINFO;
  2776. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  2777. switch (sig) {
  2778. case SIGINT:
  2779. default: break;
  2780. }
  2781. };
  2782. ::sigaction(SIGINT, &act, nullptr);
  2783. };
  2784. Server svr;
  2785. int port = 0;
  2786. auto thread = std::thread([&]() {
  2787. setupSignalHandlers();
  2788. port = svr.bind_to_any_port(HOST);
  2789. svr.listen_after_bind();
  2790. });
  2791. auto se = detail::scope_exit([&] {
  2792. svr.stop();
  2793. thread.join();
  2794. ASSERT_FALSE(svr.is_running());
  2795. });
  2796. svr.wait_until_ready();
  2797. ASSERT_TRUE(svr.is_running());
  2798. pthread_kill(thread.native_handle(), SIGINT);
  2799. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  2800. ASSERT_TRUE(svr.is_running());
  2801. }
  2802. #endif
  2803. TEST(RedirectToDifferentPort, Redirect) {
  2804. Server svr1;
  2805. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  2806. res.set_content("Hello World!", "text/plain");
  2807. });
  2808. int svr1_port = 0;
  2809. auto thread1 = std::thread([&]() {
  2810. svr1_port = svr1.bind_to_any_port(HOST);
  2811. svr1.listen_after_bind();
  2812. });
  2813. Server svr2;
  2814. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  2815. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  2816. });
  2817. int svr2_port = 0;
  2818. auto thread2 = std::thread([&]() {
  2819. svr2_port = svr2.bind_to_any_port(HOST);
  2820. svr2.listen_after_bind();
  2821. });
  2822. auto se = detail::scope_exit([&] {
  2823. svr2.stop();
  2824. thread2.join();
  2825. svr1.stop();
  2826. thread1.join();
  2827. ASSERT_FALSE(svr2.is_running());
  2828. ASSERT_FALSE(svr1.is_running());
  2829. });
  2830. svr1.wait_until_ready();
  2831. svr2.wait_until_ready();
  2832. Client cli("localhost", svr2_port);
  2833. cli.set_follow_location(true);
  2834. auto res = cli.Get("/2");
  2835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2836. EXPECT_EQ(StatusCode::OK_200, res->status);
  2837. EXPECT_EQ("Hello World!", res->body);
  2838. }
  2839. static void
  2840. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  2841. Server svr1;
  2842. std::string captured_authorization;
  2843. svr1.Get("/target", [&](const Request &req, Response &res) {
  2844. captured_authorization = req.get_header_value("Authorization");
  2845. res.set_content("OK", "text/plain");
  2846. });
  2847. int svr1_port = 0;
  2848. auto thread1 = std::thread([&]() {
  2849. svr1_port = svr1.bind_to_any_port(HOST);
  2850. svr1.listen_after_bind();
  2851. });
  2852. Server svr2;
  2853. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2854. res.set_redirect(
  2855. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  2856. });
  2857. int svr2_port = 0;
  2858. auto thread2 = std::thread([&]() {
  2859. svr2_port = svr2.bind_to_any_port(HOST);
  2860. svr2.listen_after_bind();
  2861. });
  2862. auto se = detail::scope_exit([&] {
  2863. svr2.stop();
  2864. thread2.join();
  2865. svr1.stop();
  2866. thread1.join();
  2867. ASSERT_FALSE(svr2.is_running());
  2868. ASSERT_FALSE(svr1.is_running());
  2869. });
  2870. svr1.wait_until_ready();
  2871. svr2.wait_until_ready();
  2872. Client cli("localhost", svr2_port);
  2873. cli.set_follow_location(true);
  2874. set_auth(cli);
  2875. auto res = cli.Get("/redir");
  2876. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2877. EXPECT_EQ(StatusCode::OK_200, res->status);
  2878. // RFC 9110: credentials MUST NOT be forwarded to a different host
  2879. EXPECT_TRUE(captured_authorization.empty());
  2880. }
  2881. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  2882. TestDoNotForwardCredentialsOnRedirect(
  2883. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  2884. }
  2885. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  2886. TestDoNotForwardCredentialsOnRedirect(
  2887. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  2888. }
  2889. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  2890. Server svr1;
  2891. std::string captured_cookie;
  2892. bool target_hit = false;
  2893. svr1.Get("/target", [&](const Request &req, Response &res) {
  2894. captured_cookie = req.get_header_value("Cookie");
  2895. target_hit = true;
  2896. res.set_content("OK", "text/plain");
  2897. });
  2898. int svr1_port = 0;
  2899. auto thread1 = std::thread([&]() {
  2900. svr1_port = svr1.bind_to_any_port(HOST);
  2901. svr1.listen_after_bind();
  2902. });
  2903. Server svr2;
  2904. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2905. res.set_redirect(
  2906. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  2907. });
  2908. int svr2_port = 0;
  2909. auto thread2 = std::thread([&]() {
  2910. svr2_port = svr2.bind_to_any_port(HOST);
  2911. svr2.listen_after_bind();
  2912. });
  2913. auto se = detail::scope_exit([&] {
  2914. svr2.stop();
  2915. thread2.join();
  2916. svr1.stop();
  2917. thread1.join();
  2918. ASSERT_FALSE(svr2.is_running());
  2919. ASSERT_FALSE(svr1.is_running());
  2920. });
  2921. svr1.wait_until_ready();
  2922. svr2.wait_until_ready();
  2923. Client cli("localhost", svr2_port);
  2924. cli.set_follow_location(true);
  2925. Headers headers = {{"Cookie", "session_id=SECRET; auth=PRIVATE"}};
  2926. auto res = cli.Get("/redir", headers);
  2927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2928. EXPECT_EQ(StatusCode::OK_200, res->status);
  2929. EXPECT_TRUE(target_hit);
  2930. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  2931. EXPECT_TRUE(captured_cookie.empty());
  2932. }
  2933. TEST(RedirectToSamePort, ForwardCookie) {
  2934. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  2935. // header so that ordinary session flows keep working.
  2936. Server svr;
  2937. std::string captured_cookie;
  2938. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2939. res.set_redirect("/target", 302);
  2940. });
  2941. svr.Get("/target", [&](const Request &req, Response &res) {
  2942. captured_cookie = req.get_header_value("Cookie");
  2943. res.set_content("OK", "text/plain");
  2944. });
  2945. auto port = svr.bind_to_any_port(HOST);
  2946. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2947. auto se = detail::scope_exit([&] {
  2948. svr.stop();
  2949. thread.join();
  2950. ASSERT_FALSE(svr.is_running());
  2951. });
  2952. svr.wait_until_ready();
  2953. Client cli(HOST, port);
  2954. cli.set_follow_location(true);
  2955. Headers headers = {{"Cookie", "session_id=SECRET"}};
  2956. auto res = cli.Get("/redir", headers);
  2957. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2958. EXPECT_EQ(StatusCode::OK_200, res->status);
  2959. EXPECT_EQ("session_id=SECRET", captured_cookie);
  2960. }
  2961. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  2962. Server svr;
  2963. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2964. // Port number that overflows int — should not crash
  2965. res.set_redirect("http://localhost:99999999999999999999/target");
  2966. });
  2967. auto port = svr.bind_to_any_port(HOST);
  2968. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2969. auto se = detail::scope_exit([&] {
  2970. svr.stop();
  2971. thread.join();
  2972. ASSERT_FALSE(svr.is_running());
  2973. });
  2974. svr.wait_until_ready();
  2975. Client cli(HOST, port);
  2976. cli.set_follow_location(true);
  2977. auto res = cli.Get("/redir");
  2978. // Should fail gracefully, not crash (no valid response due to bad port)
  2979. EXPECT_FALSE(res);
  2980. }
  2981. TEST(RedirectFromPageWithContent, Redirect) {
  2982. Server svr;
  2983. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2984. res.set_content("___", "text/plain");
  2985. res.set_redirect("/2");
  2986. });
  2987. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  2988. res.set_content("Hello World!", "text/plain");
  2989. });
  2990. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  2991. auto se = detail::scope_exit([&] {
  2992. svr.stop();
  2993. th.join();
  2994. ASSERT_FALSE(svr.is_running());
  2995. });
  2996. svr.wait_until_ready();
  2997. {
  2998. Client cli("localhost", PORT);
  2999. cli.set_follow_location(true);
  3000. std::string body;
  3001. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3002. body.append(data, data_length);
  3003. return true;
  3004. });
  3005. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3006. EXPECT_EQ(StatusCode::OK_200, res->status);
  3007. EXPECT_EQ("Hello World!", body);
  3008. }
  3009. {
  3010. Client cli("localhost", PORT);
  3011. std::string body;
  3012. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3013. body.append(data, data_length);
  3014. return true;
  3015. });
  3016. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3017. EXPECT_EQ(StatusCode::Found_302, res->status);
  3018. EXPECT_EQ("___", body);
  3019. }
  3020. }
  3021. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3022. Server svr;
  3023. auto port_str = std::to_string(PORT);
  3024. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3025. auto expected_host = "[::1]:" + port_str;
  3026. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3027. res.set_content("___", "text/plain");
  3028. // res.set_redirect("/2");
  3029. res.set_redirect(redirect_url);
  3030. });
  3031. svr.Get("/2", [&](const Request &req, Response &res) {
  3032. auto host_header = req.headers.find("Host");
  3033. ASSERT_TRUE(host_header != req.headers.end());
  3034. EXPECT_EQ(expected_host, host_header->second);
  3035. res.set_content("Hello World!", "text/plain");
  3036. });
  3037. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3038. auto se = detail::scope_exit([&] {
  3039. svr.stop();
  3040. th.join();
  3041. ASSERT_FALSE(svr.is_running());
  3042. });
  3043. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3044. // actually starts anything, so the condition !svr.is_running() will
  3045. // always remain true, and the loop never stops.
  3046. // This basically counts how many milliseconds have passed since the
  3047. // call to svr.listen(), and if after 5 seconds nothing started yet
  3048. // aborts the test.
  3049. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3050. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3051. ASSERT_LT(milliseconds, 5000U);
  3052. }
  3053. {
  3054. Client cli("::1", PORT);
  3055. cli.set_follow_location(true);
  3056. std::string body;
  3057. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3058. body.append(data, data_length);
  3059. return true;
  3060. });
  3061. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3062. EXPECT_EQ(StatusCode::OK_200, res->status);
  3063. EXPECT_EQ("Hello World!", body);
  3064. }
  3065. {
  3066. Client cli("::1", PORT);
  3067. std::string body;
  3068. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3069. body.append(data, data_length);
  3070. return true;
  3071. });
  3072. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3073. EXPECT_EQ(StatusCode::Found_302, res->status);
  3074. EXPECT_EQ("___", body);
  3075. }
  3076. }
  3077. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3078. Server svr;
  3079. svr.Get("/foo", [](const Request &req, Response &res) {
  3080. auto a = req.params.find("a");
  3081. if (a != req.params.end()) {
  3082. res.set_content((*a).second, "text/plain");
  3083. res.status = StatusCode::OK_200;
  3084. } else {
  3085. res.status = StatusCode::BadRequest_400;
  3086. }
  3087. });
  3088. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3089. auto se = detail::scope_exit([&] {
  3090. svr.stop();
  3091. thread.join();
  3092. ASSERT_FALSE(svr.is_running());
  3093. });
  3094. svr.wait_until_ready();
  3095. {
  3096. Client cli(HOST, PORT);
  3097. cli.set_path_encode(false);
  3098. auto res = cli.Get("/foo?a=explicitly+encoded");
  3099. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3100. EXPECT_EQ(StatusCode::OK_200, res->status);
  3101. // This expects it back with a space, as the `+` won't have been
  3102. // url-encoded, and server-side the params get decoded turning `+`
  3103. // into spaces.
  3104. EXPECT_EQ("explicitly encoded", res->body);
  3105. }
  3106. }
  3107. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3108. // When path encoding is disabled the client must transmit the supplied
  3109. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3110. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3111. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3112. // than a space (0x20). Assert on the raw wire target to catch this.
  3113. Server svr;
  3114. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3115. svr.Get("/foo", [&](const Request &req, Response &res) {
  3116. EXPECT_EQ(expected_target, req.target);
  3117. res.status = StatusCode::OK_200;
  3118. });
  3119. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3120. auto se = detail::scope_exit([&] {
  3121. svr.stop();
  3122. thread.join();
  3123. ASSERT_FALSE(svr.is_running());
  3124. });
  3125. svr.wait_until_ready();
  3126. {
  3127. Client cli(HOST, PORT);
  3128. cli.set_path_encode(false);
  3129. auto res = cli.Get(expected_target.c_str());
  3130. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3131. EXPECT_EQ(StatusCode::OK_200, res->status);
  3132. }
  3133. }
  3134. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3135. // `open_stream()` used to skip the path encoding that the buffered send
  3136. // path applies, so the same `path` produced different bytes in the request
  3137. // line depending on which API was used. Assert the two agree.
  3138. Server svr;
  3139. std::string target;
  3140. svr.Get(".*", [&](const Request &req, Response &res) {
  3141. target = req.target;
  3142. res.status = StatusCode::OK_200;
  3143. });
  3144. auto port = svr.bind_to_any_port(HOST);
  3145. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3146. auto se = detail::scope_exit([&] {
  3147. svr.stop();
  3148. thread.join();
  3149. ASSERT_FALSE(svr.is_running());
  3150. });
  3151. svr.wait_until_ready();
  3152. struct {
  3153. const char *path;
  3154. const char *expected;
  3155. } cases[] = {
  3156. {"/a b?x=1", "/a%20b?x=1"},
  3157. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3158. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3159. };
  3160. for (const auto &c : cases) {
  3161. Client cli(HOST, port);
  3162. target.clear();
  3163. auto res = cli.Get(c.path);
  3164. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3165. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3166. auto buffered_target = target;
  3167. target.clear();
  3168. auto handle = cli.open_stream("GET", c.path);
  3169. EXPECT_TRUE(handle.is_valid())
  3170. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3171. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3172. }
  3173. }
  3174. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3175. // The `set_path_encode(false)` contract — transmit the supplied target
  3176. // verbatim — must hold for the streaming API too.
  3177. Server svr;
  3178. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3179. std::string target;
  3180. svr.Get("/foo", [&](const Request &req, Response &res) {
  3181. target = req.target;
  3182. res.status = StatusCode::OK_200;
  3183. });
  3184. auto port = svr.bind_to_any_port(HOST);
  3185. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3186. auto se = detail::scope_exit([&] {
  3187. svr.stop();
  3188. thread.join();
  3189. ASSERT_FALSE(svr.is_running());
  3190. });
  3191. svr.wait_until_ready();
  3192. {
  3193. Client cli(HOST, port);
  3194. cli.set_path_encode(false);
  3195. auto handle = cli.open_stream("GET", expected_target);
  3196. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3197. EXPECT_EQ(expected_target, target);
  3198. }
  3199. }
  3200. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3201. // With path encoding enabled a CR/LF in the target is percent-encoded
  3202. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3203. // write_request_line still backstops `set_path_encode(false)`, which is
  3204. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3205. Server svr;
  3206. // Captured before routing: the decoded path contains a newline, which a
  3207. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3208. std::string target;
  3209. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3210. target = req.target;
  3211. res.status = StatusCode::OK_200;
  3212. return Server::HandlerResponse::Handled;
  3213. });
  3214. auto port = svr.bind_to_any_port(HOST);
  3215. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3216. auto se = detail::scope_exit([&] {
  3217. svr.stop();
  3218. thread.join();
  3219. ASSERT_FALSE(svr.is_running());
  3220. });
  3221. svr.wait_until_ready();
  3222. {
  3223. Client cli(HOST, port);
  3224. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3225. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3226. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3227. }
  3228. }
  3229. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3230. // Nothing may reach the wire: a raw CR/LF target would split the request
  3231. // line and inject headers.
  3232. Server svr;
  3233. // Pre-routing so that "not called" means nothing reached the server at all,
  3234. // rather than merely failing to match a handler pattern.
  3235. auto handler_called = false;
  3236. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3237. handler_called = true;
  3238. res.status = StatusCode::OK_200;
  3239. return Server::HandlerResponse::Handled;
  3240. });
  3241. auto port = svr.bind_to_any_port(HOST);
  3242. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3243. auto se = detail::scope_exit([&] {
  3244. svr.stop();
  3245. thread.join();
  3246. ASSERT_FALSE(svr.is_running());
  3247. });
  3248. svr.wait_until_ready();
  3249. {
  3250. Client cli(HOST, port);
  3251. cli.set_path_encode(false);
  3252. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3253. EXPECT_FALSE(handle.is_valid());
  3254. EXPECT_EQ(Error::Write, handle.error);
  3255. EXPECT_FALSE(handler_called);
  3256. }
  3257. }
  3258. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3259. // Which of the two branches runs is decided by whether the query component
  3260. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3261. // an empty query and must still fall back to building one from
  3262. // `req.params`, while a non-empty query must win over `req.params`.
  3263. Server svr;
  3264. std::string target;
  3265. svr.Get("/foo", [&](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. {
  3278. // Trailing `?` -> empty query component -> `req.params` is used.
  3279. Client cli(HOST, port);
  3280. Request req;
  3281. req.method = "GET";
  3282. req.path = "/foo?";
  3283. req.params.emplace("a", "1");
  3284. target.clear();
  3285. auto res = cli.send(req);
  3286. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3287. EXPECT_EQ("/foo?a=1", target);
  3288. }
  3289. {
  3290. // Non-empty query in `req.path` -> `req.params` is not appended.
  3291. Client cli(HOST, port);
  3292. Request req;
  3293. req.method = "GET";
  3294. req.path = "/foo?b=2";
  3295. req.params.emplace("a", "1");
  3296. target.clear();
  3297. auto res = cli.send(req);
  3298. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3299. EXPECT_EQ("/foo?b=2", target);
  3300. }
  3301. }
  3302. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3303. Server svr;
  3304. svr.Get("/", [](const Request &req, Response &) {
  3305. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3306. });
  3307. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3308. auto se = detail::scope_exit([&] {
  3309. svr.stop();
  3310. thread.join();
  3311. ASSERT_FALSE(svr.is_running());
  3312. });
  3313. svr.wait_until_ready();
  3314. {
  3315. Client cli(HOST, PORT);
  3316. cli.set_path_encode(false);
  3317. auto res = cli.Get("/?something=%0A");
  3318. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3319. EXPECT_EQ(StatusCode::OK_200, res->status);
  3320. }
  3321. }
  3322. TEST(BindServerTest, BindDualStack) {
  3323. Server svr;
  3324. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3325. res.set_content("Hello World!", "text/plain");
  3326. });
  3327. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3328. auto se = detail::scope_exit([&] {
  3329. svr.stop();
  3330. thread.join();
  3331. ASSERT_FALSE(svr.is_running());
  3332. });
  3333. svr.wait_until_ready();
  3334. {
  3335. Client cli("127.0.0.1", PORT);
  3336. auto res = cli.Get("/1");
  3337. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3338. EXPECT_EQ(StatusCode::OK_200, res->status);
  3339. EXPECT_EQ("Hello World!", res->body);
  3340. }
  3341. {
  3342. Client cli("::1", PORT);
  3343. auto res = cli.Get("/1");
  3344. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3345. EXPECT_EQ(StatusCode::OK_200, res->status);
  3346. EXPECT_EQ("Hello World!", res->body);
  3347. }
  3348. }
  3349. TEST(BindServerTest, BindAndListenSeparately) {
  3350. Server svr;
  3351. int port = svr.bind_to_any_port("0.0.0.0");
  3352. ASSERT_TRUE(svr.is_valid());
  3353. ASSERT_TRUE(port > 0);
  3354. svr.stop();
  3355. }
  3356. // Reports whether anything is still listening on a loopback port. A plain
  3357. // connect() is used instead of a Client request because a socket left bound by
  3358. // mistake accepts the connection into its backlog and never answers, which
  3359. // would hang the test instead of failing it.
  3360. static bool is_loopback_port_accepting(int port) {
  3361. sockaddr_in addr{};
  3362. addr.sin_family = AF_INET;
  3363. addr.sin_port = htons(static_cast<uint16_t>(port));
  3364. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3365. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3366. EXPECT_NE(sock, INVALID_SOCKET);
  3367. if (sock == INVALID_SOCKET) { return false; }
  3368. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3369. static_cast<socklen_t>(sizeof(addr)));
  3370. detail::close_socket(sock);
  3371. return ret == 0;
  3372. }
  3373. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3374. Server svr;
  3375. auto port = svr.bind_to_any_port("127.0.0.1");
  3376. ASSERT_TRUE(port > 0);
  3377. svr.stop();
  3378. // bind_to_any_port() already called listen(2), so until stop() closed the
  3379. // descriptor the port kept accepting connections into the backlog. ASSERT
  3380. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3381. // below blocks forever in the accept loop.
  3382. ASSERT_FALSE(is_loopback_port_accepting(port));
  3383. // Nothing is left to accept on, so listen_after_bind() must report failure
  3384. // instead of returning success without ever serving.
  3385. EXPECT_FALSE(svr.listen_after_bind());
  3386. // The failed listen marks the server decommissioned, so a waiter returns
  3387. // instead of spinning forever.
  3388. svr.wait_until_ready();
  3389. }
  3390. #ifdef CPPHTTPLIB_SSL_ENABLED
  3391. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3392. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3393. CLIENT_CA_CERT_DIR);
  3394. int port = svr.bind_to_any_port("0.0.0.0");
  3395. ASSERT_TRUE(svr.is_valid());
  3396. ASSERT_TRUE(port > 0);
  3397. svr.stop();
  3398. }
  3399. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  3400. // or a rejected CustomRoute() registration would not stop the server binding.
  3401. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  3402. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3403. CLIENT_CA_CERT_DIR);
  3404. ASSERT_TRUE(svr.is_valid());
  3405. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  3406. EXPECT_FALSE(svr.is_valid());
  3407. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  3408. }
  3409. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  3410. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  3411. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  3412. int port = svr.bind_to_any_port("0.0.0.0");
  3413. ASSERT_TRUE(svr.is_valid());
  3414. ASSERT_TRUE(port > 0);
  3415. svr.stop();
  3416. }
  3417. TEST(BindServerTest, UpdateCertsPem) {
  3418. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3419. int port = svr.bind_to_any_port("0.0.0.0");
  3420. ASSERT_TRUE(svr.is_valid());
  3421. ASSERT_TRUE(port > 0);
  3422. // Read PEM files
  3423. std::string cert_pem, key_pem, ca_pem;
  3424. read_file(SERVER_CERT_FILE, cert_pem);
  3425. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3426. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3427. // Update server certificates using PEM API
  3428. ASSERT_TRUE(
  3429. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3430. ASSERT_TRUE(svr.is_valid());
  3431. svr.stop();
  3432. }
  3433. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  3434. // Start server with client CA (enables client auth)
  3435. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3436. ASSERT_TRUE(svr.is_valid());
  3437. bool handler_called = false;
  3438. svr.Get("/test", [&](const Request &req, Response &res) {
  3439. handler_called = true;
  3440. // Verify client certificate is present
  3441. auto cert = req.peer_cert();
  3442. EXPECT_TRUE(static_cast<bool>(cert));
  3443. res.set_content("ok", "text/plain");
  3444. });
  3445. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3446. auto se = detail::scope_exit([&] {
  3447. svr.stop();
  3448. t.join();
  3449. ASSERT_FALSE(svr.is_running());
  3450. });
  3451. svr.wait_until_ready();
  3452. // Read PEM files
  3453. std::string cert_pem, key_pem, ca_pem;
  3454. read_file(SERVER_CERT_FILE, cert_pem);
  3455. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3456. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3457. // Update server certificates and client CA using PEM API while server running
  3458. ASSERT_TRUE(
  3459. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3460. // Connect with client certificate
  3461. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3462. cli.enable_server_certificate_verification(false);
  3463. cli.set_connection_timeout(30);
  3464. auto res = cli.Get("/test");
  3465. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3466. ASSERT_EQ(StatusCode::OK_200, res->status);
  3467. ASSERT_TRUE(handler_called);
  3468. EXPECT_EQ("ok", res->body);
  3469. }
  3470. #endif
  3471. TEST(ErrorHandlerTest, ContentLength) {
  3472. Server svr;
  3473. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3474. res.status = StatusCode::OK_200;
  3475. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3476. "text/html"); // <= Content-Length still 13
  3477. });
  3478. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3479. res.set_content("Hello World!\n", "text/plain");
  3480. res.status = 524;
  3481. });
  3482. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3483. auto se = detail::scope_exit([&] {
  3484. svr.stop();
  3485. thread.join();
  3486. ASSERT_FALSE(svr.is_running());
  3487. });
  3488. svr.wait_until_ready();
  3489. {
  3490. Client cli(HOST, PORT);
  3491. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3492. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3493. EXPECT_EQ(StatusCode::OK_200, res->status);
  3494. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3495. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3496. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3497. }
  3498. }
  3499. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3500. TEST(ExceptionTest, WithoutExceptionHandler) {
  3501. Server svr;
  3502. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  3503. throw std::runtime_error("exception...");
  3504. });
  3505. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  3506. throw std::runtime_error("exception\r\n...");
  3507. });
  3508. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3509. auto se = detail::scope_exit([&] {
  3510. svr.stop();
  3511. listen_thread.join();
  3512. ASSERT_FALSE(svr.is_running());
  3513. });
  3514. svr.wait_until_ready();
  3515. Client cli("localhost", PORT);
  3516. {
  3517. auto res = cli.Get("/exception");
  3518. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3519. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3520. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3521. }
  3522. {
  3523. auto res = cli.Get("/unknown");
  3524. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3525. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3526. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3527. }
  3528. }
  3529. TEST(ExceptionTest, WithExceptionHandler) {
  3530. Server svr;
  3531. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  3532. std::exception_ptr ep) {
  3533. EXPECT_FALSE(ep == nullptr);
  3534. try {
  3535. std::rethrow_exception(ep);
  3536. } catch (std::exception &e) {
  3537. EXPECT_EQ("abc", std::string(e.what()));
  3538. } catch (...) {}
  3539. res.status = StatusCode::InternalServerError_500;
  3540. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3541. "text/html"); // <= Content-Length still 13 at this point
  3542. });
  3543. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3544. res.set_content("Hello World!\n", "text/plain");
  3545. throw std::runtime_error("abc");
  3546. });
  3547. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3548. auto se = detail::scope_exit([&] {
  3549. svr.stop();
  3550. thread.join();
  3551. ASSERT_FALSE(svr.is_running());
  3552. });
  3553. svr.wait_until_ready();
  3554. for (size_t i = 0; i < 10; i++) {
  3555. Client cli(HOST, PORT);
  3556. for (size_t j = 0; j < 100; j++) {
  3557. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3558. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3559. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3560. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3561. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3562. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3563. }
  3564. cli.set_keep_alive(true);
  3565. for (size_t j = 0; j < 100; j++) {
  3566. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3567. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3568. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3569. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3570. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3571. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3572. }
  3573. }
  3574. }
  3575. TEST(ExceptionTest, AndErrorHandler) {
  3576. Server svr;
  3577. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3578. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  3579. });
  3580. svr.set_exception_handler(
  3581. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  3582. EXPECT_FALSE(ep == nullptr);
  3583. try {
  3584. std::rethrow_exception(ep);
  3585. } catch (std::exception &e) {
  3586. res.set_content(e.what(), "text/html");
  3587. } catch (...) {}
  3588. res.status = StatusCode::InternalServerError_500;
  3589. });
  3590. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  3591. throw std::runtime_error("EXCEPTION");
  3592. });
  3593. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  3594. res.set_content("ERROR", "text/html");
  3595. res.status = StatusCode::InternalServerError_500;
  3596. });
  3597. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3598. auto se = detail::scope_exit([&] {
  3599. svr.stop();
  3600. thread.join();
  3601. ASSERT_FALSE(svr.is_running());
  3602. });
  3603. svr.wait_until_ready();
  3604. Client cli(HOST, PORT);
  3605. {
  3606. auto res = cli.Get("/exception");
  3607. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3608. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3609. EXPECT_EQ("EXCEPTION", res->body);
  3610. }
  3611. {
  3612. auto res = cli.Get("/error");
  3613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3614. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3615. EXPECT_EQ("ERROR", res->body);
  3616. }
  3617. {
  3618. auto res = cli.Get("/invalid");
  3619. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3620. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3621. EXPECT_EQ("NOT_FOUND", res->body);
  3622. }
  3623. }
  3624. #endif
  3625. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3626. // process_request() wraps only routing() in a try/catch, so an exception from
  3627. // any other user callback used to unwind into the task queue - which does not
  3628. // catch - and terminate the process. Each test below runs the server on a
  3629. // single worker thread: a guard that catches the exception but still loses the
  3630. // thread would otherwise be hidden by a spare worker serving the follow-up
  3631. // request. Note that a regression here aborts the whole test binary rather
  3632. // than failing one test.
  3633. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  3634. Server svr;
  3635. svr.new_task_queue = [] { return new ThreadPool(1); };
  3636. std::atomic<int> reported{0};
  3637. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  3638. if (err == Error::UserCallbackException) { reported++; }
  3639. });
  3640. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  3641. res.set_content_provider(
  3642. 1024, "text/plain",
  3643. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  3644. sink.write("hello", 5);
  3645. throw std::runtime_error("from the content provider");
  3646. });
  3647. });
  3648. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  3649. res.set_content("ok", "text/plain");
  3650. });
  3651. auto port = svr.bind_to_any_port(HOST);
  3652. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3653. auto se = detail::scope_exit([&] {
  3654. svr.stop();
  3655. listen_thread.join();
  3656. ASSERT_FALSE(svr.is_running());
  3657. });
  3658. svr.wait_until_ready();
  3659. {
  3660. Client cli(HOST, port);
  3661. cli.set_read_timeout(5, 0);
  3662. EXPECT_FALSE(cli.Get("/throw"));
  3663. }
  3664. EXPECT_TRUE(svr.is_running());
  3665. EXPECT_EQ(1, reported.load());
  3666. // A request on a fresh connection is still served.
  3667. {
  3668. Client cli(HOST, port);
  3669. auto res = cli.Get("/ok");
  3670. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3671. EXPECT_EQ(StatusCode::OK_200, res->status);
  3672. EXPECT_EQ("ok", res->body);
  3673. }
  3674. }
  3675. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  3676. Server svr;
  3677. svr.new_task_queue = [] { return new ThreadPool(1); };
  3678. std::atomic<bool> should_throw{true};
  3679. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3680. res.set_content("hi", "text/plain");
  3681. });
  3682. svr.set_post_routing_handler(
  3683. [&](const Request & /*req*/, Response & /*res*/) {
  3684. if (should_throw) {
  3685. throw std::runtime_error("from the post-routing handler");
  3686. }
  3687. });
  3688. auto port = svr.bind_to_any_port(HOST);
  3689. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3690. auto se = detail::scope_exit([&] {
  3691. svr.stop();
  3692. listen_thread.join();
  3693. ASSERT_FALSE(svr.is_running());
  3694. });
  3695. svr.wait_until_ready();
  3696. {
  3697. Client cli(HOST, port);
  3698. cli.set_read_timeout(5, 0);
  3699. EXPECT_FALSE(cli.Get("/hi"));
  3700. }
  3701. EXPECT_TRUE(svr.is_running());
  3702. should_throw = false;
  3703. {
  3704. Client cli(HOST, port);
  3705. auto res = cli.Get("/hi");
  3706. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3707. EXPECT_EQ(StatusCode::OK_200, res->status);
  3708. EXPECT_EQ("hi", res->body);
  3709. }
  3710. }
  3711. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  3712. // The guard reports the caught exception through the error logger, which is
  3713. // a user callback too. A logger that throws has to be contained as well, or
  3714. // the process would terminate from inside the catch.
  3715. Server svr;
  3716. svr.new_task_queue = [] { return new ThreadPool(1); };
  3717. std::atomic<int> reported{0};
  3718. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  3719. if (err == Error::UserCallbackException) {
  3720. reported++;
  3721. throw std::runtime_error("from the error logger");
  3722. }
  3723. });
  3724. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  3725. res.set_content_provider(
  3726. 1024, "text/plain",
  3727. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  3728. sink.write("hello", 5);
  3729. throw std::runtime_error("from the content provider");
  3730. });
  3731. });
  3732. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  3733. res.set_content("ok", "text/plain");
  3734. });
  3735. auto port = svr.bind_to_any_port(HOST);
  3736. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3737. auto se = detail::scope_exit([&] {
  3738. svr.stop();
  3739. listen_thread.join();
  3740. ASSERT_FALSE(svr.is_running());
  3741. });
  3742. svr.wait_until_ready();
  3743. {
  3744. Client cli(HOST, port);
  3745. cli.set_read_timeout(5, 0);
  3746. EXPECT_FALSE(cli.Get("/throw"));
  3747. }
  3748. EXPECT_TRUE(svr.is_running());
  3749. EXPECT_EQ(1, reported.load());
  3750. {
  3751. Client cli(HOST, port);
  3752. auto res = cli.Get("/ok");
  3753. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3754. EXPECT_EQ(StatusCode::OK_200, res->status);
  3755. EXPECT_EQ("ok", res->body);
  3756. }
  3757. }
  3758. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  3759. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  3760. // so the exception unwinds through the ws::WebSocket object on its way to
  3761. // the guard. None of the HTTP cases above cross that.
  3762. Server svr;
  3763. svr.new_task_queue = [] { return new ThreadPool(1); };
  3764. std::atomic<int> reported{0};
  3765. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  3766. if (err == Error::UserCallbackException) { reported++; }
  3767. });
  3768. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  3769. throw std::runtime_error("from the WebSocket handler");
  3770. });
  3771. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  3772. res.set_content("ok", "text/plain");
  3773. });
  3774. auto port = svr.bind_to_any_port(HOST);
  3775. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3776. auto se = detail::scope_exit([&] {
  3777. svr.stop();
  3778. listen_thread.join();
  3779. ASSERT_FALSE(svr.is_running());
  3780. });
  3781. svr.wait_until_ready();
  3782. {
  3783. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  3784. "/ws");
  3785. auto res = client.connect();
  3786. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3787. // The server dropped the connection instead of dying.
  3788. std::string msg;
  3789. EXPECT_FALSE(client.read(msg));
  3790. client.close();
  3791. }
  3792. EXPECT_TRUE(svr.is_running());
  3793. EXPECT_EQ(1, reported.load());
  3794. {
  3795. Client cli(HOST, port);
  3796. auto res = cli.Get("/ok");
  3797. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3798. EXPECT_EQ(StatusCode::OK_200, res->status);
  3799. EXPECT_EQ("ok", res->body);
  3800. }
  3801. }
  3802. #ifdef CPPHTTPLIB_SSL_ENABLED
  3803. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  3804. // SSLServer::process_and_close_socket() is a separate overload with its own
  3805. // guard, so it is exercised on its own.
  3806. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  3807. ASSERT_TRUE(svr.is_valid());
  3808. svr.new_task_queue = [] { return new ThreadPool(1); };
  3809. std::atomic<int> reported{0};
  3810. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  3811. if (err == Error::UserCallbackException) { reported++; }
  3812. });
  3813. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  3814. res.set_content_provider(
  3815. 1024, "text/plain",
  3816. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  3817. sink.write("hello", 5);
  3818. throw std::runtime_error("from the content provider");
  3819. });
  3820. });
  3821. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  3822. res.set_content("ok", "text/plain");
  3823. });
  3824. auto port = svr.bind_to_any_port(HOST);
  3825. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3826. auto se = detail::scope_exit([&] {
  3827. svr.stop();
  3828. listen_thread.join();
  3829. ASSERT_FALSE(svr.is_running());
  3830. });
  3831. svr.wait_until_ready();
  3832. {
  3833. SSLClient cli(HOST, port);
  3834. cli.enable_server_certificate_verification(false);
  3835. cli.set_read_timeout(5, 0);
  3836. EXPECT_FALSE(cli.Get("/throw"));
  3837. }
  3838. EXPECT_TRUE(svr.is_running());
  3839. EXPECT_EQ(1, reported.load());
  3840. {
  3841. SSLClient cli(HOST, port);
  3842. cli.enable_server_certificate_verification(false);
  3843. auto res = cli.Get("/ok");
  3844. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3845. EXPECT_EQ(StatusCode::OK_200, res->status);
  3846. EXPECT_EQ("ok", res->body);
  3847. }
  3848. }
  3849. #endif
  3850. #endif
  3851. TEST(NoContentTest, ContentLength) {
  3852. Server svr;
  3853. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3854. res.status = StatusCode::NoContent_204;
  3855. });
  3856. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3857. auto se = detail::scope_exit([&] {
  3858. svr.stop();
  3859. thread.join();
  3860. ASSERT_FALSE(svr.is_running());
  3861. });
  3862. svr.wait_until_ready();
  3863. {
  3864. Client cli(HOST, PORT);
  3865. auto res = cli.Get("/hi");
  3866. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3867. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  3868. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3869. }
  3870. }
  3871. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  3872. #ifdef CPPHTTPLIB_SSL_ENABLED
  3873. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  3874. ASSERT_TRUE(svr.is_valid());
  3875. #else
  3876. Server svr;
  3877. #endif
  3878. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  3879. if (req.path == "/routing_handler") {
  3880. res.set_header("PRE_ROUTING", "on");
  3881. res.set_content("Routing Handler", "text/plain");
  3882. return httplib::Server::HandlerResponse::Handled;
  3883. }
  3884. return httplib::Server::HandlerResponse::Unhandled;
  3885. });
  3886. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3887. res.set_content("Error", "text/html");
  3888. });
  3889. svr.set_post_routing_handler([](const Request &req, Response &res) {
  3890. if (req.path == "/routing_handler") {
  3891. res.set_header("POST_ROUTING", "on");
  3892. }
  3893. });
  3894. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3895. res.set_content("Hello World!\n", "text/plain");
  3896. });
  3897. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3898. auto se = detail::scope_exit([&] {
  3899. svr.stop();
  3900. thread.join();
  3901. ASSERT_FALSE(svr.is_running());
  3902. });
  3903. svr.wait_until_ready();
  3904. {
  3905. #ifdef CPPHTTPLIB_SSL_ENABLED
  3906. SSLClient cli(HOST, PORT);
  3907. cli.enable_server_certificate_verification(false);
  3908. #else
  3909. Client cli(HOST, PORT);
  3910. #endif
  3911. auto res = cli.Get("/routing_handler");
  3912. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3913. EXPECT_EQ(StatusCode::OK_200, res->status);
  3914. EXPECT_EQ("Routing Handler", res->body);
  3915. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  3916. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  3917. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  3918. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  3919. }
  3920. {
  3921. #ifdef CPPHTTPLIB_SSL_ENABLED
  3922. SSLClient cli(HOST, PORT);
  3923. cli.enable_server_certificate_verification(false);
  3924. #else
  3925. Client cli(HOST, PORT);
  3926. #endif
  3927. auto res = cli.Get("/hi");
  3928. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3929. EXPECT_EQ(StatusCode::OK_200, res->status);
  3930. EXPECT_EQ("Hello World!\n", res->body);
  3931. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  3932. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  3933. }
  3934. {
  3935. #ifdef CPPHTTPLIB_SSL_ENABLED
  3936. SSLClient cli(HOST, PORT);
  3937. cli.enable_server_certificate_verification(false);
  3938. #else
  3939. Client cli(HOST, PORT);
  3940. #endif
  3941. auto res = cli.Get("/aaa");
  3942. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3943. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3944. EXPECT_EQ("Error", res->body);
  3945. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  3946. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  3947. }
  3948. }
  3949. TEST(RequestHandlerTest, PreRequestHandler) {
  3950. auto route_path = "/user/:user";
  3951. Server svr;
  3952. svr.Get("/hi", [](const Request &, Response &res) {
  3953. res.set_content("hi", "text/plain");
  3954. });
  3955. svr.Get(route_path, [](const Request &req, Response &res) {
  3956. res.set_content(req.path_params.at("user"), "text/plain");
  3957. });
  3958. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  3959. if (req.matched_route == route_path) {
  3960. auto user = req.path_params.at("user");
  3961. if (user != "john") {
  3962. res.status = StatusCode::Forbidden_403;
  3963. res.set_content("error", "text/html");
  3964. return Server::HandlerResponse::Handled;
  3965. }
  3966. }
  3967. return Server::HandlerResponse::Unhandled;
  3968. });
  3969. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3970. auto se = detail::scope_exit([&] {
  3971. svr.stop();
  3972. thread.join();
  3973. ASSERT_FALSE(svr.is_running());
  3974. });
  3975. svr.wait_until_ready();
  3976. Client cli(HOST, PORT);
  3977. {
  3978. auto res = cli.Get("/hi");
  3979. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3980. EXPECT_EQ(StatusCode::OK_200, res->status);
  3981. EXPECT_EQ("hi", res->body);
  3982. }
  3983. {
  3984. auto res = cli.Get("/user/john");
  3985. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3986. EXPECT_EQ(StatusCode::OK_200, res->status);
  3987. EXPECT_EQ("john", res->body);
  3988. }
  3989. {
  3990. auto res = cli.Get("/user/invalid-user");
  3991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3992. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  3993. EXPECT_EQ("error", res->body);
  3994. }
  3995. }
  3996. // The pre-request handler must run before the request body is read, so a
  3997. // rejected request never forces the server to buffer a (potentially large)
  3998. // body. Here the posted body is larger than the payload limit: if the body
  3999. // were read first the server would answer 413, but because the pre-request
  4000. // handler runs first it answers 403 and the body is never read.
  4001. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  4002. Server svr;
  4003. svr.set_payload_max_length(8);
  4004. auto handler_ran = false;
  4005. svr.Post("/reject", [&](const Request &req, Response &res) {
  4006. handler_ran = true;
  4007. res.set_content(req.body, "text/plain");
  4008. });
  4009. svr.Post("/accept", [](const Request &req, Response &res) {
  4010. res.set_content(req.body, "text/plain");
  4011. });
  4012. svr.set_pre_request_handler([](const Request &req, Response &res) {
  4013. if (req.matched_route == "/reject") {
  4014. res.status = StatusCode::Forbidden_403;
  4015. res.set_content("denied", "text/plain");
  4016. return Server::HandlerResponse::Handled;
  4017. }
  4018. return Server::HandlerResponse::Unhandled;
  4019. });
  4020. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4021. auto se = detail::scope_exit([&] {
  4022. svr.stop();
  4023. thread.join();
  4024. ASSERT_FALSE(svr.is_running());
  4025. });
  4026. svr.wait_until_ready();
  4027. Client cli(HOST, PORT);
  4028. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  4029. // rejects with 403 before the body is read, so 413 is never reached.
  4030. {
  4031. auto res = cli.Post("/reject", "0123456789", "text/plain");
  4032. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4033. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4034. EXPECT_EQ("denied", res->body);
  4035. EXPECT_FALSE(handler_ran);
  4036. }
  4037. // An approved route still reads the body and enforces the payload limit.
  4038. {
  4039. auto res = cli.Post("/accept", "0123456789", "text/plain");
  4040. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4041. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  4042. }
  4043. }
  4044. TEST(UserDataTest, BasicOperations) {
  4045. httplib::UserData ud;
  4046. // Initially empty
  4047. EXPECT_FALSE(ud.has("key"));
  4048. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4049. // set and get
  4050. ud.set("key", 42);
  4051. EXPECT_TRUE(ud.has("key"));
  4052. auto *p = ud.get<int>("key");
  4053. ASSERT_NE(nullptr, p);
  4054. EXPECT_EQ(42, *p);
  4055. // Type mismatch → nullptr
  4056. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  4057. // Overwrite with different type
  4058. ud.set("key", std::string("hello"));
  4059. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4060. auto *s = ud.get<std::string>("key");
  4061. ASSERT_NE(nullptr, s);
  4062. EXPECT_EQ("hello", *s);
  4063. // erase
  4064. ud.erase("key");
  4065. EXPECT_FALSE(ud.has("key"));
  4066. // clear
  4067. ud.set("a", 1);
  4068. ud.set("b", 2);
  4069. ud.clear();
  4070. EXPECT_FALSE(ud.has("a"));
  4071. EXPECT_FALSE(ud.has("b"));
  4072. }
  4073. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  4074. struct AuthCtx {
  4075. std::string user_id;
  4076. };
  4077. Server svr;
  4078. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  4079. res.user_data.set("auth", AuthCtx{"alice"});
  4080. return Server::HandlerResponse::Unhandled;
  4081. });
  4082. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  4083. auto *ctx = res.user_data.get<AuthCtx>("auth");
  4084. ASSERT_NE(nullptr, ctx);
  4085. res.set_content("Hello " + ctx->user_id, "text/plain");
  4086. });
  4087. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4088. auto se = detail::scope_exit([&] {
  4089. svr.stop();
  4090. thread.join();
  4091. ASSERT_FALSE(svr.is_running());
  4092. });
  4093. svr.wait_until_ready();
  4094. Client cli(HOST, PORT);
  4095. auto res = cli.Get("/me");
  4096. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4097. EXPECT_EQ(StatusCode::OK_200, res->status);
  4098. EXPECT_EQ("Hello alice", res->body);
  4099. }
  4100. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  4101. struct RoleCtx {
  4102. std::string role;
  4103. };
  4104. Server svr;
  4105. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  4106. res.user_data.set("role", RoleCtx{"admin"});
  4107. return Server::HandlerResponse::Unhandled;
  4108. });
  4109. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  4110. auto *ctx = res.user_data.get<RoleCtx>("role");
  4111. ASSERT_NE(nullptr, ctx);
  4112. res.set_content(ctx->role, "text/plain");
  4113. });
  4114. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4115. auto se = detail::scope_exit([&] {
  4116. svr.stop();
  4117. thread.join();
  4118. ASSERT_FALSE(svr.is_running());
  4119. });
  4120. svr.wait_until_ready();
  4121. Client cli(HOST, PORT);
  4122. auto res = cli.Get("/role");
  4123. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4124. EXPECT_EQ(StatusCode::OK_200, res->status);
  4125. EXPECT_EQ("admin", res->body);
  4126. }
  4127. TEST(InvalidFormatTest, StatusCode) {
  4128. Server svr;
  4129. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4130. res.set_content("Hello World!\n", "text/plain");
  4131. res.status = 9999; // Status should be a three-digit code...
  4132. });
  4133. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4134. auto se = detail::scope_exit([&] {
  4135. svr.stop();
  4136. thread.join();
  4137. ASSERT_FALSE(svr.is_running());
  4138. });
  4139. svr.wait_until_ready();
  4140. {
  4141. Client cli(HOST, PORT);
  4142. auto res = cli.Get("/hi");
  4143. ASSERT_FALSE(res);
  4144. }
  4145. }
  4146. TEST(URLFragmentTest, WithFragment) {
  4147. Server svr;
  4148. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  4149. EXPECT_TRUE(req.target == "/hi");
  4150. });
  4151. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4152. auto se = detail::scope_exit([&] {
  4153. svr.stop();
  4154. thread.join();
  4155. ASSERT_FALSE(svr.is_running());
  4156. });
  4157. svr.wait_until_ready();
  4158. {
  4159. Client cli(HOST, PORT);
  4160. auto res = cli.Get("/hi#key1=val1=key2=val2");
  4161. EXPECT_TRUE(res);
  4162. EXPECT_EQ(StatusCode::OK_200, res->status);
  4163. res = cli.Get("/hi%23key1=val1=key2=val2");
  4164. EXPECT_TRUE(res);
  4165. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4166. }
  4167. }
  4168. TEST(HeaderWriter, SetHeaderWriter) {
  4169. Server svr;
  4170. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  4171. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  4172. return detail::write_headers(strm, hdrs);
  4173. });
  4174. svr.Get("/hi", [](const Request &req, Response &res) {
  4175. auto it = req.headers.find("CustomClientHeader");
  4176. EXPECT_TRUE(it != req.headers.end());
  4177. EXPECT_EQ(it->second, "CustomClientValue");
  4178. res.set_content("Hello World!\n", "text/plain");
  4179. });
  4180. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4181. auto se = detail::scope_exit([&] {
  4182. svr.stop();
  4183. thread.join();
  4184. ASSERT_FALSE(svr.is_running());
  4185. });
  4186. svr.wait_until_ready();
  4187. {
  4188. Client cli(HOST, PORT);
  4189. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  4190. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  4191. return detail::write_headers(strm, hdrs);
  4192. });
  4193. auto res = cli.Get("/hi");
  4194. EXPECT_TRUE(res);
  4195. EXPECT_EQ(StatusCode::OK_200, res->status);
  4196. auto it = res->headers.find("CustomServerHeader");
  4197. EXPECT_TRUE(it != res->headers.end());
  4198. EXPECT_EQ(it->second, "CustomServerValue");
  4199. }
  4200. }
  4201. class ServerTest : public ::testing::Test {
  4202. protected:
  4203. ServerTest()
  4204. : cli_(HOST, PORT)
  4205. #ifdef CPPHTTPLIB_SSL_ENABLED
  4206. ,
  4207. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  4208. #endif
  4209. {
  4210. #ifdef CPPHTTPLIB_SSL_ENABLED
  4211. cli_.enable_server_certificate_verification(false);
  4212. #endif
  4213. // Allow LARGE_DATA (100MB) responses
  4214. cli_.set_payload_max_length(200 * 1024 * 1024);
  4215. }
  4216. virtual void SetUp() {
  4217. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  4218. svr_.set_payload_max_length(200 * 1024 * 1024);
  4219. svr_.set_mount_point("/", "./www");
  4220. svr_.set_mount_point("/mount", "./www2");
  4221. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  4222. svr_.Get("/hi",
  4223. [&](const Request & /*req*/, Response &res) {
  4224. res.set_content("Hello World!", "text/plain");
  4225. })
  4226. .Get("/file_content",
  4227. [&](const Request & /*req*/, Response &res) {
  4228. res.set_file_content("./www/dir/test.html");
  4229. })
  4230. .Get("/file_content_with_content_type",
  4231. [&](const Request & /*req*/, Response &res) {
  4232. res.set_file_content("./www/file", "text/plain");
  4233. })
  4234. .Get("/invalid_file_content",
  4235. [&](const Request & /*req*/, Response &res) {
  4236. res.set_file_content("./www/dir/invalid_file_path");
  4237. })
  4238. .Get("/http_response_splitting",
  4239. [&](const Request & /*req*/, Response &res) {
  4240. res.set_header("a", "1\r\nSet-Cookie: a=1");
  4241. EXPECT_EQ(0U, res.headers.size());
  4242. EXPECT_FALSE(res.has_header("a"));
  4243. res.set_header("a", "1\nSet-Cookie: a=1");
  4244. EXPECT_EQ(0U, res.headers.size());
  4245. EXPECT_FALSE(res.has_header("a"));
  4246. res.set_header("a", "1\rSet-Cookie: a=1");
  4247. EXPECT_EQ(0U, res.headers.size());
  4248. EXPECT_FALSE(res.has_header("a"));
  4249. res.set_header("a\r\nb", "0");
  4250. EXPECT_EQ(0U, res.headers.size());
  4251. EXPECT_FALSE(res.has_header("a"));
  4252. res.set_header("a\rb", "0");
  4253. EXPECT_EQ(0U, res.headers.size());
  4254. EXPECT_FALSE(res.has_header("a"));
  4255. res.set_header("a\nb", "0");
  4256. EXPECT_EQ(0U, res.headers.size());
  4257. EXPECT_FALSE(res.has_header("a"));
  4258. res.set_redirect("1\r\nSet-Cookie: a=1");
  4259. EXPECT_EQ(0U, res.headers.size());
  4260. EXPECT_FALSE(res.has_header("Location"));
  4261. })
  4262. .Get("/slow",
  4263. [&](const Request & /*req*/, Response &res) {
  4264. std::this_thread::sleep_for(std::chrono::seconds(4));
  4265. res.set_content("slow", "text/plain");
  4266. })
  4267. #if 0
  4268. .Post("/slowpost",
  4269. [&](const Request & /*req*/, Response &res) {
  4270. std::this_thread::sleep_for(std::chrono::seconds(2));
  4271. res.set_content("slow", "text/plain");
  4272. })
  4273. #endif
  4274. .Get("/remote_addr",
  4275. [&](const Request &req, Response &res) {
  4276. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  4277. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  4278. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4279. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  4280. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  4281. #endif
  4282. res.set_content(req.remote_addr, "text/plain");
  4283. })
  4284. .Get("/local_addr",
  4285. [&](const Request &req, Response &res) {
  4286. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  4287. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  4288. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4289. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  4290. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  4291. #endif
  4292. auto local_addr = req.local_addr;
  4293. auto local_port = std::to_string(req.local_port);
  4294. res.set_content(local_addr.append(":").append(local_port),
  4295. "text/plain");
  4296. })
  4297. .Get("/endwith%",
  4298. [&](const Request & /*req*/, Response &res) {
  4299. res.set_content("Hello World!", "text/plain");
  4300. })
  4301. .Get("/a\\+\\+b",
  4302. [&](const Request &req, Response &res) {
  4303. ASSERT_TRUE(req.has_param("a +b"));
  4304. auto val = req.get_param_value("a +b");
  4305. res.set_content(val, "text/plain");
  4306. })
  4307. .Get("/", [&](const Request & /*req*/,
  4308. Response &res) { res.set_redirect("/hi"); })
  4309. .Post("/1",
  4310. [](const Request & /*req*/, Response &res) {
  4311. res.set_redirect("/2", StatusCode::SeeOther_303);
  4312. })
  4313. .Get("/2",
  4314. [](const Request & /*req*/, Response &res) {
  4315. res.set_content("redirected.", "text/plain");
  4316. res.status = StatusCode::OK_200;
  4317. })
  4318. .Post("/person",
  4319. [&](const Request &req, Response &res) {
  4320. if (req.has_param("name") && req.has_param("note")) {
  4321. persons_[req.get_param_value("name")] =
  4322. req.get_param_value("note");
  4323. } else {
  4324. res.status = StatusCode::BadRequest_400;
  4325. }
  4326. })
  4327. .Put("/person",
  4328. [&](const Request &req, Response &res) {
  4329. if (req.has_param("name") && req.has_param("note")) {
  4330. persons_[req.get_param_value("name")] =
  4331. req.get_param_value("note");
  4332. } else {
  4333. res.status = StatusCode::BadRequest_400;
  4334. }
  4335. })
  4336. .Get("/person/(.*)",
  4337. [&](const Request &req, Response &res) {
  4338. string name = req.matches[1];
  4339. if (persons_.find(name) != persons_.end()) {
  4340. auto note = persons_[name];
  4341. res.set_content(note, "text/plain");
  4342. } else {
  4343. res.status = StatusCode::NotFound_404;
  4344. }
  4345. })
  4346. .Delete("/person",
  4347. [&](const Request &req, Response &res) {
  4348. if (req.has_param("name")) {
  4349. string name = req.get_param_value("name");
  4350. if (persons_.find(name) != persons_.end()) {
  4351. persons_.erase(name);
  4352. res.set_content("DELETED", "text/plain");
  4353. } else {
  4354. res.status = StatusCode::NotFound_404;
  4355. }
  4356. } else {
  4357. res.status = StatusCode::BadRequest_400;
  4358. }
  4359. })
  4360. .Post("/x-www-form-urlencoded-json",
  4361. [&](const Request &req, Response &res) {
  4362. auto json = req.get_param_value("json");
  4363. ASSERT_EQ(JSON_DATA, json);
  4364. res.set_content(json, "appliation/json");
  4365. res.status = StatusCode::OK_200;
  4366. })
  4367. .Get("/streamed-chunked",
  4368. [&](const Request & /*req*/, Response &res) {
  4369. res.set_chunked_content_provider(
  4370. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  4371. sink.os << "123";
  4372. sink.os << "456";
  4373. sink.os << "789";
  4374. sink.done();
  4375. return true;
  4376. });
  4377. })
  4378. .Get("/streamed-chunked-with-prohibited-trailer",
  4379. [&](const Request & /*req*/, Response &res) {
  4380. auto i = new int(0);
  4381. // Declare both a prohibited trailer (Content-Length) and an
  4382. // allowed one
  4383. res.set_header("Trailer", "Content-Length, X-Allowed");
  4384. res.set_chunked_content_provider(
  4385. "text/plain",
  4386. [i](size_t /*offset*/, DataSink &sink) {
  4387. switch (*i) {
  4388. case 0: sink.os << "123"; break;
  4389. case 1: sink.os << "456"; break;
  4390. case 2: sink.os << "789"; break;
  4391. case 3: {
  4392. sink.done_with_trailer(
  4393. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  4394. } break;
  4395. }
  4396. (*i)++;
  4397. return true;
  4398. },
  4399. [i](bool success) {
  4400. EXPECT_TRUE(success);
  4401. delete i;
  4402. });
  4403. })
  4404. .Get("/streamed-chunked2",
  4405. [&](const Request & /*req*/, Response &res) {
  4406. auto i = new int(0);
  4407. res.set_chunked_content_provider(
  4408. "text/plain",
  4409. [i](size_t /*offset*/, DataSink &sink) {
  4410. switch (*i) {
  4411. case 0: sink.os << "123"; break;
  4412. case 1: sink.os << "456"; break;
  4413. case 2: sink.os << "789"; break;
  4414. case 3: sink.done(); break;
  4415. }
  4416. (*i)++;
  4417. return true;
  4418. },
  4419. [i](bool success) {
  4420. EXPECT_TRUE(success);
  4421. delete i;
  4422. });
  4423. })
  4424. .Get("/streamed-chunked-with-trailer",
  4425. [&](const Request & /*req*/, Response &res) {
  4426. auto i = new int(0);
  4427. res.set_header("Trailer", "Dummy1, Dummy2");
  4428. res.set_chunked_content_provider(
  4429. "text/plain",
  4430. [i](size_t /*offset*/, DataSink &sink) {
  4431. switch (*i) {
  4432. case 0: sink.os << "123"; break;
  4433. case 1: sink.os << "456"; break;
  4434. case 2: sink.os << "789"; break;
  4435. case 3: {
  4436. sink.done_with_trailer(
  4437. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  4438. } break;
  4439. }
  4440. (*i)++;
  4441. return true;
  4442. },
  4443. [i](bool success) {
  4444. EXPECT_TRUE(success);
  4445. delete i;
  4446. });
  4447. })
  4448. .Get("/streamed",
  4449. [&](const Request & /*req*/, Response &res) {
  4450. res.set_content_provider(
  4451. 6, "text/plain",
  4452. [](size_t offset, size_t /*length*/, DataSink &sink) {
  4453. sink.os << (offset < 3 ? "a" : "b");
  4454. return true;
  4455. });
  4456. })
  4457. .Get("/streamed-without-length",
  4458. [&](const Request & /*req*/, Response &res) {
  4459. auto data = new std::string("abcdefg");
  4460. res.set_content_provider(
  4461. "text/plain",
  4462. [data](size_t offset, DataSink &sink) {
  4463. if (offset < data->size()) {
  4464. sink.os << data->substr(offset);
  4465. }
  4466. sink.done();
  4467. return true;
  4468. },
  4469. [data](bool success) {
  4470. EXPECT_TRUE(success);
  4471. delete data;
  4472. });
  4473. })
  4474. .Get("/streamed-with-range",
  4475. [&](const Request &req, Response &res) {
  4476. auto data = new std::string("abcdefg");
  4477. // An explicit status keeps the server from picking the 206 it
  4478. // would otherwise choose for a ranged request, so the response
  4479. // is not a partial representation.
  4480. auto status = req.get_param_value("status");
  4481. if (status == "200") {
  4482. res.status = StatusCode::OK_200;
  4483. } else if (status == "403") {
  4484. res.status = StatusCode::Forbidden_403;
  4485. }
  4486. res.set_content_provider(
  4487. data->size(), "text/plain",
  4488. [data](size_t offset, size_t length, DataSink &sink) {
  4489. size_t DATA_CHUNK_SIZE = 4;
  4490. const auto &d = *data;
  4491. auto out_len =
  4492. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  4493. auto ret =
  4494. sink.write(&d[static_cast<size_t>(offset)], out_len);
  4495. EXPECT_TRUE(ret);
  4496. return true;
  4497. },
  4498. [data, &req](bool success) {
  4499. EXPECT_EQ(success, !req.has_param("error"));
  4500. delete data;
  4501. });
  4502. })
  4503. .Get("/streamed-cancel",
  4504. [&](const Request & /*req*/, Response &res) {
  4505. res.set_content_provider(
  4506. size_t(-1), "text/plain",
  4507. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4508. sink.os << "data_chunk";
  4509. return true;
  4510. });
  4511. })
  4512. .Get("/regex-with-delimiter",
  4513. [&](const Request &req, Response & /*res*/) {
  4514. ASSERT_TRUE(req.has_param("key"));
  4515. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  4516. })
  4517. .Get("/with-range",
  4518. [&](const Request & /*req*/, Response &res) {
  4519. res.set_content("abcdefg", "text/plain");
  4520. })
  4521. .Get("/test-start-time",
  4522. [&](const Request &req, Response & /*res*/) {
  4523. EXPECT_NE(req.start_time_,
  4524. std::chrono::steady_clock::time_point::min());
  4525. })
  4526. .Get("/with-range-customized-response",
  4527. [&](const Request & /*req*/, Response &res) {
  4528. res.status = StatusCode::BadRequest_400;
  4529. res.set_content(JSON_DATA, "application/json");
  4530. })
  4531. .Post("/chunked",
  4532. [&](const Request &req, Response & /*res*/) {
  4533. EXPECT_EQ(req.body, "dechunked post body");
  4534. })
  4535. .Post("/large-chunked",
  4536. [&](const Request &req, Response & /*res*/) {
  4537. std::string expected(6 * 30 * 1024u, 'a');
  4538. EXPECT_EQ(req.body, expected);
  4539. })
  4540. .Post("/multipart",
  4541. [&](const Request &req, Response & /*res*/) {
  4542. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  4543. req.form.get_field_count("text2") +
  4544. req.form.get_field_count("file3") +
  4545. req.form.get_field_count("file4"));
  4546. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  4547. req.form.get_file_count("file2"));
  4548. ASSERT_TRUE(!req.form.has_file("???"));
  4549. ASSERT_TRUE(!req.form.has_field("???"));
  4550. ASSERT_TRUE(req.body.empty());
  4551. {
  4552. const auto &text = req.form.get_field("text1");
  4553. EXPECT_EQ("text default", text);
  4554. }
  4555. {
  4556. const auto &text = req.form.get_field("text2");
  4557. EXPECT_EQ("aωb", text);
  4558. }
  4559. {
  4560. const auto &file = req.form.get_file("file1");
  4561. EXPECT_EQ("hello.txt", file.filename);
  4562. EXPECT_EQ("text/plain", file.content_type);
  4563. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  4564. }
  4565. {
  4566. const auto &file = req.form.get_file("file2");
  4567. EXPECT_EQ("world.json", file.filename);
  4568. EXPECT_EQ("application/json", file.content_type);
  4569. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  4570. }
  4571. {
  4572. const auto &text = req.form.get_field("file3");
  4573. EXPECT_EQ(0u, text.size());
  4574. }
  4575. {
  4576. const auto &text = req.form.get_field("file4");
  4577. EXPECT_EQ(0u, text.size());
  4578. }
  4579. })
  4580. .Post("/multipart/multi_file_values",
  4581. [&](const Request &req, Response & /*res*/) {
  4582. EXPECT_EQ(3u, req.form.get_field_count("text") +
  4583. req.form.get_field_count("multi_text1"));
  4584. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  4585. ASSERT_TRUE(!req.form.has_file("???"));
  4586. ASSERT_TRUE(!req.form.has_field("???"));
  4587. ASSERT_TRUE(req.body.empty());
  4588. {
  4589. const auto &text = req.form.get_field("text");
  4590. EXPECT_EQ("default text", text);
  4591. }
  4592. {
  4593. const auto &text1_values = req.form.get_fields("multi_text1");
  4594. EXPECT_EQ(2u, text1_values.size());
  4595. EXPECT_EQ("aaaaa", text1_values[0]);
  4596. EXPECT_EQ("bbbbb", text1_values[1]);
  4597. }
  4598. {
  4599. const auto &file1_values = req.form.get_files("multi_file1");
  4600. EXPECT_EQ(2u, file1_values.size());
  4601. auto file1 = file1_values[0];
  4602. EXPECT_EQ(file1.filename, "hello.txt");
  4603. EXPECT_EQ(file1.content_type, "text/plain");
  4604. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  4605. auto file2 = file1_values[1];
  4606. EXPECT_EQ(file2.filename, "world.json");
  4607. EXPECT_EQ(file2.content_type, "application/json");
  4608. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  4609. }
  4610. })
  4611. .Post("/empty",
  4612. [&](const Request &req, Response &res) {
  4613. EXPECT_EQ(req.body, "");
  4614. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  4615. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4616. res.set_content("empty", "text/plain");
  4617. })
  4618. .Post("/empty-no-content-type",
  4619. [&](const Request &req, Response &res) {
  4620. EXPECT_EQ(req.body, "");
  4621. EXPECT_FALSE(req.has_header("Content-Type"));
  4622. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4623. res.set_content("empty-no-content-type", "text/plain");
  4624. })
  4625. .Post("/path-only",
  4626. [&](const Request &req, Response &res) {
  4627. EXPECT_EQ(req.body, "");
  4628. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4629. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4630. res.set_content("path-only", "text/plain");
  4631. })
  4632. .Post("/path-headers-only",
  4633. [&](const Request &req, Response &res) {
  4634. EXPECT_EQ(req.body, "");
  4635. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4636. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4637. EXPECT_EQ("world", req.get_header_value("hello"));
  4638. EXPECT_EQ("world2", req.get_header_value("hello2"));
  4639. res.set_content("path-headers-only", "text/plain");
  4640. })
  4641. .Post("/post-large",
  4642. [&](const Request &req, Response &res) {
  4643. EXPECT_EQ(req.body, LARGE_DATA);
  4644. res.set_content(req.body, "text/plain");
  4645. })
  4646. .Post("/post-loopback",
  4647. [&](const Request &, Response &res,
  4648. ContentReader const &content_reader) {
  4649. std::string body;
  4650. content_reader([&](const char *data, size_t data_length) {
  4651. body.append(data, data_length);
  4652. return true;
  4653. });
  4654. res.set_content(body, "text/plain");
  4655. })
  4656. .Put("/put-loopback",
  4657. [&](const Request &, Response &res,
  4658. ContentReader const &content_reader) {
  4659. std::string body;
  4660. content_reader([&](const char *data, size_t data_length) {
  4661. body.append(data, data_length);
  4662. return true;
  4663. });
  4664. res.set_content(body, "text/plain");
  4665. })
  4666. .Patch("/patch-loopback",
  4667. [&](const Request &, Response &res,
  4668. ContentReader const &content_reader) {
  4669. std::string body;
  4670. content_reader([&](const char *data, size_t data_length) {
  4671. body.append(data, data_length);
  4672. return true;
  4673. });
  4674. res.set_content(body, "text/plain");
  4675. })
  4676. .Put("/empty-no-content-type",
  4677. [&](const Request &req, Response &res) {
  4678. EXPECT_EQ(req.body, "");
  4679. EXPECT_FALSE(req.has_header("Content-Type"));
  4680. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4681. res.set_content("empty-no-content-type", "text/plain");
  4682. })
  4683. .Put("/put",
  4684. [&](const Request &req, Response &res) {
  4685. EXPECT_EQ(req.body, "PUT");
  4686. res.set_content(req.body, "text/plain");
  4687. })
  4688. .Put("/put-large",
  4689. [&](const Request &req, Response &res) {
  4690. EXPECT_EQ(req.body, LARGE_DATA);
  4691. res.set_content(req.body, "text/plain");
  4692. })
  4693. .Patch("/patch",
  4694. [&](const Request &req, Response &res) {
  4695. EXPECT_EQ(req.body, "PATCH");
  4696. res.set_content(req.body, "text/plain");
  4697. })
  4698. .Delete("/delete",
  4699. [&](const Request & /*req*/, Response &res) {
  4700. res.set_content("DELETE", "text/plain");
  4701. })
  4702. .Delete("/delete-body",
  4703. [&](const Request &req, Response &res) {
  4704. EXPECT_EQ(req.body, "content");
  4705. res.set_content(req.body, "text/plain");
  4706. })
  4707. .Options(R"(\*)",
  4708. [&](const Request & /*req*/, Response &res) {
  4709. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  4710. })
  4711. .CustomRoute("PROPFIND", "/dav/:id",
  4712. [&](const Request &req, Response &res) {
  4713. res.set_header("x-body-size",
  4714. std::to_string(req.body.size()));
  4715. res.set_header("x-matched-route", req.matched_route);
  4716. res.set_header("x-dav-id", req.path_params.at("id"));
  4717. res.status = StatusCode::MultiStatus_207;
  4718. res.set_content(req.body, "application/xml");
  4719. })
  4720. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  4721. [&](const Request &req, Response &res) {
  4722. res.set_header("x-dav-match", req.matches[1]);
  4723. res.status = StatusCode::MultiStatus_207;
  4724. })
  4725. .CustomRoute("MKCOL", "/dav-mkcol",
  4726. [&](const Request &req, Response &res) {
  4727. EXPECT_TRUE(req.body.empty());
  4728. res.status = StatusCode::Created_201;
  4729. })
  4730. .CustomRoute(
  4731. "REPORT", "/dav-report",
  4732. [&](const Request & /*req*/, Response &res,
  4733. const ContentReader &content_reader) {
  4734. std::string body;
  4735. content_reader([&](const char *data, size_t data_length) {
  4736. body.append(data, data_length);
  4737. return true;
  4738. });
  4739. res.set_header("x-body-size", std::to_string(body.size()));
  4740. res.status = StatusCode::MultiStatus_207;
  4741. res.set_content(body, "application/xml");
  4742. })
  4743. .Get("/request-target",
  4744. [&](const Request &req, Response & /*res*/) {
  4745. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  4746. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  4747. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  4748. })
  4749. .Get("/long-query-value",
  4750. [&](const Request &req, Response & /*res*/) {
  4751. EXPECT_EQ(LONG_QUERY_URL, req.target);
  4752. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  4753. })
  4754. .Get("/too-long-query-value",
  4755. [&](const Request &req, Response & /*res*/) {
  4756. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  4757. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  4758. })
  4759. .Get("/array-param",
  4760. [&](const Request &req, Response & /*res*/) {
  4761. EXPECT_EQ(3u, req.get_param_value_count("array"));
  4762. EXPECT_EQ("value1", req.get_param_value("array", 0));
  4763. EXPECT_EQ("value2", req.get_param_value("array", 1));
  4764. EXPECT_EQ("value3", req.get_param_value("array", 2));
  4765. })
  4766. .Get("/array-param-values",
  4767. [&](const Request &req, Response & /*res*/) {
  4768. auto values = req.get_param_values("array");
  4769. EXPECT_EQ(3u, values.size());
  4770. EXPECT_EQ("value1", values[0]);
  4771. EXPECT_EQ("value2", values[1]);
  4772. EXPECT_EQ("value3", values[2]);
  4773. auto empty = req.get_param_values("nonexistent");
  4774. EXPECT_TRUE(empty.empty());
  4775. })
  4776. .Post("/validate-no-multiple-headers",
  4777. [&](const Request &req, Response & /*res*/) {
  4778. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  4779. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  4780. })
  4781. .Post("/content_receiver",
  4782. [&](const Request &req, Response &res,
  4783. const ContentReader &content_reader) {
  4784. if (req.is_multipart_form_data()) {
  4785. std::vector<FormData> items;
  4786. content_reader(
  4787. [&](const FormData &file) {
  4788. items.push_back(file);
  4789. return true;
  4790. },
  4791. [&](const char *data, size_t data_length) {
  4792. items.back().content.append(data, data_length);
  4793. return true;
  4794. });
  4795. EXPECT_EQ(5u, items.size());
  4796. {
  4797. const auto &file = get_file_value(items, "text1");
  4798. EXPECT_TRUE(file.filename.empty());
  4799. EXPECT_EQ("text default", file.content);
  4800. }
  4801. {
  4802. const auto &file = get_file_value(items, "text2");
  4803. EXPECT_TRUE(file.filename.empty());
  4804. EXPECT_EQ("aωb", file.content);
  4805. }
  4806. {
  4807. const auto &file = get_file_value(items, "file1");
  4808. EXPECT_EQ("hello.txt", file.filename);
  4809. EXPECT_EQ("text/plain", file.content_type);
  4810. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  4811. }
  4812. {
  4813. const auto &file = get_file_value(items, "file2");
  4814. EXPECT_EQ("world.json", file.filename);
  4815. EXPECT_EQ("application/json", file.content_type);
  4816. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  4817. }
  4818. {
  4819. const auto &file = get_file_value(items, "file3");
  4820. EXPECT_TRUE(file.filename.empty());
  4821. EXPECT_EQ("application/octet-stream", file.content_type);
  4822. EXPECT_EQ(0u, file.content.size());
  4823. }
  4824. } else {
  4825. std::string body;
  4826. content_reader([&](const char *data, size_t data_length) {
  4827. EXPECT_EQ(7U, data_length);
  4828. body.append(data, data_length);
  4829. return true;
  4830. });
  4831. EXPECT_EQ(body, "content");
  4832. res.set_content(body, "text/plain");
  4833. }
  4834. })
  4835. .Put("/content_receiver",
  4836. [&](const Request & /*req*/, Response &res,
  4837. const ContentReader &content_reader) {
  4838. std::string body;
  4839. content_reader([&](const char *data, size_t data_length) {
  4840. body.append(data, data_length);
  4841. return true;
  4842. });
  4843. EXPECT_EQ(body, "content");
  4844. res.set_content(body, "text/plain");
  4845. })
  4846. .Patch("/content_receiver",
  4847. [&](const Request & /*req*/, Response &res,
  4848. const ContentReader &content_reader) {
  4849. std::string body;
  4850. content_reader([&](const char *data, size_t data_length) {
  4851. body.append(data, data_length);
  4852. return true;
  4853. });
  4854. EXPECT_EQ(body, "content");
  4855. res.set_content(body, "text/plain");
  4856. })
  4857. .Post("/query-string-and-body",
  4858. [&](const Request &req, Response & /*res*/) {
  4859. ASSERT_TRUE(req.has_param("key"));
  4860. EXPECT_EQ(req.get_param_value("key"), "value");
  4861. EXPECT_EQ(req.body, "content");
  4862. })
  4863. .Get("/last-request",
  4864. [&](const Request &req, Response & /*res*/) {
  4865. EXPECT_EQ("close", req.get_header_value("Connection"));
  4866. })
  4867. .Get(R"(/redirect/(\d+))",
  4868. [&](const Request &req, Response &res) {
  4869. auto num = std::stoi(req.matches[1]) + 1;
  4870. std::string url = "/redirect/" + std::to_string(num);
  4871. res.set_redirect(url);
  4872. })
  4873. .Post("/binary",
  4874. [&](const Request &req, Response &res) {
  4875. EXPECT_EQ(4U, req.body.size());
  4876. EXPECT_EQ("application/octet-stream",
  4877. req.get_header_value("Content-Type"));
  4878. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4879. res.set_content(req.body, "application/octet-stream");
  4880. })
  4881. .Put("/binary",
  4882. [&](const Request &req, Response &res) {
  4883. EXPECT_EQ(4U, req.body.size());
  4884. EXPECT_EQ("application/octet-stream",
  4885. req.get_header_value("Content-Type"));
  4886. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4887. res.set_content(req.body, "application/octet-stream");
  4888. })
  4889. .Patch("/binary",
  4890. [&](const Request &req, Response &res) {
  4891. EXPECT_EQ(4U, req.body.size());
  4892. EXPECT_EQ("application/octet-stream",
  4893. req.get_header_value("Content-Type"));
  4894. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4895. res.set_content(req.body, "application/octet-stream");
  4896. })
  4897. .Delete("/binary",
  4898. [&](const Request &req, Response &res) {
  4899. EXPECT_EQ(4U, req.body.size());
  4900. EXPECT_EQ("application/octet-stream",
  4901. req.get_header_value("Content-Type"));
  4902. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4903. res.set_content(req.body, "application/octet-stream");
  4904. })
  4905. .Get("/issue1772",
  4906. [&](const Request & /*req*/, Response &res) {
  4907. res.status = 401;
  4908. res.set_header("WWW-Authenticate", "Basic realm=123456");
  4909. })
  4910. .Delete("/issue609",
  4911. [](const httplib::Request &, httplib::Response &res,
  4912. const httplib::ContentReader &) {
  4913. res.set_content("ok", "text/plain");
  4914. })
  4915. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  4916. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  4917. .Get("/compress",
  4918. [&](const Request & /*req*/, Response &res) {
  4919. res.set_content(
  4920. "12345678901234567890123456789012345678901234567890123456789"
  4921. "01234567890123456789012345678901234567890",
  4922. "text/plain");
  4923. })
  4924. .Get("/compress-with-charset",
  4925. [&](const Request & /*req*/, Response &res) {
  4926. res.set_content(
  4927. "12345678901234567890123456789012345678901234567890123456789"
  4928. "01234567890123456789012345678901234567890",
  4929. "application/json; charset=utf-8");
  4930. })
  4931. .Get("/nocompress",
  4932. [&](const Request & /*req*/, Response &res) {
  4933. res.set_content(
  4934. "12345678901234567890123456789012345678901234567890123456789"
  4935. "01234567890123456789012345678901234567890",
  4936. "application/octet-stream");
  4937. })
  4938. .Post("/compress-multipart",
  4939. [&](const Request &req, Response & /*res*/) {
  4940. EXPECT_EQ(2u, req.form.fields.size());
  4941. ASSERT_TRUE(!req.form.has_field("???"));
  4942. {
  4943. const auto &text = req.form.get_field("key1");
  4944. EXPECT_EQ("test", text);
  4945. }
  4946. {
  4947. const auto &text = req.form.get_field("key2");
  4948. EXPECT_EQ("--abcdefg123", text);
  4949. }
  4950. })
  4951. #endif
  4952. ;
  4953. persons_["john"] = "programmer";
  4954. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  4955. svr_.wait_until_ready();
  4956. }
  4957. virtual void TearDown() {
  4958. svr_.stop();
  4959. if (!request_threads_.empty()) {
  4960. std::this_thread::sleep_for(std::chrono::seconds(1));
  4961. for (auto &t : request_threads_) {
  4962. t.join();
  4963. }
  4964. }
  4965. t_.join();
  4966. }
  4967. map<string, string> persons_;
  4968. #ifdef CPPHTTPLIB_SSL_ENABLED
  4969. SSLClient cli_;
  4970. SSLServer svr_;
  4971. #else
  4972. Client cli_;
  4973. Server svr_;
  4974. #endif
  4975. thread t_;
  4976. std::vector<thread> request_threads_;
  4977. };
  4978. TEST_F(ServerTest, GetMethod200) {
  4979. auto res = cli_.Get("/hi");
  4980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4981. EXPECT_EQ("HTTP/1.1", res->version);
  4982. EXPECT_EQ(StatusCode::OK_200, res->status);
  4983. EXPECT_EQ("OK", res->reason);
  4984. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4985. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  4986. EXPECT_EQ("Hello World!", res->body);
  4987. }
  4988. TEST_F(ServerTest, GetEmptyFile) {
  4989. auto res = cli_.Get("/empty_file");
  4990. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4991. EXPECT_EQ(StatusCode::OK_200, res->status);
  4992. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  4993. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  4994. EXPECT_EQ("", res->body);
  4995. }
  4996. TEST_F(ServerTest, GetFileContent) {
  4997. auto res = cli_.Get("/file_content");
  4998. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4999. EXPECT_EQ(StatusCode::OK_200, res->status);
  5000. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5001. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  5002. EXPECT_EQ("test.html", res->body);
  5003. }
  5004. TEST_F(ServerTest, GetFileContentWithRange) {
  5005. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  5006. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5007. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5008. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5009. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  5010. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  5011. EXPECT_EQ("est", res->body);
  5012. }
  5013. TEST_F(ServerTest, GetFileContentWithContentType) {
  5014. auto res = cli_.Get("/file_content_with_content_type");
  5015. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5016. EXPECT_EQ(StatusCode::OK_200, res->status);
  5017. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5018. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  5019. EXPECT_EQ("file\n", res->body);
  5020. }
  5021. TEST_F(ServerTest, GetInvalidFileContent) {
  5022. auto res = cli_.Get("/invalid_file_content");
  5023. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5024. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5025. }
  5026. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  5027. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  5028. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5029. EXPECT_EQ("HTTP/1.1", res->version);
  5030. EXPECT_EQ(StatusCode::OK_200, res->status);
  5031. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5032. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5033. EXPECT_EQ("Hello World!", res->body);
  5034. }
  5035. TEST_F(ServerTest, GetMethod302) {
  5036. auto res = cli_.Get("/");
  5037. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5038. EXPECT_EQ(StatusCode::Found_302, res->status);
  5039. EXPECT_EQ("/hi", res->get_header_value("Location"));
  5040. }
  5041. TEST_F(ServerTest, GetMethod302Redirect) {
  5042. cli_.set_follow_location(true);
  5043. auto res = cli_.Get("/");
  5044. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5045. EXPECT_EQ(StatusCode::OK_200, res->status);
  5046. EXPECT_EQ("Hello World!", res->body);
  5047. EXPECT_EQ("/hi", res->location);
  5048. }
  5049. TEST_F(ServerTest, GetMethod404) {
  5050. auto res = cli_.Get("/invalid");
  5051. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5052. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5053. }
  5054. TEST_F(ServerTest, HeadMethod200) {
  5055. auto res = cli_.Head("/hi");
  5056. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5057. EXPECT_EQ(StatusCode::OK_200, res->status);
  5058. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5059. EXPECT_TRUE(res->body.empty());
  5060. }
  5061. TEST_F(ServerTest, HeadMethod200Static) {
  5062. auto res = cli_.Head("/mount/dir/index.html");
  5063. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5064. EXPECT_EQ(StatusCode::OK_200, res->status);
  5065. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5066. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  5067. EXPECT_TRUE(res->body.empty());
  5068. }
  5069. TEST_F(ServerTest, HeadMethod404) {
  5070. auto res = cli_.Head("/invalid");
  5071. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5072. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5073. EXPECT_TRUE(res->body.empty());
  5074. }
  5075. TEST_F(ServerTest, GetMethodPersonJohn) {
  5076. auto res = cli_.Get("/person/john");
  5077. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5078. EXPECT_EQ(StatusCode::OK_200, res->status);
  5079. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5080. EXPECT_EQ("programmer", res->body);
  5081. }
  5082. TEST_F(ServerTest, PostMethod1) {
  5083. auto res = cli_.Get("/person/john1");
  5084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5085. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5086. res = cli_.Post("/person", "name=john1&note=coder",
  5087. "application/x-www-form-urlencoded");
  5088. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5089. ASSERT_EQ(StatusCode::OK_200, res->status);
  5090. res = cli_.Get("/person/john1");
  5091. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5092. ASSERT_EQ(StatusCode::OK_200, res->status);
  5093. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5094. ASSERT_EQ("coder", res->body);
  5095. }
  5096. TEST_F(ServerTest, PostMethod2) {
  5097. auto res = cli_.Get("/person/john2");
  5098. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5099. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5100. Params params;
  5101. params.emplace("name", "john2");
  5102. params.emplace("note", "coder");
  5103. res = cli_.Post("/person", params);
  5104. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5105. ASSERT_EQ(StatusCode::OK_200, res->status);
  5106. res = cli_.Get("/person/john2");
  5107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5108. ASSERT_EQ(StatusCode::OK_200, res->status);
  5109. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5110. ASSERT_EQ("coder", res->body);
  5111. }
  5112. TEST_F(ServerTest, PutMethod3) {
  5113. auto res = cli_.Get("/person/john3");
  5114. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5115. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5116. Params params;
  5117. params.emplace("name", "john3");
  5118. params.emplace("note", "coder");
  5119. res = cli_.Put("/person", params);
  5120. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5121. ASSERT_EQ(StatusCode::OK_200, res->status);
  5122. res = cli_.Get("/person/john3");
  5123. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5124. ASSERT_EQ(StatusCode::OK_200, res->status);
  5125. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5126. ASSERT_EQ("coder", res->body);
  5127. }
  5128. TEST_F(ServerTest, DeleteMethod1) {
  5129. auto res = cli_.Get("/person/john4");
  5130. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5131. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5132. Params params;
  5133. params.emplace("name", "john4");
  5134. params.emplace("note", "coder");
  5135. res = cli_.Post("/person", params);
  5136. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5137. ASSERT_EQ(StatusCode::OK_200, res->status);
  5138. res = cli_.Get("/person/john4");
  5139. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5140. ASSERT_EQ(StatusCode::OK_200, res->status);
  5141. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5142. ASSERT_EQ("coder", res->body);
  5143. Params delete_params;
  5144. delete_params.emplace("name", "john4");
  5145. res = cli_.Delete("/person", delete_params);
  5146. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5147. ASSERT_EQ(StatusCode::OK_200, res->status);
  5148. ASSERT_EQ("DELETED", res->body);
  5149. res = cli_.Get("/person/john4");
  5150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5151. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5152. }
  5153. TEST_F(ServerTest, DeleteMethod2) {
  5154. auto res = cli_.Get("/person/john5");
  5155. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5156. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5157. Params params;
  5158. params.emplace("name", "john5");
  5159. params.emplace("note", "developer");
  5160. res = cli_.Post("/person", params);
  5161. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5162. ASSERT_EQ(StatusCode::OK_200, res->status);
  5163. res = cli_.Get("/person/john5");
  5164. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5165. ASSERT_EQ(StatusCode::OK_200, res->status);
  5166. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5167. ASSERT_EQ("developer", res->body);
  5168. Params delete_params;
  5169. delete_params.emplace("name", "john5");
  5170. Headers headers;
  5171. headers.emplace("Custom-Header", "test-value");
  5172. res = cli_.Delete("/person", headers, delete_params);
  5173. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5174. ASSERT_EQ(StatusCode::OK_200, res->status);
  5175. ASSERT_EQ("DELETED", res->body);
  5176. res = cli_.Get("/person/john5");
  5177. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5178. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5179. }
  5180. TEST_F(ServerTest, DeleteMethod3) {
  5181. auto res = cli_.Get("/person/john6");
  5182. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5183. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5184. Params params;
  5185. params.emplace("name", "john6");
  5186. params.emplace("note", "tester");
  5187. res = cli_.Post("/person", params);
  5188. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5189. ASSERT_EQ(StatusCode::OK_200, res->status);
  5190. res = cli_.Get("/person/john6");
  5191. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5192. ASSERT_EQ(StatusCode::OK_200, res->status);
  5193. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5194. ASSERT_EQ("tester", res->body);
  5195. Params delete_params;
  5196. delete_params.emplace("name", "john6");
  5197. Headers headers;
  5198. headers.emplace("Custom-Header", "test-value");
  5199. res = cli_.Delete("/person", headers, delete_params, nullptr);
  5200. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5201. ASSERT_EQ(StatusCode::OK_200, res->status);
  5202. ASSERT_EQ("DELETED", res->body);
  5203. res = cli_.Get("/person/john6");
  5204. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5205. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5206. }
  5207. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  5208. Params params;
  5209. params.emplace("json", JSON_DATA);
  5210. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  5211. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5212. ASSERT_EQ(StatusCode::OK_200, res->status);
  5213. ASSERT_EQ(JSON_DATA, res->body);
  5214. }
  5215. TEST_F(ServerTest, PostEmptyContent) {
  5216. auto res = cli_.Post("/empty", "", "text/plain");
  5217. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5218. ASSERT_EQ(StatusCode::OK_200, res->status);
  5219. ASSERT_EQ("empty", res->body);
  5220. }
  5221. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  5222. auto res = cli_.Post("/empty-no-content-type");
  5223. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5224. ASSERT_EQ(StatusCode::OK_200, res->status);
  5225. ASSERT_EQ("empty-no-content-type", res->body);
  5226. }
  5227. TEST_F(ServerTest, PostPathOnly) {
  5228. auto res = cli_.Post("/path-only");
  5229. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5230. ASSERT_EQ(StatusCode::OK_200, res->status);
  5231. ASSERT_EQ("path-only", res->body);
  5232. }
  5233. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  5234. auto res = cli_.Post("/path-headers-only",
  5235. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  5236. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5237. ASSERT_EQ(StatusCode::OK_200, res->status);
  5238. ASSERT_EQ("path-headers-only", res->body);
  5239. }
  5240. TEST_F(ServerTest, PostLarge) {
  5241. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  5242. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5243. ASSERT_EQ(StatusCode::OK_200, res->status);
  5244. EXPECT_EQ(LARGE_DATA, res->body);
  5245. }
  5246. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  5247. auto res = cli_.Put("/empty-no-content-type");
  5248. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5249. ASSERT_EQ(StatusCode::OK_200, res->status);
  5250. ASSERT_EQ("empty-no-content-type", res->body);
  5251. }
  5252. TEST_F(ServerTest, GetMethodDir) {
  5253. auto res = cli_.Get("/dir/");
  5254. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5255. EXPECT_EQ(StatusCode::OK_200, res->status);
  5256. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5257. auto body = R"(<html>
  5258. <head>
  5259. </head>
  5260. <body>
  5261. <a href="/dir/test.html">Test</a>
  5262. <a href="/hi">hi</a>
  5263. </body>
  5264. </html>
  5265. )";
  5266. EXPECT_EQ(body, res->body);
  5267. }
  5268. TEST_F(ServerTest, GetMethodDirTest) {
  5269. auto res = cli_.Get("/dir/test.html");
  5270. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5271. EXPECT_EQ(StatusCode::OK_200, res->status);
  5272. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5273. EXPECT_EQ("test.html", res->body);
  5274. }
  5275. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  5276. auto res = cli_.Get("/dir/../dir/test.html");
  5277. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5278. EXPECT_EQ(StatusCode::OK_200, res->status);
  5279. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5280. EXPECT_EQ("test.html", res->body);
  5281. }
  5282. TEST_F(ServerTest, GetMethodInvalidPath) {
  5283. auto res = cli_.Get("/dir/../test.html");
  5284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5285. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5286. }
  5287. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  5288. auto res = cli_.Get("/../www/dir/test.html");
  5289. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5290. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5291. }
  5292. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  5293. auto res = cli_.Get("/dir/../../www/dir/test.html");
  5294. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5295. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5296. }
  5297. TEST_F(ServerTest, GetMethodDirMountTest) {
  5298. auto res = cli_.Get("/mount/dir/test.html");
  5299. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5300. EXPECT_EQ(StatusCode::OK_200, res->status);
  5301. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5302. EXPECT_EQ("test.html", res->body);
  5303. }
  5304. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  5305. auto res = cli_.Get("/mount/dir/../dir/test.html");
  5306. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5307. EXPECT_EQ(StatusCode::OK_200, res->status);
  5308. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5309. EXPECT_EQ("test.html", res->body);
  5310. }
  5311. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  5312. auto res = cli_.Get("/mount/dir/../test.html");
  5313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5314. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5315. }
  5316. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  5317. auto res = cli_.Get("/mount/dir/test.html%00.js");
  5318. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5319. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5320. }
  5321. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  5322. auto res = cli_.Get("/mount/../www2/dir/test.html");
  5323. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5324. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5325. }
  5326. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  5327. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  5328. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5329. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5330. }
  5331. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  5332. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  5333. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5334. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5335. }
  5336. TEST_F(ServerTest, PostMethod303) {
  5337. auto res = cli_.Post("/1", "body", "text/plain");
  5338. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5339. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  5340. EXPECT_EQ("/2", res->get_header_value("Location"));
  5341. }
  5342. TEST_F(ServerTest, PostMethod303Redirect) {
  5343. cli_.set_follow_location(true);
  5344. auto res = cli_.Post("/1", "body", "text/plain");
  5345. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5346. EXPECT_EQ(StatusCode::OK_200, res->status);
  5347. EXPECT_EQ("redirected.", res->body);
  5348. EXPECT_EQ("/2", res->location);
  5349. }
  5350. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  5351. auto res = cli_.Get("/dir/test.abcde");
  5352. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5353. EXPECT_EQ(StatusCode::OK_200, res->status);
  5354. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5355. EXPECT_EQ("abcde", res->body);
  5356. }
  5357. TEST_F(ServerTest, StaticFileRange) {
  5358. auto res =
  5359. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  5360. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5361. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5362. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5363. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5364. EXPECT_EQ(true, res->has_header("Content-Range"));
  5365. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5366. EXPECT_EQ(std::string("cd"), res->body);
  5367. }
  5368. TEST_F(ServerTest, StaticFileRanges) {
  5369. auto res = cli_.Get("/dir/test.abcde",
  5370. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  5371. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5372. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5373. EXPECT_TRUE(
  5374. res->get_header_value("Content-Type")
  5375. .find(
  5376. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  5377. 0);
  5378. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  5379. }
  5380. TEST_F(ServerTest, StaticFileRangeHead) {
  5381. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  5382. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5383. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5384. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5385. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5386. EXPECT_EQ(true, res->has_header("Content-Range"));
  5387. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5388. }
  5389. TEST_F(ServerTest, StaticFileRangeBigFile) {
  5390. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  5391. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5392. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5393. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5394. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  5395. EXPECT_EQ(true, res->has_header("Content-Range"));
  5396. EXPECT_EQ("bytes 1048571-1048575/1048576",
  5397. res->get_header_value("Content-Range"));
  5398. EXPECT_EQ("LAST\n", res->body);
  5399. }
  5400. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  5401. auto res =
  5402. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  5403. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5404. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5405. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5406. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  5407. EXPECT_EQ(true, res->has_header("Content-Range"));
  5408. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  5409. }
  5410. TEST_F(ServerTest, StaticFileBigFile) {
  5411. auto res = cli_.Get("/dir/1MB.txt");
  5412. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5413. EXPECT_EQ(StatusCode::OK_200, res->status);
  5414. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5415. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  5416. }
  5417. TEST_F(ServerTest, InvalidBaseDirMount) {
  5418. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  5419. }
  5420. TEST_F(ServerTest, Binary) {
  5421. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  5422. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  5423. "application/octet-stream");
  5424. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5425. ASSERT_EQ(StatusCode::OK_200, res->status);
  5426. ASSERT_EQ(4U, res->body.size());
  5427. res = cli_.Put("/binary", binary.data(), binary.size(),
  5428. "application/octet-stream");
  5429. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5430. ASSERT_EQ(StatusCode::OK_200, res->status);
  5431. ASSERT_EQ(4U, res->body.size());
  5432. res = cli_.Patch("/binary", binary.data(), binary.size(),
  5433. "application/octet-stream");
  5434. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5435. ASSERT_EQ(StatusCode::OK_200, res->status);
  5436. ASSERT_EQ(4U, res->body.size());
  5437. res = cli_.Delete("/binary", binary.data(), binary.size(),
  5438. "application/octet-stream");
  5439. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5440. ASSERT_EQ(StatusCode::OK_200, res->status);
  5441. ASSERT_EQ(4U, res->body.size());
  5442. }
  5443. TEST_F(ServerTest, BinaryString) {
  5444. auto binary = std::string("\x00\x01\x02\x03", 4);
  5445. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  5446. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5447. ASSERT_EQ(StatusCode::OK_200, res->status);
  5448. ASSERT_EQ(4U, res->body.size());
  5449. res = cli_.Put("/binary", binary, "application/octet-stream");
  5450. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5451. ASSERT_EQ(StatusCode::OK_200, res->status);
  5452. ASSERT_EQ(4U, res->body.size());
  5453. res = cli_.Patch("/binary", binary, "application/octet-stream");
  5454. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5455. ASSERT_EQ(StatusCode::OK_200, res->status);
  5456. ASSERT_EQ(4U, res->body.size());
  5457. res = cli_.Delete("/binary", binary, "application/octet-stream");
  5458. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5459. ASSERT_EQ(StatusCode::OK_200, res->status);
  5460. ASSERT_EQ(4U, res->body.size());
  5461. }
  5462. TEST_F(ServerTest, EmptyRequest) {
  5463. auto res = cli_.Get("");
  5464. ASSERT_TRUE(!res);
  5465. EXPECT_EQ(Error::Connection, res.error());
  5466. }
  5467. TEST_F(ServerTest, LongRequest) {
  5468. std::string request;
  5469. for (size_t i = 0; i < 545; i++) {
  5470. request += "/TooLongRequest";
  5471. }
  5472. request += "OK";
  5473. auto res = cli_.Get(request.c_str());
  5474. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5475. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5476. }
  5477. TEST_F(ServerTest, TooLongRequest) {
  5478. std::string request;
  5479. for (size_t i = 0; i < 546; i++) {
  5480. request += "/TooLongRequest";
  5481. }
  5482. request += "_NG";
  5483. auto start = std::chrono::high_resolution_clock::now();
  5484. cli_.set_keep_alive(true);
  5485. auto res = cli_.Get(request.c_str());
  5486. auto end = std::chrono::high_resolution_clock::now();
  5487. auto elapsed =
  5488. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5489. .count();
  5490. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5491. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5492. EXPECT_LE(elapsed, 1000);
  5493. EXPECT_EQ("close", res->get_header_value("Connection"));
  5494. EXPECT_FALSE(cli_.is_socket_open());
  5495. }
  5496. TEST_F(ServerTest, AlmostTooLongRequest) {
  5497. // test for #2046 - URI length check shouldn't include other content on req
  5498. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  5499. // leading /, space, HTTP/1.1)
  5500. std::string request =
  5501. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  5502. auto res = cli_.Get(request.c_str());
  5503. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5504. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5505. }
  5506. TEST_F(ServerTest, LongHeader) {
  5507. Request req;
  5508. req.method = "GET";
  5509. req.path = "/hi";
  5510. std::string host_and_port;
  5511. host_and_port += HOST;
  5512. host_and_port += ":";
  5513. host_and_port += std::to_string(PORT);
  5514. req.headers.emplace("Host", host_and_port.c_str());
  5515. req.headers.emplace("Accept", "*/*");
  5516. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5517. req.headers.emplace(
  5518. "Header-Name",
  5519. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5520. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5521. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5522. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5523. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5524. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5525. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5526. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5527. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5528. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5529. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5530. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5531. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5532. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5533. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5534. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5535. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5536. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5537. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5538. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5539. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5540. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5541. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5542. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5543. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5544. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5545. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5546. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5547. "@@@@@@@@@@@@@@@@");
  5548. auto res = std::make_shared<Response>();
  5549. auto error = Error::Success;
  5550. auto ret = cli_.send(req, *res, error);
  5551. ASSERT_TRUE(ret);
  5552. EXPECT_EQ(StatusCode::OK_200, res->status);
  5553. }
  5554. TEST_F(ServerTest, LongQueryValue) {
  5555. auto start = std::chrono::high_resolution_clock::now();
  5556. cli_.set_keep_alive(true);
  5557. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  5558. auto end = std::chrono::high_resolution_clock::now();
  5559. auto elapsed =
  5560. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5561. .count();
  5562. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5563. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5564. EXPECT_LE(elapsed, 1000);
  5565. EXPECT_EQ("close", res->get_header_value("Connection"));
  5566. EXPECT_FALSE(cli_.is_socket_open());
  5567. }
  5568. TEST_F(ServerTest, TooLongQueryValue) {
  5569. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  5570. ASSERT_FALSE(res);
  5571. EXPECT_EQ(Error::Read, res.error());
  5572. }
  5573. TEST_F(ServerTest, TooLongHeader) {
  5574. Request req;
  5575. req.method = "GET";
  5576. req.path = "/hi";
  5577. std::string host_and_port;
  5578. host_and_port += HOST;
  5579. host_and_port += ":";
  5580. host_and_port += std::to_string(PORT);
  5581. req.headers.emplace("Host", host_and_port.c_str());
  5582. req.headers.emplace("Accept", "*/*");
  5583. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5584. req.headers.emplace(
  5585. "Header-Name",
  5586. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5587. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5588. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5589. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5590. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5591. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5592. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5593. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5594. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5595. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5596. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5597. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5598. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5599. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5600. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5601. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5602. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5603. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5604. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5605. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5606. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5607. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5608. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5609. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5610. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5611. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5612. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5613. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5614. "@@@@@@@@@@@@@@@@@");
  5615. auto res = std::make_shared<Response>();
  5616. auto error = Error::Success;
  5617. auto ret = cli_.send(req, *res, error);
  5618. ASSERT_TRUE(ret);
  5619. EXPECT_EQ(StatusCode::OK_200, res->status);
  5620. }
  5621. TEST_F(ServerTest, HeaderCountAtLimit) {
  5622. // Test with headers just under the 100 limit
  5623. httplib::Headers headers;
  5624. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  5625. // This should keep us just under the 100 header limit
  5626. for (int i = 0; i < 95; i++) {
  5627. std::string name = "X-Test-Header-" + std::to_string(i);
  5628. std::string value = "value" + std::to_string(i);
  5629. headers.emplace(name, value);
  5630. }
  5631. // This should work fine as we're under the limit
  5632. auto res = cli_.Get("/hi", headers);
  5633. EXPECT_TRUE(res);
  5634. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  5635. }
  5636. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  5637. // Test with many headers to exceed the 100 limit
  5638. httplib::Headers headers;
  5639. // Add 150 headers to definitely exceed the 100 limit
  5640. for (int i = 0; i < 150; i++) {
  5641. std::string name = "X-Test-Header-" + std::to_string(i);
  5642. std::string value = "value" + std::to_string(i);
  5643. headers.emplace(name, value);
  5644. }
  5645. // This should fail due to exceeding header count limit
  5646. cli_.set_keep_alive(true);
  5647. auto res = cli_.Get("/hi", headers);
  5648. // The server should respond with 400 Bad Request
  5649. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5650. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5651. EXPECT_EQ("close", res->get_header_value("Connection"));
  5652. EXPECT_FALSE(cli_.is_socket_open());
  5653. }
  5654. TEST_F(ServerTest, PercentEncoding) {
  5655. auto res = cli_.Get("/e%6edwith%");
  5656. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5657. EXPECT_EQ(StatusCode::OK_200, res->status);
  5658. }
  5659. TEST_F(ServerTest, PercentEncodingUnicode) {
  5660. auto res = cli_.Get("/e%u006edwith%");
  5661. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5662. EXPECT_EQ(StatusCode::OK_200, res->status);
  5663. }
  5664. TEST_F(ServerTest, InvalidPercentEncoding) {
  5665. auto res = cli_.Get("/%endwith%");
  5666. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5667. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5668. }
  5669. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  5670. auto res = cli_.Get("/%uendwith%");
  5671. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5672. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5673. }
  5674. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  5675. auto res = cli_.Get("/hello?aaa=bbb%");
  5676. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5677. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5678. }
  5679. TEST_F(ServerTest, PlusSignEncoding) {
  5680. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  5681. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5682. EXPECT_EQ(StatusCode::OK_200, res->status);
  5683. EXPECT_EQ("a +b", res->body);
  5684. }
  5685. TEST_F(ServerTest, HeaderCountSecurityTest) {
  5686. // This test simulates a potential DoS attack using many headers
  5687. // to verify our security fix prevents memory exhaustion
  5688. httplib::Headers attack_headers;
  5689. // Attempt to add many headers like an attacker would (200 headers to far
  5690. // exceed limit)
  5691. for (int i = 0; i < 200; i++) {
  5692. std::string name = "X-Attack-Header-" + std::to_string(i);
  5693. std::string value = "attack_payload_" + std::to_string(i);
  5694. attack_headers.emplace(name, value);
  5695. }
  5696. // Try to POST with excessive headers
  5697. cli_.set_keep_alive(true);
  5698. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  5699. // Should either fail or return 400 Bad Request due to security limit
  5700. if (res) {
  5701. // If we get a response, it should be 400 Bad Request
  5702. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5703. EXPECT_EQ("close", res->get_header_value("Connection"));
  5704. }
  5705. EXPECT_FALSE(cli_.is_socket_open());
  5706. }
  5707. TEST_F(ServerTest, MultipartFormData) {
  5708. UploadFormDataItems items = {
  5709. {"text1", "text default", "", ""},
  5710. {"text2", "aωb", "", ""},
  5711. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5712. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  5713. {"file3", "", "", "application/octet-stream"},
  5714. {"file4", "", "", " application/json tmp-string "}};
  5715. auto res = cli_.Post("/multipart", items);
  5716. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5717. EXPECT_EQ(StatusCode::OK_200, res->status);
  5718. }
  5719. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  5720. UploadFormDataItems items = {
  5721. {"text", "default text", "", ""},
  5722. {"multi_text1", "aaaaa", "", ""},
  5723. {"multi_text1", "bbbbb", "", ""},
  5724. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5725. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  5726. "application/json"},
  5727. };
  5728. auto res = cli_.Post("/multipart/multi_file_values", items);
  5729. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5730. EXPECT_EQ(StatusCode::OK_200, res->status);
  5731. }
  5732. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  5733. auto res = cli_.Get("/hi");
  5734. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5735. EXPECT_EQ(StatusCode::OK_200, res->status);
  5736. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  5737. EXPECT_EQ("Hello World!", res->body);
  5738. }
  5739. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  5740. Request req;
  5741. req.method = "POST";
  5742. req.path = "/chunked";
  5743. std::string host_and_port;
  5744. host_and_port += HOST;
  5745. host_and_port += ":";
  5746. host_and_port += std::to_string(PORT);
  5747. req.headers.emplace("Host", host_and_port.c_str());
  5748. req.headers.emplace("Accept", "*/*");
  5749. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5750. req.headers.emplace("Content-Type", "text/plain");
  5751. req.headers.emplace("Content-Length", "0");
  5752. req.headers.emplace(
  5753. "Transfer-Encoding",
  5754. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  5755. // Client does not chunk, so make a chunked body manually.
  5756. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  5757. auto res = std::make_shared<Response>();
  5758. auto error = Error::Success;
  5759. auto ret = cli_.send(req, *res, error);
  5760. ASSERT_TRUE(ret);
  5761. EXPECT_EQ(StatusCode::OK_200, res->status);
  5762. }
  5763. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  5764. // rather than treat them as valid lengths.
  5765. template <typename ClientT>
  5766. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  5767. Request req;
  5768. req.method = "POST";
  5769. req.path = "/chunked";
  5770. std::string host_and_port;
  5771. host_and_port += HOST;
  5772. host_and_port += ":";
  5773. host_and_port += std::to_string(PORT);
  5774. req.headers.emplace("Host", host_and_port.c_str());
  5775. req.headers.emplace("Content-Length", "0");
  5776. req.headers.emplace("Transfer-Encoding", "chunked");
  5777. req.body = body;
  5778. auto res = std::make_shared<Response>();
  5779. auto error = Error::Success;
  5780. ASSERT_TRUE(cli.send(req, *res, error));
  5781. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5782. }
  5783. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  5784. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  5785. }
  5786. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  5787. expect_chunked_body_rejected(
  5788. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  5789. }
  5790. TEST_F(ServerTest, GetStreamed2) {
  5791. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  5792. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5793. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5794. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5795. EXPECT_EQ(true, res->has_header("Content-Range"));
  5796. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  5797. EXPECT_EQ(std::string("ab"), res->body);
  5798. }
  5799. TEST_F(ServerTest, GetStreamed) {
  5800. auto res = cli_.Get("/streamed");
  5801. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5802. EXPECT_EQ(StatusCode::OK_200, res->status);
  5803. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5804. EXPECT_EQ(std::string("aaabbb"), res->body);
  5805. }
  5806. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  5807. auto res = cli_.Get("/streamed-without-length",
  5808. Headers{make_range_header({{0, -1}})});
  5809. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5810. EXPECT_EQ(StatusCode::OK_200, res->status);
  5811. EXPECT_EQ(false, res->has_header("Content-Length"));
  5812. EXPECT_EQ(false, res->has_header("Content-Range"));
  5813. EXPECT_EQ(std::string("abcdefg"), res->body);
  5814. }
  5815. TEST_F(ServerTest, GetStreamedWithRange1) {
  5816. auto res =
  5817. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  5818. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5819. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5820. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5821. EXPECT_EQ(true, res->has_header("Content-Range"));
  5822. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  5823. EXPECT_EQ(std::string("def"), res->body);
  5824. }
  5825. TEST_F(ServerTest, GetStreamedWithRange2) {
  5826. auto res =
  5827. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  5828. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5829. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5830. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5831. EXPECT_EQ(true, res->has_header("Content-Range"));
  5832. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  5833. EXPECT_EQ(std::string("bcdefg"), res->body);
  5834. }
  5835. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  5836. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  5837. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5838. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5839. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5840. EXPECT_EQ(true, res->has_header("Content-Range"));
  5841. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  5842. EXPECT_EQ(std::string("efg"), res->body);
  5843. }
  5844. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  5845. auto res =
  5846. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-9999"}});
  5847. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5848. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5849. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5850. EXPECT_EQ(false, res->has_header("Content-Range"));
  5851. EXPECT_EQ(0U, res->body.size());
  5852. }
  5853. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  5854. // Only a 206 is served as a partial representation. Under any other status
  5855. // `apply_ranges()` reported the full content length, so the body must match
  5856. // that header, and the content provider must never be asked for an offset
  5857. // outside the representation.
  5858. auto check = [&](int status, const char *range) {
  5859. auto path =
  5860. std::string("/streamed-with-range?status=") + std::to_string(status);
  5861. auto ctx = path + " Range: " + range;
  5862. auto res = cli_.Get(path, Headers{{"Range", range}});
  5863. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  5864. EXPECT_EQ(status, res->status) << ctx;
  5865. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  5866. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  5867. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  5868. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  5869. };
  5870. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  5871. check(403, "bytes=3-5");
  5872. // The offset is far past the representation.
  5873. check(403, "bytes=100000-100200");
  5874. // `first_pos` is still -1 here, and the bounds asserts in
  5875. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  5876. check(403, "bytes=-3");
  5877. // `apply_ranges()` makes no boundary for a non-206 response, so the
  5878. // multipart branch would have written one that is empty.
  5879. check(403, "bytes=1-2, 4-5");
  5880. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  5881. // covers the whole representation.
  5882. check(200, "bytes=3-5");
  5883. check(200, "bytes=1-2, 4-5");
  5884. }
  5885. TEST_F(ServerTest, GetStreamedWithRangeError) {
  5886. auto res =
  5887. cli_.Get("/streamed-with-range",
  5888. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  5889. "92233720368547758079223372036854775807"}});
  5890. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5891. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5892. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5893. EXPECT_EQ(false, res->has_header("Content-Range"));
  5894. EXPECT_EQ(0U, res->body.size());
  5895. }
  5896. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  5897. auto res = cli_.Get(
  5898. "/with-range",
  5899. Headers{{"Range",
  5900. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  5901. {"Accept-Encoding", ""}});
  5902. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5903. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5904. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  5905. EXPECT_EQ(true, res->has_header("Content-Range"));
  5906. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  5907. EXPECT_EQ(std::string("abcdefg"), res->body);
  5908. }
  5909. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  5910. auto res = cli_.Get("/with-range", Headers{
  5911. {"Range", "bytes=0-"},
  5912. {"Accept-Encoding", ""},
  5913. });
  5914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5915. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5916. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  5917. EXPECT_EQ(true, res->has_header("Content-Range"));
  5918. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  5919. EXPECT_EQ(std::string("abcdefg"), res->body);
  5920. }
  5921. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  5922. auto res = cli_.Get("/streamed-with-range",
  5923. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5924. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5925. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5926. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  5927. EXPECT_EQ(false, res->has_header("Content-Range"));
  5928. EXPECT_EQ(267U, res->body.size());
  5929. // Check that both range contents are present
  5930. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  5931. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  5932. // Check that Content-Range headers are present for both ranges
  5933. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  5934. std::string::npos);
  5935. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  5936. std::string::npos);
  5937. }
  5938. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  5939. Ranges ranges;
  5940. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  5941. ranges.emplace_back(0, -1);
  5942. }
  5943. auto res = cli_.Get("/streamed-with-range?error",
  5944. Headers{{make_range_header(ranges)}});
  5945. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5946. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5947. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5948. EXPECT_EQ(false, res->has_header("Content-Range"));
  5949. EXPECT_EQ(0U, res->body.size());
  5950. }
  5951. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  5952. auto res = cli_.Get("/streamed-with-range",
  5953. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  5954. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5955. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5956. EXPECT_EQ(5U, res->body.size());
  5957. // Check that overlapping ranges are coalesced into a single range
  5958. EXPECT_EQ("bcdef", res->body);
  5959. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  5960. // Should be single range, not multipart
  5961. EXPECT_TRUE(res->has_header("Content-Range"));
  5962. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5963. }
  5964. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  5965. auto res = cli_.Get("/streamed-with-range",
  5966. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  5967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5968. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5969. EXPECT_EQ(268U, res->body.size());
  5970. // Check that both range contents are present
  5971. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  5972. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  5973. // Check that Content-Range headers are present for both ranges
  5974. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  5975. std::string::npos);
  5976. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  5977. std::string::npos);
  5978. }
  5979. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  5980. auto res = cli_.Get("/streamed-with-range",
  5981. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  5982. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5983. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5984. EXPECT_EQ(269U, res->body.size());
  5985. // Check that both duplicate range contents are present
  5986. size_t first_abc = res->body.find("abc\r\n");
  5987. EXPECT_TRUE(first_abc != std::string::npos);
  5988. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  5989. EXPECT_TRUE(second_abc != std::string::npos);
  5990. // Check that Content-Range headers are present for both ranges
  5991. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  5992. EXPECT_TRUE(first_range != std::string::npos);
  5993. size_t second_range =
  5994. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  5995. EXPECT_TRUE(second_range != std::string::npos);
  5996. }
  5997. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  5998. auto res =
  5999. cli_.Get("/streamed-with-range?error",
  6000. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  6001. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6002. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6003. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6004. EXPECT_EQ(false, res->has_header("Content-Range"));
  6005. EXPECT_EQ(0U, res->body.size());
  6006. }
  6007. TEST_F(ServerTest, GetStreamedEndless) {
  6008. uint64_t offset = 0;
  6009. auto res = cli_.Get("/streamed-cancel",
  6010. [&](const char * /*data*/, uint64_t data_length) {
  6011. if (offset < 100) {
  6012. offset += data_length;
  6013. return true;
  6014. }
  6015. return false;
  6016. });
  6017. ASSERT_TRUE(!res);
  6018. EXPECT_EQ(Error::Canceled, res.error());
  6019. }
  6020. TEST_F(ServerTest, ClientStop) {
  6021. std::atomic_size_t count{4};
  6022. std::vector<std::thread> threads;
  6023. for (auto i = count.load(); i != 0; --i) {
  6024. threads.emplace_back([&]() {
  6025. auto res = cli_.Get("/streamed-cancel",
  6026. [&](const char *, uint64_t) { return true; });
  6027. --count;
  6028. ASSERT_TRUE(!res);
  6029. EXPECT_TRUE(res.error() == Error::Canceled ||
  6030. res.error() == Error::Read || res.error() == Error::Write);
  6031. });
  6032. }
  6033. std::this_thread::sleep_for(std::chrono::seconds(2));
  6034. while (count != 0) {
  6035. cli_.stop();
  6036. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  6037. }
  6038. for (auto &t : threads) {
  6039. t.join();
  6040. }
  6041. }
  6042. TEST_F(ServerTest, GetWithRange1) {
  6043. auto res = cli_.Get("/with-range", Headers{
  6044. make_range_header({{3, 5}}),
  6045. {"Accept-Encoding", ""},
  6046. });
  6047. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6048. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6049. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6050. EXPECT_EQ(true, res->has_header("Content-Range"));
  6051. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6052. EXPECT_EQ(std::string("def"), res->body);
  6053. }
  6054. TEST_F(ServerTest, GetWithRange2) {
  6055. auto res = cli_.Get("/with-range", Headers{
  6056. make_range_header({{1, -1}}),
  6057. {"Accept-Encoding", ""},
  6058. });
  6059. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6060. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6061. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6062. EXPECT_EQ(true, res->has_header("Content-Range"));
  6063. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6064. EXPECT_EQ(std::string("bcdefg"), res->body);
  6065. }
  6066. TEST_F(ServerTest, GetWithRange3) {
  6067. auto res = cli_.Get("/with-range", Headers{
  6068. make_range_header({{0, 0}}),
  6069. {"Accept-Encoding", ""},
  6070. });
  6071. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6072. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6073. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  6074. EXPECT_EQ(true, res->has_header("Content-Range"));
  6075. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  6076. EXPECT_EQ(std::string("a"), res->body);
  6077. }
  6078. TEST_F(ServerTest, GetWithRange4) {
  6079. auto res = cli_.Get("/with-range", Headers{
  6080. make_range_header({{-1, 2}}),
  6081. {"Accept-Encoding", ""},
  6082. });
  6083. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6084. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6085. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6086. EXPECT_EQ(true, res->has_header("Content-Range"));
  6087. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  6088. EXPECT_EQ(std::string("fg"), res->body);
  6089. }
  6090. TEST_F(ServerTest, GetWithRange5) {
  6091. auto res = cli_.Get("/with-range", Headers{
  6092. make_range_header({{0, 5}}),
  6093. {"Accept-Encoding", ""},
  6094. });
  6095. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6096. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6097. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6098. EXPECT_EQ(true, res->has_header("Content-Range"));
  6099. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  6100. EXPECT_EQ(std::string("abcdef"), res->body);
  6101. }
  6102. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  6103. auto res =
  6104. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  6105. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6106. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6107. }
  6108. TEST_F(ServerTest, GetWithRangeMultipart) {
  6109. auto res =
  6110. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6111. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6112. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6113. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6114. EXPECT_EQ(false, res->has_header("Content-Range"));
  6115. EXPECT_EQ(267U, res->body.size());
  6116. }
  6117. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  6118. auto res = cli_.Get("/with-range",
  6119. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  6120. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6121. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6122. }
  6123. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  6124. auto res = cli_.Get("/with-range-customized-response",
  6125. Headers{{make_range_header({{1, 2}})}});
  6126. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6127. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6128. EXPECT_EQ(true, res->has_header("Content-Length"));
  6129. EXPECT_EQ(false, res->has_header("Content-Range"));
  6130. EXPECT_EQ(JSON_DATA, res->body);
  6131. }
  6132. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  6133. auto res = cli_.Get("/with-range-customized-response",
  6134. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6135. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6136. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6137. EXPECT_EQ(true, res->has_header("Content-Length"));
  6138. EXPECT_EQ(false, res->has_header("Content-Range"));
  6139. EXPECT_EQ(JSON_DATA, res->body);
  6140. }
  6141. TEST_F(ServerTest, Issue1772) {
  6142. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  6143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6144. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  6145. }
  6146. TEST_F(ServerTest, Issue609) {
  6147. auto res = cli_.Delete("/issue609");
  6148. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6149. EXPECT_EQ(StatusCode::OK_200, res->status);
  6150. EXPECT_EQ(std::string("ok"), res->body);
  6151. }
  6152. TEST_F(ServerTest, GetStreamedChunked) {
  6153. auto res = cli_.Get("/streamed-chunked");
  6154. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6155. EXPECT_EQ(StatusCode::OK_200, res->status);
  6156. EXPECT_EQ(std::string("123456789"), res->body);
  6157. }
  6158. TEST_F(ServerTest, GetStreamedChunked2) {
  6159. auto res = cli_.Get("/streamed-chunked2");
  6160. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6161. EXPECT_EQ(StatusCode::OK_200, res->status);
  6162. EXPECT_EQ(std::string("123456789"), res->body);
  6163. }
  6164. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  6165. auto res = cli_.Get("/streamed-chunked-with-trailer");
  6166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6167. EXPECT_EQ(StatusCode::OK_200, res->status);
  6168. EXPECT_EQ(std::string("123456789"), res->body);
  6169. EXPECT_TRUE(res->has_header("Trailer"));
  6170. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  6171. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  6172. // Trailers are now stored separately from headers (security fix)
  6173. EXPECT_EQ(2U, res->trailers.size());
  6174. EXPECT_TRUE(res->has_trailer("Dummy1"));
  6175. EXPECT_TRUE(res->has_trailer("Dummy2"));
  6176. EXPECT_FALSE(res->has_trailer("Dummy3"));
  6177. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  6178. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  6179. // Verify trailers are NOT in headers (security verification)
  6180. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  6181. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  6182. }
  6183. TEST_F(ServerTest, LargeChunkedPost) {
  6184. Request req;
  6185. req.method = "POST";
  6186. req.path = "/large-chunked";
  6187. std::string host_and_port;
  6188. host_and_port += HOST;
  6189. host_and_port += ":";
  6190. host_and_port += std::to_string(PORT);
  6191. req.headers.emplace("Host", host_and_port.c_str());
  6192. req.headers.emplace("Accept", "*/*");
  6193. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6194. req.headers.emplace("Content-Type", "text/plain");
  6195. req.headers.emplace("Content-Length", "0");
  6196. req.headers.emplace("Transfer-Encoding", "chunked");
  6197. std::string long_string(30 * 1024u, 'a');
  6198. std::string chunk = "7800\r\n" + long_string + "\r\n";
  6199. // Attempt to make a large enough post to exceed OS buffers, to test that
  6200. // the server handles short reads if the full chunk data isn't available.
  6201. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  6202. auto res = std::make_shared<Response>();
  6203. auto error = Error::Success;
  6204. auto ret = cli_.send(req, *res, error);
  6205. ASSERT_TRUE(ret);
  6206. EXPECT_EQ(StatusCode::OK_200, res->status);
  6207. }
  6208. TEST_F(ServerTest, GetMethodRemoteAddr) {
  6209. auto res = cli_.Get("/remote_addr");
  6210. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6211. EXPECT_EQ(StatusCode::OK_200, res->status);
  6212. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6213. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  6214. }
  6215. TEST_F(ServerTest, GetMethodLocalAddr) {
  6216. auto res = cli_.Get("/local_addr");
  6217. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6218. EXPECT_EQ(StatusCode::OK_200, res->status);
  6219. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6220. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  6221. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  6222. }
  6223. TEST_F(ServerTest, HTTPResponseSplitting) {
  6224. auto res = cli_.Get("/http_response_splitting");
  6225. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6226. EXPECT_EQ(StatusCode::OK_200, res->status);
  6227. }
  6228. TEST_F(ServerTest, SlowRequest) {
  6229. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6230. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6231. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6232. }
  6233. #if 0
  6234. TEST_F(ServerTest, SlowPost) {
  6235. char buffer[64 * 1024];
  6236. memset(buffer, 0x42, sizeof(buffer));
  6237. auto res = cli_.Post(
  6238. "/slowpost", 64 * 1024 * 1024,
  6239. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6240. auto ret = sink.write(buffer, sizeof(buffer));
  6241. EXPECT_TRUE(ret);
  6242. return true;
  6243. },
  6244. "text/plain");
  6245. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6246. EXPECT_EQ(StatusCode::OK_200, res->status);
  6247. }
  6248. TEST_F(ServerTest, SlowPostFail) {
  6249. char buffer[64 * 1024];
  6250. memset(buffer, 0x42, sizeof(buffer));
  6251. cli_.set_write_timeout(std::chrono::seconds(0));
  6252. auto res = cli_.Post(
  6253. "/slowpost", 64 * 1024 * 1024,
  6254. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6255. sink.write(buffer, sizeof(buffer));
  6256. return true;
  6257. },
  6258. "text/plain");
  6259. ASSERT_TRUE(!res);
  6260. EXPECT_EQ(Error::Write, res.error());
  6261. }
  6262. #endif
  6263. TEST_F(ServerTest, Put) {
  6264. auto res = cli_.Put("/put", "PUT", "text/plain");
  6265. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6266. EXPECT_EQ(StatusCode::OK_200, res->status);
  6267. EXPECT_EQ("PUT", res->body);
  6268. }
  6269. TEST_F(ServerTest, PutWithContentProvider) {
  6270. auto res = cli_.Put(
  6271. "/put", 3,
  6272. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6273. sink.os << "PUT";
  6274. return true;
  6275. },
  6276. "text/plain");
  6277. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6278. EXPECT_EQ(StatusCode::OK_200, res->status);
  6279. EXPECT_EQ("PUT", res->body);
  6280. }
  6281. TEST_F(ServerTest, PostWithContentProviderAbort) {
  6282. auto res = cli_.Post(
  6283. "/post", 42,
  6284. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6285. return false;
  6286. },
  6287. "text/plain");
  6288. ASSERT_TRUE(!res);
  6289. EXPECT_EQ(Error::Canceled, res.error());
  6290. }
  6291. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  6292. auto res = cli_.Put(
  6293. "/put",
  6294. [](size_t /*offset*/, DataSink &sink) {
  6295. sink.os << "PUT";
  6296. sink.done();
  6297. return true;
  6298. },
  6299. "text/plain");
  6300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6301. EXPECT_EQ(StatusCode::OK_200, res->status);
  6302. EXPECT_EQ("PUT", res->body);
  6303. }
  6304. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  6305. auto res = cli_.Post(
  6306. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6307. "text/plain");
  6308. ASSERT_TRUE(!res);
  6309. EXPECT_EQ(Error::Canceled, res.error());
  6310. }
  6311. TEST_F(ServerTest, PostLoopBack) {
  6312. std::string body;
  6313. auto res = cli_.Post(
  6314. "/post-loopback", 9,
  6315. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6316. EXPECT_EQ(9u, length);
  6317. sink.write("123", 3);
  6318. sink.write("456", 3);
  6319. sink.write("789", 3);
  6320. return true;
  6321. },
  6322. "text/plain",
  6323. [&body](const char *data, size_t data_length) {
  6324. body.append(data, data_length);
  6325. return true;
  6326. });
  6327. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6328. EXPECT_EQ(StatusCode::OK_200, res->status);
  6329. EXPECT_EQ("123456789", body);
  6330. }
  6331. TEST_F(ServerTest, PutLoopBack) {
  6332. std::string body;
  6333. auto res = cli_.Put(
  6334. "/put-loopback", 9,
  6335. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6336. EXPECT_EQ(9u, length);
  6337. sink.write("123", 3);
  6338. sink.write("456", 3);
  6339. sink.write("789", 3);
  6340. return true;
  6341. },
  6342. "text/plain",
  6343. [&body](const char *data, size_t data_length) {
  6344. body.append(data, data_length);
  6345. return true;
  6346. });
  6347. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6348. EXPECT_EQ(StatusCode::OK_200, res->status);
  6349. EXPECT_EQ("123456789", body);
  6350. }
  6351. TEST_F(ServerTest, PatchLoopBack) {
  6352. std::string body;
  6353. auto res = cli_.Patch(
  6354. "/patch-loopback", 9,
  6355. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6356. EXPECT_EQ(9u, length);
  6357. sink.write("123", 3);
  6358. sink.write("456", 3);
  6359. sink.write("789", 3);
  6360. return true;
  6361. },
  6362. "text/plain",
  6363. [&body](const char *data, size_t data_length) {
  6364. body.append(data, data_length);
  6365. return true;
  6366. });
  6367. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6368. EXPECT_EQ(StatusCode::OK_200, res->status);
  6369. EXPECT_EQ("123456789", body);
  6370. }
  6371. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  6372. std::string body;
  6373. auto res = cli_.Post(
  6374. "/post-loopback",
  6375. [](size_t /*offset*/, DataSink &sink) {
  6376. sink.write("123", 3);
  6377. sink.write("456", 3);
  6378. sink.write("789", 3);
  6379. sink.done();
  6380. return true;
  6381. },
  6382. "text/plain",
  6383. [&body](const char *data, size_t data_length) {
  6384. body.append(data, data_length);
  6385. return true;
  6386. });
  6387. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6388. EXPECT_EQ(StatusCode::OK_200, res->status);
  6389. EXPECT_EQ("123456789", body);
  6390. }
  6391. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6392. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  6393. cli_.set_compress(true);
  6394. auto res = cli_.Put(
  6395. "/put", 3,
  6396. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6397. sink.os << "PUT";
  6398. return true;
  6399. },
  6400. "text/plain");
  6401. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6402. EXPECT_EQ(StatusCode::OK_200, res->status);
  6403. EXPECT_EQ("PUT", res->body);
  6404. }
  6405. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  6406. cli_.set_compress(true);
  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, PutWithContentProviderWithoutLengthWithGzip) {
  6417. cli_.set_compress(true);
  6418. auto res = cli_.Put(
  6419. "/put",
  6420. [](size_t /*offset*/, DataSink &sink) {
  6421. sink.os << "PUT";
  6422. sink.done();
  6423. return true;
  6424. },
  6425. "text/plain");
  6426. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6427. EXPECT_EQ(StatusCode::OK_200, res->status);
  6428. EXPECT_EQ("PUT", res->body);
  6429. }
  6430. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  6431. cli_.set_compress(true);
  6432. auto res = cli_.Post(
  6433. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6434. "text/plain");
  6435. ASSERT_TRUE(!res);
  6436. EXPECT_EQ(Error::Canceled, res.error());
  6437. }
  6438. TEST_F(ServerTest, PutLargeFileWithGzip) {
  6439. cli_.set_compress(true);
  6440. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6441. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6442. EXPECT_EQ(StatusCode::OK_200, res->status);
  6443. EXPECT_EQ(LARGE_DATA, res->body);
  6444. }
  6445. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  6446. #ifdef CPPHTTPLIB_SSL_ENABLED
  6447. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  6448. Client cli(s.c_str());
  6449. cli.enable_server_certificate_verification(false);
  6450. #else
  6451. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  6452. Client cli(s.c_str());
  6453. #endif
  6454. cli.set_compress(true);
  6455. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  6456. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6457. EXPECT_EQ(StatusCode::OK_200, res->status);
  6458. EXPECT_EQ(LARGE_DATA, res->body);
  6459. // The compressed size should be less than a 10th of the original. May vary
  6460. // depending on the zlib library.
  6461. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  6462. static_cast<uint64_t>(10 * 1024 * 1024));
  6463. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6464. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6465. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  6466. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  6467. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  6468. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  6469. #endif
  6470. }
  6471. TEST_F(ServerTest, PutContentWithDeflate) {
  6472. cli_.set_compress(false);
  6473. Headers headers;
  6474. headers.emplace("Content-Encoding", "deflate");
  6475. // PUT in deflate format:
  6476. auto res = cli_.Put("/put", headers,
  6477. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  6478. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6479. EXPECT_EQ(StatusCode::OK_200, res->status);
  6480. EXPECT_EQ("PUT", res->body);
  6481. }
  6482. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  6483. Headers headers;
  6484. headers.emplace("Accept-Encoding", "gzip, deflate");
  6485. auto res = cli_.Get("/streamed-chunked", headers);
  6486. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6487. EXPECT_EQ(StatusCode::OK_200, res->status);
  6488. EXPECT_EQ(std::string("123456789"), res->body);
  6489. }
  6490. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  6491. Headers headers;
  6492. headers.emplace("Accept-Encoding", "gzip, deflate");
  6493. auto res = cli_.Get("/streamed-chunked2", headers);
  6494. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6495. EXPECT_EQ(StatusCode::OK_200, res->status);
  6496. EXPECT_EQ(std::string("123456789"), res->body);
  6497. }
  6498. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  6499. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  6500. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6501. EXPECT_EQ(StatusCode::OK_200, res->status);
  6502. }
  6503. TEST(GzipDecompressor, ChunkedDecompression) {
  6504. std::string data;
  6505. for (size_t i = 0; i < 32 * 1024; ++i) {
  6506. data.push_back(static_cast<char>('a' + i % 26));
  6507. }
  6508. std::string compressed_data;
  6509. {
  6510. httplib::detail::gzip_compressor compressor;
  6511. bool result = compressor.compress(
  6512. data.data(), data.size(),
  6513. /*last=*/true,
  6514. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  6515. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  6516. compressed_data_size);
  6517. return true;
  6518. });
  6519. ASSERT_TRUE(result);
  6520. }
  6521. std::string decompressed_data;
  6522. {
  6523. httplib::detail::gzip_decompressor decompressor;
  6524. // Chunk size is chosen specifically to have a decompressed chunk size equal
  6525. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  6526. size_t chunk_size = 130;
  6527. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  6528. chunk_begin += chunk_size) {
  6529. size_t current_chunk_size =
  6530. std::min(compressed_data.size() - chunk_begin, chunk_size);
  6531. bool result = decompressor.decompress(
  6532. compressed_data.data() + chunk_begin, current_chunk_size,
  6533. [&](const char *decompressed_data_chunk,
  6534. size_t decompressed_data_chunk_size) {
  6535. decompressed_data.insert(decompressed_data.size(),
  6536. decompressed_data_chunk,
  6537. decompressed_data_chunk_size);
  6538. return true;
  6539. });
  6540. ASSERT_TRUE(result);
  6541. }
  6542. }
  6543. ASSERT_EQ(data, decompressed_data);
  6544. }
  6545. TEST(GzipDecompressor, DeflateDecompression) {
  6546. std::string original_text = "Raw deflate without gzip";
  6547. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6548. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6549. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6550. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  6551. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6552. std::string decompressed_data;
  6553. {
  6554. httplib::detail::gzip_decompressor decompressor;
  6555. bool result = decompressor.decompress(
  6556. compressed_data.data(), compressed_data.size(),
  6557. [&](const char *decompressed_data_chunk,
  6558. size_t decompressed_data_chunk_size) {
  6559. decompressed_data.insert(decompressed_data.size(),
  6560. decompressed_data_chunk,
  6561. decompressed_data_chunk_size);
  6562. return true;
  6563. });
  6564. ASSERT_TRUE(result);
  6565. }
  6566. ASSERT_EQ(original_text, decompressed_data);
  6567. }
  6568. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  6569. std::string original_text = "Raw deflate without gzip";
  6570. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6571. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6572. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6573. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  6574. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  6575. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6576. std::string decompressed_data;
  6577. {
  6578. httplib::detail::gzip_decompressor decompressor;
  6579. bool result = decompressor.decompress(
  6580. compressed_data.data(), compressed_data.size(),
  6581. [&](const char *decompressed_data_chunk,
  6582. size_t decompressed_data_chunk_size) {
  6583. decompressed_data.insert(decompressed_data.size(),
  6584. decompressed_data_chunk,
  6585. decompressed_data_chunk_size);
  6586. return true;
  6587. });
  6588. ASSERT_TRUE(result);
  6589. }
  6590. ASSERT_EQ(original_text, decompressed_data);
  6591. }
  6592. #endif
  6593. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6594. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  6595. Headers headers;
  6596. headers.emplace("Accept-Encoding", "br");
  6597. auto res = cli_.Get("/streamed-chunked", headers);
  6598. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6599. EXPECT_EQ(StatusCode::OK_200, res->status);
  6600. EXPECT_EQ(std::string("123456789"), res->body);
  6601. }
  6602. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  6603. Headers headers;
  6604. headers.emplace("Accept-Encoding", "br");
  6605. auto res = cli_.Get("/streamed-chunked2", headers);
  6606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6607. EXPECT_EQ(StatusCode::OK_200, res->status);
  6608. EXPECT_EQ(std::string("123456789"), res->body);
  6609. }
  6610. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  6611. cli_.set_compress(true);
  6612. auto res = cli_.Put(
  6613. "/put", 3,
  6614. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6615. sink.os << "PUT";
  6616. return true;
  6617. },
  6618. "text/plain");
  6619. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6620. EXPECT_EQ(StatusCode::OK_200, res->status);
  6621. EXPECT_EQ("PUT", res->body);
  6622. }
  6623. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  6624. cli_.set_compress(true);
  6625. auto res = cli_.Put(
  6626. "/put",
  6627. [](size_t /*offset*/, DataSink &sink) {
  6628. sink.os << "PUT";
  6629. sink.done();
  6630. return true;
  6631. },
  6632. "text/plain");
  6633. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6634. EXPECT_EQ(StatusCode::OK_200, res->status);
  6635. EXPECT_EQ("PUT", res->body);
  6636. }
  6637. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  6638. cli_.set_compress(true);
  6639. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6640. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6641. EXPECT_EQ(StatusCode::OK_200, res->status);
  6642. EXPECT_EQ(LARGE_DATA, res->body);
  6643. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6644. }
  6645. #endif
  6646. TEST_F(ServerTest, Patch) {
  6647. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  6648. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6649. EXPECT_EQ(StatusCode::OK_200, res->status);
  6650. EXPECT_EQ("PATCH", res->body);
  6651. }
  6652. TEST_F(ServerTest, Delete) {
  6653. auto res = cli_.Delete("/delete");
  6654. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6655. EXPECT_EQ(StatusCode::OK_200, res->status);
  6656. EXPECT_EQ("DELETE", res->body);
  6657. }
  6658. TEST_F(ServerTest, DeleteContentReceiver) {
  6659. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  6660. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6661. EXPECT_EQ(StatusCode::OK_200, res->status);
  6662. EXPECT_EQ("content", res->body);
  6663. }
  6664. TEST_F(ServerTest, Options) {
  6665. auto res = cli_.Options("*");
  6666. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6667. EXPECT_EQ(StatusCode::OK_200, res->status);
  6668. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  6669. EXPECT_TRUE(res->body.empty());
  6670. }
  6671. TEST_F(ServerTest, URL) {
  6672. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  6673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6674. EXPECT_EQ(StatusCode::OK_200, res->status);
  6675. }
  6676. TEST_F(ServerTest, ArrayParam) {
  6677. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  6678. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6679. EXPECT_EQ(StatusCode::OK_200, res->status);
  6680. }
  6681. TEST_F(ServerTest, ArrayParamValues) {
  6682. auto res =
  6683. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  6684. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6685. EXPECT_EQ(StatusCode::OK_200, res->status);
  6686. }
  6687. TEST_F(ServerTest, NoMultipleHeaders) {
  6688. Headers headers = {{"Content-Length", "5"}};
  6689. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  6690. "text/plain");
  6691. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6692. EXPECT_EQ(StatusCode::OK_200, res->status);
  6693. }
  6694. TEST_F(ServerTest, PostContentReceiver) {
  6695. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  6696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6697. ASSERT_EQ(StatusCode::OK_200, res->status);
  6698. ASSERT_EQ("content", res->body);
  6699. }
  6700. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  6701. UploadFormDataItems items = {
  6702. {"text1", "text default", "", ""},
  6703. {"text2", "aωb", "", ""},
  6704. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6705. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  6706. {"file3", "", "", "application/octet-stream"},
  6707. };
  6708. auto res = cli_.Post("/content_receiver", items);
  6709. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6710. EXPECT_EQ(StatusCode::OK_200, res->status);
  6711. }
  6712. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  6713. UploadFormDataItems items = {
  6714. {"text1", "text default", "", ""},
  6715. {"text2", "aωb", "", ""},
  6716. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6717. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  6718. {"file3", "", "", "application/octet-stream"},
  6719. };
  6720. auto boundary = std::string("+++++");
  6721. std::string body;
  6722. for (const auto &item : items) {
  6723. body += "--" + boundary + "\r\n";
  6724. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  6725. if (!item.filename.empty()) {
  6726. body += "; filename=\"" + item.filename + "\"";
  6727. }
  6728. body += "\r\n";
  6729. if (!item.content_type.empty()) {
  6730. body += "Content-Type: " + item.content_type + "\r\n";
  6731. }
  6732. body += "\r\n";
  6733. body += item.content + "\r\n";
  6734. }
  6735. body += "--" + boundary + "--\r\n";
  6736. std::string content_type = "multipart/form-data; boundary=" + boundary;
  6737. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  6738. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6739. EXPECT_EQ(StatusCode::OK_200, res->status);
  6740. }
  6741. TEST(MultipartFormDataTest, FieldEscaping) {
  6742. Server svr;
  6743. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  6744. const ContentReader &content_reader) {
  6745. ASSERT_TRUE(req.is_multipart_form_data());
  6746. std::vector<FormData> received;
  6747. content_reader(
  6748. [&](const FormData &file) {
  6749. received.push_back(file);
  6750. return true;
  6751. },
  6752. [&](const char *data, size_t data_length) {
  6753. received.back().content.append(data, data_length);
  6754. return true;
  6755. });
  6756. // '"', CR and LF in names and filenames are escaped following the
  6757. // WHATWG HTML standard, so each part still parses as a single part
  6758. // with no injected headers. Content types get CR/LF escaped too,
  6759. // while '"' (legal there, e.g. quoted charset) is preserved.
  6760. ASSERT_EQ(4U, received.size());
  6761. EXPECT_EQ("na%22me", received[0].name);
  6762. EXPECT_EQ("quoted name", received[0].content);
  6763. EXPECT_EQ("file", received[1].name);
  6764. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  6765. received[1].filename);
  6766. EXPECT_EQ("application/octet-stream", received[1].content_type);
  6767. EXPECT_EQ("injected", received[1].content);
  6768. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  6769. EXPECT_EQ("my%22file.txt", received[2].filename);
  6770. EXPECT_EQ("cr lf name", received[2].content);
  6771. EXPECT_EQ("typed", received[3].name);
  6772. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  6773. received[3].content_type);
  6774. EXPECT_EQ("typed content", received[3].content);
  6775. });
  6776. auto port = svr.bind_to_any_port("localhost");
  6777. auto t = std::thread([&]() { svr.listen_after_bind(); });
  6778. auto se = detail::scope_exit([&] {
  6779. svr.stop();
  6780. t.join();
  6781. ASSERT_FALSE(svr.is_running());
  6782. });
  6783. svr.wait_until_ready();
  6784. Client cli("localhost", port);
  6785. UploadFormDataItems items = {
  6786. {"na\"me", "quoted name", "", ""},
  6787. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  6788. "application/octet-stream"},
  6789. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  6790. {"typed", "typed content", "",
  6791. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  6792. };
  6793. auto res = cli.Post("/post", items);
  6794. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6795. EXPECT_EQ(StatusCode::OK_200, res->status);
  6796. }
  6797. TEST(MultipartFormDataTest, PublicWriterAPI) {
  6798. const UploadFormDataItems items = {
  6799. {"name1", "Content 1", "", ""},
  6800. {"name2", "Content 2", "file2.txt", "text/plain"},
  6801. };
  6802. Server svr;
  6803. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  6804. const ContentReader &content_reader) {
  6805. ASSERT_TRUE(req.is_multipart_form_data());
  6806. std::vector<FormData> received;
  6807. content_reader(
  6808. [&](const FormData &file) {
  6809. received.push_back(file);
  6810. return true;
  6811. },
  6812. [&](const char *data, size_t data_length) {
  6813. received.back().content.append(data, data_length);
  6814. return true;
  6815. });
  6816. ASSERT_EQ(2U, received.size());
  6817. EXPECT_EQ("name1", received[0].name);
  6818. EXPECT_EQ("Content 1", received[0].content);
  6819. EXPECT_EQ("name2", received[1].name);
  6820. EXPECT_EQ("Content 2", received[1].content);
  6821. EXPECT_EQ("file2.txt", received[1].filename);
  6822. EXPECT_EQ("text/plain", received[1].content_type);
  6823. });
  6824. auto port = svr.bind_to_any_port("localhost");
  6825. auto t = std::thread([&]() { svr.listen_after_bind(); });
  6826. auto se = detail::scope_exit([&] {
  6827. svr.stop();
  6828. t.join();
  6829. ASSERT_FALSE(svr.is_running());
  6830. });
  6831. svr.wait_until_ready();
  6832. Client cli("localhost", port);
  6833. // Whole-body serialization with a generated boundary
  6834. {
  6835. MultipartFormDataWriter writer;
  6836. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  6837. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  6838. writer.content_type());
  6839. auto body = writer.serialize(items);
  6840. EXPECT_EQ(body.size(), writer.content_length(items));
  6841. auto res = cli.Post("/post", body, writer.content_type());
  6842. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6843. EXPECT_EQ(StatusCode::OK_200, res->status);
  6844. }
  6845. // Per-part framing with a custom boundary via a content provider
  6846. {
  6847. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  6848. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  6849. MultipartFormDataWriter writer("custom-boundary_123");
  6850. EXPECT_EQ("custom-boundary_123", writer.boundary());
  6851. std::string body;
  6852. for (const auto &item : items) {
  6853. body += writer.item_begin(item);
  6854. body += item.content;
  6855. body += MultipartFormDataWriter::item_end();
  6856. }
  6857. body += writer.finish();
  6858. EXPECT_EQ(body.size(), writer.content_length(items));
  6859. auto res = cli.Post(
  6860. "/post", body.size(),
  6861. [&](size_t offset, size_t length, DataSink &sink) {
  6862. sink.write(body.data() + offset, length);
  6863. return true;
  6864. },
  6865. writer.content_type());
  6866. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6867. EXPECT_EQ(StatusCode::OK_200, res->status);
  6868. }
  6869. }
  6870. TEST_F(ServerTest, PostContentReceiverGzip) {
  6871. cli_.set_compress(true);
  6872. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  6873. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6874. ASSERT_EQ(StatusCode::OK_200, res->status);
  6875. ASSERT_EQ("content", res->body);
  6876. }
  6877. TEST_F(ServerTest, PutContentReceiver) {
  6878. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  6879. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6880. ASSERT_EQ(StatusCode::OK_200, res->status);
  6881. ASSERT_EQ("content", res->body);
  6882. }
  6883. TEST_F(ServerTest, PatchContentReceiver) {
  6884. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  6885. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6886. ASSERT_EQ(StatusCode::OK_200, res->status);
  6887. ASSERT_EQ("content", res->body);
  6888. }
  6889. template <typename ClientType>
  6890. void TestWithHeadersAndContentReceiver(
  6891. ClientType &cli,
  6892. std::function<Result(ClientType &, const std::string &, const Headers &,
  6893. const std::string &, const std::string &,
  6894. ContentReceiver, DownloadProgress)>
  6895. request_func) {
  6896. Headers headers;
  6897. headers.emplace("X-Custom-Header", "test-value");
  6898. std::string received_body;
  6899. auto res = request_func(
  6900. cli, "/content_receiver", headers, "content", "application/json",
  6901. [&](const char *data, size_t data_length) {
  6902. received_body.append(data, data_length);
  6903. return true;
  6904. },
  6905. nullptr);
  6906. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6907. EXPECT_EQ(StatusCode::OK_200, res->status);
  6908. EXPECT_EQ("content", received_body);
  6909. }
  6910. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  6911. #ifdef CPPHTTPLIB_SSL_ENABLED
  6912. using ClientT = SSLClient;
  6913. #else
  6914. using ClientT = Client;
  6915. #endif
  6916. TestWithHeadersAndContentReceiver<ClientT>(
  6917. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6918. const std::string &body, const std::string &content_type,
  6919. ContentReceiver receiver, DownloadProgress progress) {
  6920. return cli.Post(path, headers, body, content_type, receiver, progress);
  6921. });
  6922. }
  6923. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  6924. #ifdef CPPHTTPLIB_SSL_ENABLED
  6925. using ClientT = SSLClient;
  6926. #else
  6927. using ClientT = Client;
  6928. #endif
  6929. TestWithHeadersAndContentReceiver<ClientT>(
  6930. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6931. const std::string &body, const std::string &content_type,
  6932. ContentReceiver receiver, DownloadProgress progress) {
  6933. return cli.Put(path, headers, body, content_type, receiver, progress);
  6934. });
  6935. }
  6936. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  6937. #ifdef CPPHTTPLIB_SSL_ENABLED
  6938. using ClientT = SSLClient;
  6939. #else
  6940. using ClientT = Client;
  6941. #endif
  6942. TestWithHeadersAndContentReceiver<ClientT>(
  6943. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6944. const std::string &body, const std::string &content_type,
  6945. ContentReceiver receiver, DownloadProgress progress) {
  6946. return cli.Patch(path, headers, body, content_type, receiver, progress);
  6947. });
  6948. }
  6949. template <typename ClientType>
  6950. void TestWithHeadersAndContentReceiverWithProgress(
  6951. ClientType &cli,
  6952. std::function<Result(ClientType &, const std::string &, const Headers &,
  6953. const std::string &, const std::string &,
  6954. ContentReceiver, DownloadProgress)>
  6955. request_func) {
  6956. Headers headers;
  6957. headers.emplace("X-Test-Header", "progress-test");
  6958. std::string received_body;
  6959. auto progress_called = false;
  6960. auto res = request_func(
  6961. cli, "/content_receiver", headers, "content", "text/plain",
  6962. [&](const char *data, size_t data_length) {
  6963. received_body.append(data, data_length);
  6964. return true;
  6965. },
  6966. [&](uint64_t /*current*/, uint64_t /*total*/) {
  6967. progress_called = true;
  6968. return true;
  6969. });
  6970. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6971. EXPECT_EQ(StatusCode::OK_200, res->status);
  6972. EXPECT_EQ("content", received_body);
  6973. EXPECT_TRUE(progress_called);
  6974. }
  6975. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  6976. #ifdef CPPHTTPLIB_SSL_ENABLED
  6977. using ClientT = SSLClient;
  6978. #else
  6979. using ClientT = Client;
  6980. #endif
  6981. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  6982. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6983. const std::string &body, const std::string &content_type,
  6984. ContentReceiver receiver, DownloadProgress progress) {
  6985. return cli.Post(path, headers, body, content_type, receiver, progress);
  6986. });
  6987. }
  6988. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  6989. #ifdef CPPHTTPLIB_SSL_ENABLED
  6990. using ClientT = SSLClient;
  6991. #else
  6992. using ClientT = Client;
  6993. #endif
  6994. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  6995. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6996. const std::string &body, const std::string &content_type,
  6997. ContentReceiver receiver, DownloadProgress progress) {
  6998. return cli.Put(path, headers, body, content_type, receiver, progress);
  6999. });
  7000. }
  7001. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  7002. #ifdef CPPHTTPLIB_SSL_ENABLED
  7003. using ClientT = SSLClient;
  7004. #else
  7005. using ClientT = Client;
  7006. #endif
  7007. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7008. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7009. const std::string &body, const std::string &content_type,
  7010. ContentReceiver receiver, DownloadProgress progress) {
  7011. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7012. });
  7013. }
  7014. template <typename ClientType>
  7015. void TestWithHeadersAndContentReceiverError(
  7016. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  7017. const Headers &, const std::string &,
  7018. const std::string &, ContentReceiver)>
  7019. request_func) {
  7020. Headers headers;
  7021. headers.emplace("X-Error-Test", "true");
  7022. std::string received_body;
  7023. auto receiver_failed = false;
  7024. auto res =
  7025. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  7026. [&](const char *data, size_t data_length) {
  7027. received_body.append(data, data_length);
  7028. receiver_failed = true;
  7029. return false;
  7030. });
  7031. ASSERT_FALSE(res);
  7032. EXPECT_TRUE(receiver_failed);
  7033. }
  7034. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  7035. #ifdef CPPHTTPLIB_SSL_ENABLED
  7036. using ClientT = SSLClient;
  7037. #else
  7038. using ClientT = Client;
  7039. #endif
  7040. TestWithHeadersAndContentReceiverError<ClientT>(
  7041. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7042. const std::string &body, const std::string &content_type,
  7043. ContentReceiver receiver) {
  7044. return cli.Post(path, headers, body, content_type, receiver);
  7045. });
  7046. }
  7047. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  7048. #ifdef CPPHTTPLIB_SSL_ENABLED
  7049. using ClientT = SSLClient;
  7050. #else
  7051. using ClientT = Client;
  7052. #endif
  7053. TestWithHeadersAndContentReceiverError<ClientT>(
  7054. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7055. const std::string &body, const std::string &content_type,
  7056. ContentReceiver receiver) {
  7057. return cli.Put(path, headers, body, content_type, receiver);
  7058. });
  7059. }
  7060. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  7061. #ifdef CPPHTTPLIB_SSL_ENABLED
  7062. using ClientT = SSLClient;
  7063. #else
  7064. using ClientT = Client;
  7065. #endif
  7066. TestWithHeadersAndContentReceiverError<ClientT>(
  7067. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7068. const std::string &body, const std::string &content_type,
  7069. ContentReceiver receiver) {
  7070. return cli.Patch(path, headers, body, content_type, receiver);
  7071. });
  7072. }
  7073. TEST_F(ServerTest, PostQueryStringAndBody) {
  7074. auto res =
  7075. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  7076. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7077. ASSERT_EQ(StatusCode::OK_200, res->status);
  7078. }
  7079. TEST_F(ServerTest, HTTP2Magic) {
  7080. Request req;
  7081. req.method = "PRI";
  7082. req.path = "*";
  7083. req.body = "SM";
  7084. auto res = std::make_shared<Response>();
  7085. auto error = Error::Success;
  7086. auto ret = cli_.send(req, *res, error);
  7087. ASSERT_TRUE(ret);
  7088. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7089. }
  7090. TEST_F(ServerTest, KeepAlive) {
  7091. auto res = cli_.Get("/hi");
  7092. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7093. EXPECT_EQ(StatusCode::OK_200, res->status);
  7094. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7095. EXPECT_EQ("Hello World!", res->body);
  7096. res = cli_.Get("/hi");
  7097. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7098. EXPECT_EQ(StatusCode::OK_200, res->status);
  7099. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7100. EXPECT_EQ("Hello World!", res->body);
  7101. res = cli_.Get("/hi");
  7102. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7103. EXPECT_EQ(StatusCode::OK_200, res->status);
  7104. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7105. EXPECT_EQ("Hello World!", res->body);
  7106. res = cli_.Get("/not-exist");
  7107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7108. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7109. res = cli_.Post("/empty", "", "text/plain");
  7110. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7111. EXPECT_EQ(StatusCode::OK_200, res->status);
  7112. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7113. EXPECT_EQ("empty", res->body);
  7114. EXPECT_EQ("close", res->get_header_value("Connection"));
  7115. res = cli_.Post(
  7116. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  7117. "text/plain");
  7118. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7119. EXPECT_EQ(StatusCode::OK_200, res->status);
  7120. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7121. EXPECT_EQ("empty", res->body);
  7122. cli_.set_keep_alive(false);
  7123. res = cli_.Get("/last-request");
  7124. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7125. EXPECT_EQ(StatusCode::OK_200, res->status);
  7126. EXPECT_EQ("close", res->get_header_value("Connection"));
  7127. }
  7128. TEST_F(ServerTest, TooManyRedirect) {
  7129. cli_.set_follow_location(true);
  7130. auto res = cli_.Get("/redirect/0");
  7131. ASSERT_TRUE(!res);
  7132. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  7133. }
  7134. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  7135. Request req;
  7136. req.method = "FOOBAR";
  7137. req.path = "/hi";
  7138. cli_.set_keep_alive(true);
  7139. auto res = cli_.send(req);
  7140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7141. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7142. EXPECT_EQ("close", res->get_header_value("Connection"));
  7143. EXPECT_FALSE(cli_.is_socket_open());
  7144. }
  7145. TEST_F(ServerTest, CustomRouteReadsBody) {
  7146. const std::string xml =
  7147. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  7148. Request req;
  7149. req.method = "PROPFIND";
  7150. req.path = "/dav/dir";
  7151. req.set_header("Depth", "1");
  7152. req.body = xml;
  7153. auto res = cli_.send(req);
  7154. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7155. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7156. EXPECT_EQ(xml, res->body);
  7157. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  7158. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  7159. }
  7160. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  7161. Request req;
  7162. req.method = "PROPFIND";
  7163. req.path = "/dav/42";
  7164. auto res = cli_.send(req);
  7165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7166. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7167. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  7168. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  7169. }
  7170. TEST_F(ServerTest, CustomRouteRegexPattern) {
  7171. Request req;
  7172. req.method = "PROPFIND";
  7173. req.path = "/dav-re/123";
  7174. auto res = cli_.send(req);
  7175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7176. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7177. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  7178. }
  7179. TEST_F(ServerTest, CustomRouteWithoutBody) {
  7180. Request req;
  7181. req.method = "MKCOL";
  7182. req.path = "/dav-mkcol";
  7183. auto res = cli_.send(req);
  7184. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7185. EXPECT_EQ(StatusCode::Created_201, res->status);
  7186. }
  7187. TEST_F(ServerTest, CustomRouteWithContentReader) {
  7188. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  7189. Request req;
  7190. req.method = "REPORT";
  7191. req.path = "/dav-report";
  7192. req.body = xml;
  7193. auto res = cli_.send(req);
  7194. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7195. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7196. EXPECT_EQ(xml, res->body);
  7197. }
  7198. // A content reader route must fire even when the request carries no body,
  7199. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  7200. // Without that, a body-less PROPFIND-style request would fall through to 404.
  7201. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  7202. Request req;
  7203. req.method = "REPORT";
  7204. req.path = "/dav-report";
  7205. auto res = cli_.send(req);
  7206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7207. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7208. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  7209. }
  7210. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  7211. Request req;
  7212. req.method = "PROPFIND";
  7213. req.path = "/not-dav";
  7214. auto res = cli_.send(req);
  7215. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7216. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7217. }
  7218. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  7219. Request req;
  7220. req.method = "UNLOCK";
  7221. req.path = "/dav/dir";
  7222. cli_.set_keep_alive(true);
  7223. auto res = cli_.send(req);
  7224. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7225. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7226. EXPECT_EQ("close", res->get_header_value("Connection"));
  7227. EXPECT_FALSE(cli_.is_socket_open());
  7228. }
  7229. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  7230. // The mount point serves this path, but only for GET and HEAD.
  7231. auto get_res = cli_.Get("/dir/index.html");
  7232. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  7233. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  7234. Request req;
  7235. req.method = "PROPFIND";
  7236. req.path = "/dir/index.html";
  7237. auto res = cli_.send(req);
  7238. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7239. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7240. }
  7241. TEST_F(ServerTest, CustomRouteKeepAlive) {
  7242. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7243. cli_.set_keep_alive(true);
  7244. for (auto i = 0; i < 2; i++) {
  7245. Request req;
  7246. req.method = "PROPFIND";
  7247. req.path = "/dav/dir";
  7248. req.body = xml;
  7249. auto res = cli_.send(req);
  7250. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7251. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7252. EXPECT_EQ(xml, res->body);
  7253. EXPECT_TRUE(cli_.is_socket_open());
  7254. }
  7255. // A built-in method must still be served on the same connection.
  7256. cli_.set_keep_alive(false);
  7257. auto res = cli_.Get("/hi");
  7258. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7259. EXPECT_EQ(StatusCode::OK_200, res->status);
  7260. EXPECT_EQ("close", res->get_header_value("Connection"));
  7261. }
  7262. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  7263. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7264. Request req;
  7265. req.method = "PROPFIND";
  7266. req.path = "/dav/dir";
  7267. req.set_header("Expect", "100-continue");
  7268. req.body = xml;
  7269. auto res = cli_.send(req);
  7270. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7271. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7272. EXPECT_EQ(xml, res->body);
  7273. }
  7274. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  7275. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7276. TEST_F(ServerTest, Gzip) {
  7277. Headers headers;
  7278. headers.emplace("Accept-Encoding", "gzip, deflate");
  7279. auto res = cli_.Get("/compress", headers);
  7280. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7281. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7282. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7283. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7284. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7285. "7890123456789012345678901234567890",
  7286. res->body);
  7287. EXPECT_EQ(StatusCode::OK_200, res->status);
  7288. }
  7289. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  7290. Headers headers;
  7291. headers.emplace("Accept-Encoding", "gzip, deflate");
  7292. auto res = cli_.Get("/compress-with-charset", headers);
  7293. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7294. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7295. EXPECT_EQ("application/json; charset=utf-8",
  7296. res->get_header_value("Content-Type"));
  7297. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7298. "7890123456789012345678901234567890",
  7299. res->body);
  7300. EXPECT_EQ(StatusCode::OK_200, res->status);
  7301. }
  7302. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  7303. Headers headers;
  7304. headers.emplace("Accept-Encoding", "");
  7305. auto res = cli_.Get("/compress", headers);
  7306. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7307. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7308. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7309. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7310. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7311. "7890123456789012345678901234567890",
  7312. res->body);
  7313. EXPECT_EQ(StatusCode::OK_200, res->status);
  7314. }
  7315. TEST_F(ServerTest, GzipWithContentReceiver) {
  7316. Headers headers;
  7317. headers.emplace("Accept-Encoding", "gzip, deflate");
  7318. std::string body;
  7319. auto res = cli_.Get("/compress", headers,
  7320. [&](const char *data, uint64_t data_length) {
  7321. EXPECT_EQ(100U, data_length);
  7322. body.append(data, data_length);
  7323. return true;
  7324. });
  7325. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7326. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7327. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7328. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7329. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7330. "7890123456789012345678901234567890",
  7331. body);
  7332. EXPECT_EQ(StatusCode::OK_200, res->status);
  7333. }
  7334. TEST_F(ServerTest, GzipWithoutDecompressing) {
  7335. Headers headers;
  7336. headers.emplace("Accept-Encoding", "gzip, deflate");
  7337. cli_.set_decompress(false);
  7338. auto res = cli_.Get("/compress", headers);
  7339. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7340. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7341. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7342. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7343. EXPECT_EQ(33U, res->body.size());
  7344. EXPECT_EQ(StatusCode::OK_200, res->status);
  7345. }
  7346. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  7347. Headers headers;
  7348. headers.emplace("Accept-Encoding", "");
  7349. std::string body;
  7350. auto res = cli_.Get("/compress", headers,
  7351. [&](const char *data, uint64_t data_length) {
  7352. EXPECT_EQ(100U, data_length);
  7353. body.append(data, data_length);
  7354. return true;
  7355. });
  7356. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7357. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7358. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7359. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7360. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7361. "7890123456789012345678901234567890",
  7362. body);
  7363. EXPECT_EQ(StatusCode::OK_200, res->status);
  7364. }
  7365. TEST_F(ServerTest, NoGzip) {
  7366. Headers headers;
  7367. headers.emplace("Accept-Encoding", "gzip, deflate");
  7368. auto res = cli_.Get("/nocompress", headers);
  7369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7370. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7371. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7372. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7373. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7374. "7890123456789012345678901234567890",
  7375. res->body);
  7376. EXPECT_EQ(StatusCode::OK_200, res->status);
  7377. }
  7378. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  7379. Headers headers;
  7380. headers.emplace("Accept-Encoding", "gzip, deflate");
  7381. std::string body;
  7382. auto res = cli_.Get("/nocompress", headers,
  7383. [&](const char *data, uint64_t data_length) {
  7384. EXPECT_EQ(100U, data_length);
  7385. body.append(data, data_length);
  7386. return true;
  7387. });
  7388. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7389. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7390. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7391. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7392. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7393. "7890123456789012345678901234567890",
  7394. body);
  7395. EXPECT_EQ(StatusCode::OK_200, res->status);
  7396. }
  7397. TEST_F(ServerTest, MultipartFormDataGzip) {
  7398. UploadFormDataItems items = {
  7399. {"key1", "test", "", ""},
  7400. {"key2", "--abcdefg123", "", ""},
  7401. };
  7402. cli_.set_compress(true);
  7403. auto res = cli_.Post("/compress-multipart", items);
  7404. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7405. EXPECT_EQ(StatusCode::OK_200, res->status);
  7406. }
  7407. #endif
  7408. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7409. TEST_F(ServerTest, Brotli) {
  7410. Headers headers;
  7411. headers.emplace("Accept-Encoding", "br");
  7412. auto res = cli_.Get("/compress", headers);
  7413. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7414. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  7415. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7416. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  7417. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7418. "7890123456789012345678901234567890",
  7419. res->body);
  7420. EXPECT_EQ(StatusCode::OK_200, res->status);
  7421. }
  7422. #endif
  7423. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  7424. TEST_F(ServerTest, Zstd) {
  7425. Headers headers;
  7426. headers.emplace("Accept-Encoding", "zstd");
  7427. auto res = cli_.Get("/compress", headers);
  7428. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7429. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  7430. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7431. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  7432. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7433. "7890123456789012345678901234567890",
  7434. res->body);
  7435. EXPECT_EQ(StatusCode::OK_200, res->status);
  7436. }
  7437. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  7438. Headers headers;
  7439. headers.emplace("Accept-Encoding", "");
  7440. auto res = cli_.Get("/compress", headers);
  7441. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7442. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7443. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7444. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7445. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7446. "7890123456789012345678901234567890",
  7447. res->body);
  7448. EXPECT_EQ(StatusCode::OK_200, res->status);
  7449. }
  7450. TEST_F(ServerTest, ZstdWithContentReceiver) {
  7451. Headers headers;
  7452. headers.emplace("Accept-Encoding", "zstd");
  7453. std::string body;
  7454. auto res = cli_.Get("/compress", headers,
  7455. [&](const char *data, uint64_t data_length) {
  7456. EXPECT_EQ(100U, data_length);
  7457. body.append(data, data_length);
  7458. return true;
  7459. });
  7460. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7461. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  7462. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7463. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  7464. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7465. "7890123456789012345678901234567890",
  7466. body);
  7467. EXPECT_EQ(StatusCode::OK_200, res->status);
  7468. }
  7469. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  7470. Headers headers;
  7471. headers.emplace("Accept-Encoding", "zstd");
  7472. cli_.set_decompress(false);
  7473. auto res = cli_.Get("/compress", headers);
  7474. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  7475. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  7476. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  7477. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  7478. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7479. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  7480. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7481. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  7482. EXPECT_EQ(StatusCode::OK_200, res->status);
  7483. ASSERT_EQ(26U, res->body.size());
  7484. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  7485. 0);
  7486. }
  7487. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  7488. Headers headers;
  7489. headers.emplace("Accept-Encoding", "");
  7490. std::string body;
  7491. auto res = cli_.Get("/compress", headers,
  7492. [&](const char *data, uint64_t data_length) {
  7493. EXPECT_EQ(100U, data_length);
  7494. body.append(data, data_length);
  7495. return true;
  7496. });
  7497. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7498. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7499. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7500. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7501. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7502. "7890123456789012345678901234567890",
  7503. body);
  7504. EXPECT_EQ(StatusCode::OK_200, res->status);
  7505. }
  7506. TEST_F(ServerTest, NoZstd) {
  7507. Headers headers;
  7508. headers.emplace("Accept-Encoding", "zstd");
  7509. auto res = cli_.Get("/nocompress", headers);
  7510. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7511. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7512. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7513. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7514. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7515. "7890123456789012345678901234567890",
  7516. res->body);
  7517. EXPECT_EQ(StatusCode::OK_200, res->status);
  7518. }
  7519. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  7520. Headers headers;
  7521. headers.emplace("Accept-Encoding", "zstd");
  7522. std::string body;
  7523. auto res = cli_.Get("/nocompress", headers,
  7524. [&](const char *data, uint64_t data_length) {
  7525. EXPECT_EQ(100U, data_length);
  7526. body.append(data, data_length);
  7527. return true;
  7528. });
  7529. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7530. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7531. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7532. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7533. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7534. "7890123456789012345678901234567890",
  7535. body);
  7536. EXPECT_EQ(StatusCode::OK_200, res->status);
  7537. }
  7538. // TODO: How to enable zstd ??
  7539. TEST_F(ServerTest, MultipartFormDataZstd) {
  7540. UploadFormDataItems items = {
  7541. {"key1", "test", "", ""},
  7542. {"key2", "--abcdefg123", "", ""},
  7543. };
  7544. Headers headers;
  7545. headers.emplace("Accept-Encoding", "zstd");
  7546. cli_.set_compress(true);
  7547. auto res = cli_.Post("/compress-multipart", headers, items);
  7548. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7549. EXPECT_EQ(StatusCode::OK_200, res->status);
  7550. }
  7551. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  7552. Headers headers;
  7553. headers.emplace("Accept-Encoding", "zstd");
  7554. cli_.set_compress(true);
  7555. auto res = cli_.Put(
  7556. "/put", headers, 3,
  7557. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7558. sink.os << "PUT";
  7559. return true;
  7560. },
  7561. "text/plain");
  7562. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7563. EXPECT_EQ(StatusCode::OK_200, res->status);
  7564. EXPECT_EQ("PUT", res->body);
  7565. }
  7566. // Pre-compression logging tests
  7567. TEST_F(ServerTest, PreCompressionLogging) {
  7568. // Test data for compression (matches the actual /compress endpoint content)
  7569. const std::string test_content =
  7570. "123456789012345678901234567890123456789012345678901234567890123456789012"
  7571. "3456789012345678901234567890";
  7572. // Variables to capture logging data
  7573. std::string pre_compression_body;
  7574. std::string pre_compression_content_type;
  7575. std::string pre_compression_content_encoding;
  7576. std::string post_compression_body;
  7577. std::string post_compression_content_type;
  7578. std::string post_compression_content_encoding;
  7579. // Set up pre-compression logger
  7580. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  7581. const Response &res) {
  7582. pre_compression_body = res.body;
  7583. pre_compression_content_type = res.get_header_value("Content-Type");
  7584. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  7585. });
  7586. // Set up post-compression logger
  7587. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  7588. post_compression_body = res.body;
  7589. post_compression_content_type = res.get_header_value("Content-Type");
  7590. post_compression_content_encoding =
  7591. res.get_header_value("Content-Encoding");
  7592. });
  7593. // Test with gzip compression
  7594. Headers headers;
  7595. headers.emplace("Accept-Encoding", "gzip");
  7596. auto res = cli_.Get("/compress", headers);
  7597. // Verify response was compressed
  7598. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7599. EXPECT_EQ(StatusCode::OK_200, res->status);
  7600. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7601. // Verify pre-compression logger captured uncompressed content
  7602. EXPECT_EQ(test_content, pre_compression_body);
  7603. EXPECT_EQ("text/plain", pre_compression_content_type);
  7604. EXPECT_TRUE(pre_compression_content_encoding
  7605. .empty()); // No encoding header before compression
  7606. // Verify post-compression logger captured compressed content
  7607. EXPECT_NE(test_content,
  7608. post_compression_body); // Should be different after compression
  7609. EXPECT_EQ("text/plain", post_compression_content_type);
  7610. EXPECT_EQ("gzip", post_compression_content_encoding);
  7611. // Verify compressed content is smaller
  7612. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  7613. }
  7614. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  7615. const std::string test_content =
  7616. "123456789012345678901234567890123456789012345678901234567890123456789012"
  7617. "3456789012345678901234567890";
  7618. std::string pre_compression_body;
  7619. std::string post_compression_body;
  7620. svr_.set_pre_compression_logger(
  7621. [&](const Request & /*req*/, const Response &res) {
  7622. pre_compression_body = res.body;
  7623. });
  7624. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  7625. post_compression_body = res.body;
  7626. });
  7627. Headers headers;
  7628. headers.emplace("Accept-Encoding", "br");
  7629. auto res = cli_.Get("/compress", headers);
  7630. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7631. EXPECT_EQ(StatusCode::OK_200, res->status);
  7632. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  7633. // Verify pre-compression content is uncompressed
  7634. EXPECT_EQ(test_content, pre_compression_body);
  7635. // Verify post-compression content is compressed
  7636. EXPECT_NE(test_content, post_compression_body);
  7637. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  7638. }
  7639. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  7640. const std::string test_content =
  7641. "123456789012345678901234567890123456789012345678901234567890123456789012"
  7642. "3456789012345678901234567890";
  7643. std::string pre_compression_body;
  7644. std::string post_compression_body;
  7645. svr_.set_pre_compression_logger(
  7646. [&](const Request & /*req*/, const Response &res) {
  7647. pre_compression_body = res.body;
  7648. });
  7649. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  7650. post_compression_body = res.body;
  7651. });
  7652. // Request without compression (use /nocompress endpoint)
  7653. Headers headers;
  7654. auto res = cli_.Get("/nocompress", headers);
  7655. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7656. EXPECT_EQ(StatusCode::OK_200, res->status);
  7657. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7658. // Pre-compression logger should not be called when no compression is applied
  7659. EXPECT_TRUE(
  7660. pre_compression_body.empty()); // Pre-compression logger not called
  7661. EXPECT_EQ(
  7662. test_content,
  7663. post_compression_body); // Post-compression logger captures final content
  7664. }
  7665. TEST_F(ServerTest, LoggerSeesContentLength) {
  7666. size_t logged_content_length = 0;
  7667. std::string logged_content_length_header;
  7668. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  7669. logged_content_length = res.content_length_;
  7670. logged_content_length_header = res.get_header_value("Content-Length");
  7671. });
  7672. auto res = cli_.Get("/nocompress");
  7673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7674. EXPECT_EQ(StatusCode::OK_200, res->status);
  7675. EXPECT_EQ(res->body.size(), logged_content_length);
  7676. EXPECT_EQ(std::to_string(logged_content_length),
  7677. logged_content_length_header);
  7678. }
  7679. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  7680. const std::string test_content =
  7681. "123456789012345678901234567890123456789012345678901234567890123456789012"
  7682. "3456789012345678901234567890";
  7683. std::string pre_compression_body;
  7684. bool pre_logger_called = false;
  7685. // Set only pre-compression logger
  7686. svr_.set_pre_compression_logger(
  7687. [&](const Request & /*req*/, const Response &res) {
  7688. pre_compression_body = res.body;
  7689. pre_logger_called = true;
  7690. });
  7691. Headers headers;
  7692. headers.emplace("Accept-Encoding", "gzip");
  7693. auto res = cli_.Get("/compress", headers);
  7694. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7695. EXPECT_EQ(StatusCode::OK_200, res->status);
  7696. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7697. // Verify pre-compression logger was called
  7698. EXPECT_TRUE(pre_logger_called);
  7699. EXPECT_EQ(test_content, pre_compression_body);
  7700. }
  7701. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  7702. {
  7703. // Test with Expect: 100-continue header - success case
  7704. // Server returns 100 Continue, client sends body, server returns 200 OK
  7705. Request req;
  7706. req.method = "POST";
  7707. req.path = "/post-large";
  7708. req.set_header("Expect", "100-continue");
  7709. req.body = LARGE_DATA;
  7710. Response res;
  7711. auto error = Error::Success;
  7712. cli_.set_keep_alive(true);
  7713. auto ret = cli_.send(req, res, error);
  7714. EXPECT_TRUE(ret);
  7715. EXPECT_EQ(StatusCode::OK_200, res.status);
  7716. EXPECT_EQ(LARGE_DATA, res.body);
  7717. }
  7718. {
  7719. // Test with Expect: 100-continue header - error case
  7720. // Client should not send the body when server returns an error
  7721. Request req;
  7722. req.method = "POST";
  7723. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  7724. req.set_header("Expect", "100-continue");
  7725. req.body = LARGE_DATA;
  7726. Response res;
  7727. auto error = Error::Success;
  7728. auto start = std::chrono::high_resolution_clock::now();
  7729. cli_.set_keep_alive(true);
  7730. auto ret = cli_.send(req, res, error);
  7731. auto end = std::chrono::high_resolution_clock::now();
  7732. auto elapsed =
  7733. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  7734. .count();
  7735. // With Expect: 100-continue, request completes successfully but with error
  7736. EXPECT_TRUE(ret);
  7737. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  7738. EXPECT_EQ("close", res.get_header_value("Connection"));
  7739. EXPECT_FALSE(cli_.is_socket_open());
  7740. EXPECT_LE(elapsed, 2000);
  7741. }
  7742. {
  7743. // Send an extra GET request to ensure error recovery without hanging
  7744. Request req;
  7745. req.method = "GET";
  7746. req.path = "/hi";
  7747. auto start = std::chrono::high_resolution_clock::now();
  7748. auto res = cli_.send(req);
  7749. auto end = std::chrono::high_resolution_clock::now();
  7750. auto elapsed =
  7751. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  7752. .count();
  7753. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7754. EXPECT_EQ(StatusCode::OK_200, res->status);
  7755. EXPECT_EQ("Hello World!", res->body);
  7756. EXPECT_LE(elapsed, 500);
  7757. }
  7758. }
  7759. TEST(ZstdDecompressor, ChunkedDecompression) {
  7760. std::string data;
  7761. for (size_t i = 0; i < 32 * 1024; ++i) {
  7762. data.push_back(static_cast<char>('a' + i % 26));
  7763. }
  7764. std::string compressed_data;
  7765. {
  7766. httplib::detail::zstd_compressor compressor;
  7767. bool result = compressor.compress(
  7768. data.data(), data.size(),
  7769. /*last=*/true,
  7770. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  7771. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  7772. compressed_data_size);
  7773. return true;
  7774. });
  7775. ASSERT_TRUE(result);
  7776. }
  7777. std::string decompressed_data;
  7778. {
  7779. httplib::detail::zstd_decompressor decompressor;
  7780. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7781. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7782. size_t chunk_size = 130;
  7783. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7784. chunk_begin += chunk_size) {
  7785. size_t current_chunk_size =
  7786. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7787. bool result = decompressor.decompress(
  7788. compressed_data.data() + chunk_begin, current_chunk_size,
  7789. [&](const char *decompressed_data_chunk,
  7790. size_t decompressed_data_chunk_size) {
  7791. decompressed_data.insert(decompressed_data.size(),
  7792. decompressed_data_chunk,
  7793. decompressed_data_chunk_size);
  7794. return true;
  7795. });
  7796. ASSERT_TRUE(result);
  7797. }
  7798. }
  7799. ASSERT_EQ(data, decompressed_data);
  7800. }
  7801. TEST(ZstdDecompressor, Decompress) {
  7802. std::string original_text = "Compressed with ZSTD";
  7803. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  7804. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  7805. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  7806. 0x20, 0x5a, 0x53, 0x54, 0x44};
  7807. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7808. std::string decompressed_data;
  7809. {
  7810. httplib::detail::zstd_decompressor decompressor;
  7811. bool result = decompressor.decompress(
  7812. compressed_data.data(), compressed_data.size(),
  7813. [&](const char *decompressed_data_chunk,
  7814. size_t decompressed_data_chunk_size) {
  7815. decompressed_data.insert(decompressed_data.size(),
  7816. decompressed_data_chunk,
  7817. decompressed_data_chunk_size);
  7818. return true;
  7819. });
  7820. ASSERT_TRUE(result);
  7821. }
  7822. ASSERT_EQ(original_text, decompressed_data);
  7823. }
  7824. #endif
  7825. // Sends a raw request to a server listening at HOST:PORT, writing it in
  7826. // separate chunks so that the server sees each part in its own read(). Used to
  7827. // place a read boundary at a specific offset of a request body.
  7828. static bool send_request_in_parts(time_t read_timeout_sec,
  7829. const std::vector<std::string> &parts,
  7830. std::string *resp = nullptr,
  7831. int port = PORT) {
  7832. auto error = Error::Success;
  7833. auto client_sock = detail::create_client_socket(
  7834. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  7835. /*connection_timeout_sec=*/5, 0,
  7836. /*read_timeout_sec=*/5, 0,
  7837. /*write_timeout_sec=*/5, 0, std::string(), error);
  7838. if (client_sock == INVALID_SOCKET) { return false; }
  7839. auto ret = detail::process_client_socket(
  7840. client_sock, read_timeout_sec, 0, 0, 0, 0,
  7841. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  7842. for (size_t i = 0; i < parts.size(); i++) {
  7843. const auto &part = parts[i];
  7844. if (part.size() !=
  7845. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  7846. return false;
  7847. }
  7848. if (i + 1 < parts.size()) {
  7849. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  7850. }
  7851. }
  7852. char buf[512];
  7853. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  7854. while (line_reader.getline()) {
  7855. if (resp) { *resp += line_reader.ptr(); }
  7856. }
  7857. return true;
  7858. });
  7859. detail::close_socket(client_sock);
  7860. return ret;
  7861. }
  7862. // Sends a raw request to a server listening at HOST:PORT.
  7863. static bool send_request(time_t read_timeout_sec, const std::string &req,
  7864. std::string *resp = nullptr, int port = PORT) {
  7865. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  7866. }
  7867. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  7868. Server svr;
  7869. std::string header_value;
  7870. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  7871. header_value = req.get_header_value("foo");
  7872. res.set_content("ok", "text/plain");
  7873. });
  7874. thread t = thread([&] { svr.listen(HOST, PORT); });
  7875. auto se = detail::scope_exit([&] {
  7876. svr.stop();
  7877. t.join();
  7878. ASSERT_FALSE(svr.is_running());
  7879. });
  7880. svr.wait_until_ready();
  7881. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  7882. // like characters are not treated the same - use vertical tab and escape.
  7883. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  7884. "foo: \t \v bar \x1B\t \r\n"
  7885. "Connection: close\r\n"
  7886. "\r\n";
  7887. std::string res;
  7888. ASSERT_TRUE(send_request(5, req, &res));
  7889. EXPECT_EQ(header_value, "");
  7890. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  7891. }
  7892. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  7893. Server svr;
  7894. std::string received;
  7895. svr.Get("/order", [&](const Request &req, Response &res) {
  7896. received = entries_to_string(req.headers);
  7897. res.set_content("ok", "text/plain");
  7898. });
  7899. auto port = svr.bind_to_any_port(HOST);
  7900. thread t = thread([&] { svr.listen_after_bind(); });
  7901. auto se = detail::scope_exit([&] {
  7902. svr.stop();
  7903. t.join();
  7904. ASSERT_FALSE(svr.is_running());
  7905. });
  7906. svr.wait_until_ready();
  7907. const std::string req = "GET /order HTTP/1.1\r\n"
  7908. "X-First: 1\r\n"
  7909. "X-Dup: a\r\n"
  7910. "X-Second: 2\r\n"
  7911. "X-Dup: b\r\n"
  7912. "Connection: close\r\n"
  7913. "\r\n";
  7914. std::string res;
  7915. ASSERT_TRUE(send_request(5, req, &res, port));
  7916. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7917. EXPECT_EQ("X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ", received);
  7918. }
  7919. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  7920. Server svr;
  7921. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  7922. res.set_header("Set-Cookie", "first=1");
  7923. res.set_header("X-Between", "y");
  7924. res.set_header("Set-Cookie", "second=2");
  7925. res.set_content("ok", "text/plain");
  7926. });
  7927. auto port = svr.bind_to_any_port(HOST);
  7928. thread t = thread([&] { svr.listen_after_bind(); });
  7929. auto se = detail::scope_exit([&] {
  7930. svr.stop();
  7931. t.join();
  7932. ASSERT_FALSE(svr.is_running());
  7933. });
  7934. svr.wait_until_ready();
  7935. Client cli(HOST, port);
  7936. auto res = cli.Get("/cookies");
  7937. ASSERT_TRUE(res);
  7938. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  7939. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  7940. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  7941. }
  7942. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  7943. Server svr;
  7944. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  7945. auto i = new int(0);
  7946. res.set_header("Trailer", "X-Safe, X-Reflected");
  7947. res.set_chunked_content_provider(
  7948. "text/plain",
  7949. [i](size_t /*offset*/, DataSink &sink) {
  7950. if (*i == 0) {
  7951. sink.os << "body";
  7952. } else {
  7953. Headers trailer;
  7954. // A valid trailer that must survive.
  7955. trailer.emplace("X-Safe", "safe");
  7956. // Attacker-controlled value carrying CR/LF (response splitting).
  7957. trailer.emplace("X-Reflected",
  7958. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  7959. // Attacker-controlled name carrying CR/LF.
  7960. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  7961. sink.done_with_trailer(trailer);
  7962. }
  7963. (*i)++;
  7964. return true;
  7965. },
  7966. [i](bool /*success*/) { delete i; });
  7967. });
  7968. thread t = thread([&] { svr.listen(HOST, PORT); });
  7969. auto se = detail::scope_exit([&] {
  7970. svr.stop();
  7971. t.join();
  7972. ASSERT_FALSE(svr.is_running());
  7973. });
  7974. svr.wait_until_ready();
  7975. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  7976. "Host: " + HOST +
  7977. "\r\n"
  7978. "Connection: close\r\n"
  7979. "\r\n";
  7980. std::string res;
  7981. ASSERT_TRUE(send_request(5, req, &res));
  7982. // The injected fields must not appear anywhere in the raw response.
  7983. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  7984. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  7985. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  7986. // Invalid trailers are dropped entirely, matching set_header().
  7987. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  7988. // The valid trailer still passes through.
  7989. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  7990. }
  7991. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  7992. Server svr;
  7993. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  7994. // res.headers is a public field an application can populate directly,
  7995. // bypassing set_header()'s validation (e.g. reflecting a request value).
  7996. // A valid header that must survive.
  7997. res.headers.emplace("X-Safe", "safe");
  7998. // Attacker-controlled value carrying CR/LF (response splitting).
  7999. res.headers.emplace("X-Reflected",
  8000. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8001. // Attacker-controlled name carrying CR/LF.
  8002. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8003. res.set_content("body", "text/plain");
  8004. });
  8005. thread t = thread([&] { svr.listen(HOST, PORT); });
  8006. auto se = detail::scope_exit([&] {
  8007. svr.stop();
  8008. t.join();
  8009. ASSERT_FALSE(svr.is_running());
  8010. });
  8011. svr.wait_until_ready();
  8012. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  8013. "Host: " + HOST +
  8014. "\r\n"
  8015. "Connection: close\r\n"
  8016. "\r\n";
  8017. std::string res;
  8018. ASSERT_TRUE(send_request(5, req, &res));
  8019. // The injected fields must not appear anywhere in the raw response.
  8020. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8021. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8022. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8023. // Invalid headers are dropped entirely, matching set_header().
  8024. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8025. // The valid header still passes through.
  8026. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8027. }
  8028. // Forward declaration: in split builds split.py strips `inline` and moves the
  8029. // definition into httplib.cc, so detail::write_request_line is not visible from
  8030. // the public httplib.h. Re-declaring it here lets the tests link against the
  8031. // symbol in both header-only and split builds.
  8032. namespace httplib {
  8033. namespace detail {
  8034. ssize_t write_request_line(Stream &strm, const std::string &method,
  8035. const std::string &path);
  8036. } // namespace detail
  8037. } // namespace httplib
  8038. TEST(RequestLineInjectionTest, RejectsCRLFInTarget) {
  8039. // A well-formed target is written verbatim.
  8040. {
  8041. detail::BufferStream strm;
  8042. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  8043. EXPECT_GT(n, 0);
  8044. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  8045. }
  8046. // A target carrying CR/LF must be rejected before anything reaches the wire,
  8047. // otherwise it splits the request line and injects a header or a whole
  8048. // request. This is what a decoded redirect Location ("%0D%0A") turns into
  8049. // when path encoding is disabled.
  8050. const std::string evil_targets[] = {
  8051. "/a\r\nInjected: pwned",
  8052. "/a\rInjected",
  8053. "/a\nInjected",
  8054. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  8055. };
  8056. for (const auto &evil : evil_targets) {
  8057. detail::BufferStream strm;
  8058. auto n = detail::write_request_line(strm, "GET", evil);
  8059. EXPECT_LT(n, 0);
  8060. EXPECT_TRUE(strm.get_buffer().empty());
  8061. }
  8062. }
  8063. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  8064. // End-to-end counterpart to RejectsCRLFInTarget. With path encoding disabled
  8065. // the client transmits the target verbatim, so a CR/LF-bearing target -- what
  8066. // a redirect Location "%0D%0A" decodes to -- reaches write_request. The
  8067. // client must fail cleanly with Error::Write instead of putting a
  8068. // request-line-less, header-injecting request on the wire.
  8069. Server svr;
  8070. svr.Get("/a", [](const Request &, Response &res) {
  8071. res.set_content("ok", "text/plain");
  8072. });
  8073. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8074. auto se = detail::scope_exit([&] {
  8075. svr.stop();
  8076. thread.join();
  8077. ASSERT_FALSE(svr.is_running());
  8078. });
  8079. svr.wait_until_ready();
  8080. {
  8081. Client cli(HOST, PORT);
  8082. cli.set_path_encode(false);
  8083. // The request is rejected before anything is written, so the connection
  8084. // stays silent and the subsequent response read would otherwise block for
  8085. // the full default read timeout. Shorten it -- the assertion is on the
  8086. // error, not the timeout.
  8087. cli.set_read_timeout(1, 0);
  8088. auto res = cli.Get("/a\r\nInjected: pwned");
  8089. EXPECT_FALSE(res);
  8090. EXPECT_EQ(Error::Write, res.error());
  8091. }
  8092. }
  8093. // Sends a raw request and verifies that there isn't a crash or exception.
  8094. static void test_raw_request(const std::string &req,
  8095. std::string *out = nullptr) {
  8096. Server svr;
  8097. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  8098. res.set_content("ok", "text/plain");
  8099. });
  8100. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  8101. res.set_content("ok", "text/plain");
  8102. });
  8103. svr.Get("/header_field_value_check",
  8104. [&](const Request & /*req*/, Response &res) {
  8105. res.set_content("ok", "text/plain");
  8106. });
  8107. svr.CustomRoute("PROPFIND", "/dav",
  8108. [&](const Request & /*req*/, Response &res) {
  8109. res.status = StatusCode::MultiStatus_207;
  8110. });
  8111. // Server read timeout must be longer than the client read timeout for the
  8112. // bug to reproduce, probably to force the server to process a request
  8113. // without a trailing blank line.
  8114. const time_t client_read_timeout_sec = 1;
  8115. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  8116. bool listen_thread_ok = false;
  8117. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  8118. auto se = detail::scope_exit([&] {
  8119. svr.stop();
  8120. t.join();
  8121. ASSERT_FALSE(svr.is_running());
  8122. EXPECT_TRUE(listen_thread_ok);
  8123. });
  8124. svr.wait_until_ready();
  8125. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  8126. }
  8127. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  8128. // A certain header line causes an exception if the header property is parsed
  8129. // naively with a single regex. This occurs with libc++ but not libstdc++.
  8130. test_raw_request(
  8131. "GET /hi HTTP/1.1\r\n"
  8132. " : "
  8133. " "
  8134. " ");
  8135. }
  8136. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  8137. // A certain header line causes an exception if the header property *name* is
  8138. // parsed with a regular expression starting with "(.+?):" - this is a non-
  8139. // greedy matcher and requires backtracking when there are a lot of ":"
  8140. // characters.
  8141. // This occurs with libc++ but not libstdc++.
  8142. test_raw_request(
  8143. "GET /hi HTTP/1.1\r\n"
  8144. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  8145. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  8146. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  8147. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  8148. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  8149. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  8150. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  8151. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  8152. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  8153. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  8154. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  8155. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  8156. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  8157. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  8158. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  8159. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  8160. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  8161. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  8162. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  8163. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  8164. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  8165. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  8166. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  8167. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  8168. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  8169. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  8170. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  8171. "&&&%%%");
  8172. }
  8173. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  8174. // Make sure this doesn't crash the server.
  8175. // In a previous version of the header line regex, the "\r" rendered the line
  8176. // unparsable and the regex engine repeatedly backtracked, trying to look for
  8177. // a new position where the leading white space ended and the field value
  8178. // began.
  8179. // The crash occurs with libc++ but not libstdc++.
  8180. test_raw_request("GET /hi HTTP/1.1\r\n"
  8181. "a:" +
  8182. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  8183. "\r\n"
  8184. "\r\n");
  8185. }
  8186. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  8187. std::string out;
  8188. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  8189. "Content-Type: text/plain\r\n"
  8190. "Transfer-Encoding: chunked\r\n"
  8191. "\r\n"
  8192. "nothex\r\n",
  8193. &out);
  8194. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8195. }
  8196. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  8197. std::string out;
  8198. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  8199. "Content-Type: text/plain\r\n"
  8200. "Transfer-Encoding: chunked\r\n"
  8201. "\r\n"
  8202. "3\r\n"
  8203. "xyz\r\n"
  8204. "NaN\r\n",
  8205. &out);
  8206. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8207. }
  8208. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  8209. std::string out;
  8210. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  8211. "Content-Type: text/plain\r\n"
  8212. "Transfer-Encoding: chunked\r\n"
  8213. "\r\n"
  8214. // Length is too large for 64 bits.
  8215. "1ffffffffffffffff\r\n"
  8216. "xyz\r\n",
  8217. &out);
  8218. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8219. }
  8220. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  8221. test_raw_request("GET /hi HTTP/1.1\r\n"
  8222. "Content-Type: text/plain\r\n\r");
  8223. }
  8224. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  8225. std::string out;
  8226. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  8227. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8228. }
  8229. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  8230. Server svr;
  8231. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  8232. EXPECT_TRUE(!req.remote_addr.empty());
  8233. });
  8234. thread t = thread([&] { svr.listen(HOST, PORT); });
  8235. auto se = detail::scope_exit([&] {
  8236. svr.stop();
  8237. t.join();
  8238. ASSERT_FALSE(svr.is_running());
  8239. });
  8240. svr.wait_until_ready();
  8241. // Send an invalid request line to trigger Bad Request
  8242. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  8243. std::string out;
  8244. ASSERT_TRUE(send_request(5, bad_req, &out));
  8245. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8246. }
  8247. // A custom method with neither Content-Length nor Transfer-Encoding must be
  8248. // answered right away rather than blocking on a read that waits for EOF.
  8249. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  8250. std::string out;
  8251. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  8252. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  8253. }
  8254. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  8255. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  8256. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  8257. for (const auto *method : methods) {
  8258. Server svr;
  8259. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  8260. EXPECT_FALSE(svr.is_valid()) << method;
  8261. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  8262. }
  8263. }
  8264. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  8265. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  8266. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  8267. for (const auto *method : methods) {
  8268. Server svr;
  8269. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  8270. EXPECT_FALSE(svr.is_valid()) << method;
  8271. }
  8272. }
  8273. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  8274. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  8275. "COPY", "MOVE", "LOCK",
  8276. "UNLOCK", "REPORT", "SUBSCRIBE"};
  8277. Server svr;
  8278. for (const auto *method : methods) {
  8279. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  8280. }
  8281. EXPECT_TRUE(svr.is_valid());
  8282. }
  8283. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  8284. Server svr;
  8285. svr.CustomRoute("POST", "/x",
  8286. [](const Request &, Response &, const ContentReader &) {});
  8287. EXPECT_FALSE(svr.is_valid());
  8288. }
  8289. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  8290. Server svr;
  8291. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  8292. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  8293. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  8294. EXPECT_FALSE(svr.is_valid());
  8295. }
  8296. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  8297. Server svr;
  8298. auto captured = Error::Success;
  8299. svr.set_error_logger(
  8300. [&](const Error &err, const Request * /*req*/) { captured = err; });
  8301. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  8302. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  8303. }
  8304. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  8305. std::string out;
  8306. std::string request(
  8307. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  8308. test_raw_request(request, &out);
  8309. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8310. }
  8311. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  8312. std::string out;
  8313. std::string request(
  8314. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  8315. test_raw_request(request, &out);
  8316. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8317. }
  8318. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  8319. std::string out;
  8320. std::string request(
  8321. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  8322. test_raw_request(request, &out);
  8323. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8324. }
  8325. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  8326. std::string out;
  8327. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  8328. "Test: \r\n\r\n",
  8329. &out);
  8330. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  8331. }
  8332. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  8333. Server svr;
  8334. std::string x_custom;
  8335. std::string cookie;
  8336. std::string xff;
  8337. std::string x_unicode;
  8338. std::string x_iis;
  8339. svr.Get("/check", [&](const Request &req, Response &res) {
  8340. x_custom = req.get_header_value("X-Custom");
  8341. cookie = req.get_header_value("Cookie");
  8342. xff = req.get_header_value("X-Forwarded-For");
  8343. x_unicode = req.get_header_value("X-Unicode");
  8344. x_iis = req.get_header_value("X-IIS");
  8345. res.set_content("ok", "text/plain");
  8346. });
  8347. thread t = thread([&] { svr.listen(HOST, PORT); });
  8348. auto se = detail::scope_exit([&] {
  8349. svr.stop();
  8350. t.join();
  8351. ASSERT_FALSE(svr.is_running());
  8352. });
  8353. svr.wait_until_ready();
  8354. const std::string req = "GET /check HTTP/1.1\r\n"
  8355. "Host: localhost\r\n"
  8356. "X-Custom: a%0D%0AInjected: b\r\n"
  8357. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  8358. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  8359. "X-Unicode: %E3%81%82\r\n"
  8360. "X-IIS: %u00E9\r\n"
  8361. "Connection: close\r\n"
  8362. "\r\n";
  8363. std::string res;
  8364. ASSERT_TRUE(send_request(5, req, &res));
  8365. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8366. // Every value must be returned verbatim (wire form), with no decoding.
  8367. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  8368. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  8369. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  8370. EXPECT_EQ("%E3%81%82", x_unicode);
  8371. EXPECT_EQ("%u00E9", x_iis);
  8372. }
  8373. // Applications that previously relied on automatic percent-decoding can
  8374. // reproduce the old behavior by explicitly calling decode_path_component()
  8375. // or, for RFC 3986 conformance, decode_uri_component().
  8376. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  8377. Server svr;
  8378. std::string decoded;
  8379. svr.Get("/check", [&](const Request &req, Response &res) {
  8380. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  8381. res.set_content("ok", "text/plain");
  8382. });
  8383. thread t = thread([&] { svr.listen(HOST, PORT); });
  8384. auto se = detail::scope_exit([&] {
  8385. svr.stop();
  8386. t.join();
  8387. ASSERT_FALSE(svr.is_running());
  8388. });
  8389. svr.wait_until_ready();
  8390. const std::string req = "GET /check HTTP/1.1\r\n"
  8391. "Host: localhost\r\n"
  8392. "X-Custom: hello%20world\r\n"
  8393. "Connection: close\r\n"
  8394. "\r\n";
  8395. std::string res;
  8396. ASSERT_TRUE(send_request(5, req, &res));
  8397. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8398. EXPECT_EQ("hello world", decoded);
  8399. }
  8400. // Regression test for #2033. Browsers send Referer values that include
  8401. // percent-encoded characters such as %0A inside the URL. Decoding the
  8402. // header value would either trip the post-decode CR/LF/NUL guard (the
  8403. // original bug, returning 400) or, after that guard was relaxed, silently
  8404. // store a literal LF — both unacceptable. The wire form must round-trip.
  8405. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  8406. Server svr;
  8407. std::string referer;
  8408. svr.Get("/check", [&](const Request &req, Response &res) {
  8409. referer = req.get_header_value("Referer");
  8410. res.set_content("ok", "text/plain");
  8411. });
  8412. thread t = thread([&] { svr.listen(HOST, PORT); });
  8413. auto se = detail::scope_exit([&] {
  8414. svr.stop();
  8415. t.join();
  8416. ASSERT_FALSE(svr.is_running());
  8417. });
  8418. svr.wait_until_ready();
  8419. const std::string req = "GET /check HTTP/1.1\r\n"
  8420. "Host: localhost\r\n"
  8421. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  8422. "Connection: close\r\n"
  8423. "\r\n";
  8424. std::string res;
  8425. ASSERT_TRUE(send_request(5, req, &res));
  8426. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8427. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  8428. }
  8429. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  8430. Server svr;
  8431. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  8432. res.set_header("Cache-Control", "no-cache");
  8433. res.set_chunked_content_provider(
  8434. "text/event-stream", [](size_t offset, DataSink &sink) {
  8435. std::string s = "data:";
  8436. s += std::to_string(offset);
  8437. s += "\n\n";
  8438. auto ret = sink.write(s.data(), s.size());
  8439. EXPECT_TRUE(ret);
  8440. std::this_thread::sleep_for(std::chrono::seconds(1));
  8441. return true;
  8442. });
  8443. });
  8444. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8445. svr.wait_until_ready();
  8446. Client client(HOST, PORT);
  8447. const Headers headers = {{"Accept", "text/event-stream"}};
  8448. auto get_thread = std::thread([&client, &headers]() {
  8449. auto res = client.Get(
  8450. "/events", headers,
  8451. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  8452. });
  8453. auto se = detail::scope_exit([&] {
  8454. svr.stop();
  8455. get_thread.join();
  8456. listen_thread.join();
  8457. ASSERT_FALSE(svr.is_running());
  8458. });
  8459. // Give GET time to get a few messages.
  8460. std::this_thread::sleep_for(std::chrono::seconds(2));
  8461. }
  8462. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  8463. httplib::Server svr;
  8464. svr.Post("/hi",
  8465. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  8466. res.status = StatusCode::OK_200;
  8467. });
  8468. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8469. svr.wait_until_ready();
  8470. Client cli(HOST, PORT);
  8471. auto res = cli.Post("/hi", "data", "text/plain");
  8472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8473. EXPECT_EQ(StatusCode::OK_200, res->status);
  8474. svr.stop();
  8475. thread.join();
  8476. ASSERT_FALSE(svr.is_running());
  8477. res = cli.Post("/hi", "data", "text/plain");
  8478. ASSERT_FALSE(res);
  8479. }
  8480. TEST(ServerStopTest, ListenFailure) {
  8481. Server svr;
  8482. auto t = thread([&]() {
  8483. auto ret = svr.listen("????", PORT);
  8484. EXPECT_FALSE(ret);
  8485. });
  8486. svr.wait_until_ready();
  8487. svr.stop();
  8488. t.join();
  8489. }
  8490. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8491. TEST(ServerStopTest, Decommision) {
  8492. Server svr;
  8493. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  8494. for (int i = 0; i < 4; i++) {
  8495. auto is_even = !(i % 2);
  8496. std::thread t{[&] {
  8497. try {
  8498. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8499. if (is_even) {
  8500. throw std::runtime_error("Some thing that happens to go wrong.");
  8501. }
  8502. svr.listen(HOST, PORT);
  8503. } catch (...) { svr.decommission(); }
  8504. }};
  8505. svr.wait_until_ready();
  8506. // Server is up
  8507. {
  8508. Client cli(HOST, PORT);
  8509. auto res = cli.Get("/hi");
  8510. if (is_even) {
  8511. EXPECT_FALSE(res);
  8512. } else {
  8513. EXPECT_TRUE(res);
  8514. EXPECT_EQ("hi...", res->body);
  8515. }
  8516. }
  8517. svr.stop();
  8518. t.join();
  8519. // Server is down...
  8520. {
  8521. Client cli(HOST, PORT);
  8522. auto res = cli.Get("/hi");
  8523. EXPECT_FALSE(res);
  8524. }
  8525. }
  8526. }
  8527. #endif
  8528. // Helper function for string body upload progress tests
  8529. template <typename SetupHandler, typename ClientCall>
  8530. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  8531. ClientCall &&client_call,
  8532. const string &body) {
  8533. Server svr;
  8534. setup_handler(svr);
  8535. thread t = thread([&]() { svr.listen(HOST, PORT); });
  8536. auto se = detail::scope_exit([&] {
  8537. svr.stop();
  8538. t.join();
  8539. });
  8540. svr.wait_until_ready();
  8541. Client cli(HOST, PORT);
  8542. vector<uint64_t> progress_values;
  8543. bool progress_called = false;
  8544. auto res =
  8545. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  8546. progress_values.push_back(current);
  8547. progress_called = true;
  8548. return true;
  8549. });
  8550. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8551. EXPECT_EQ(200, res->status);
  8552. EXPECT_TRUE(progress_called);
  8553. }
  8554. TEST(UploadProgressTest, PostStringBodyBasic) {
  8555. TestStringBodyUploadProgress(
  8556. [](Server &svr) {
  8557. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  8558. res.set_content("received", "text/plain");
  8559. });
  8560. },
  8561. [](Client &cli, const string &body, UploadProgress progress_callback) {
  8562. return cli.Post("/test", body, "text/plain", progress_callback);
  8563. },
  8564. "test data for upload progress");
  8565. }
  8566. TEST(UploadProgressTest, PutStringBodyBasic) {
  8567. TestStringBodyUploadProgress(
  8568. [](Server &svr) {
  8569. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  8570. res.set_content("put received", "text/plain");
  8571. });
  8572. },
  8573. [](Client &cli, const string &body, UploadProgress progress_callback) {
  8574. return cli.Put("/test", body, "text/plain", progress_callback);
  8575. },
  8576. "put test data for upload progress");
  8577. }
  8578. TEST(UploadProgressTest, PatchStringBodyBasic) {
  8579. TestStringBodyUploadProgress(
  8580. [](Server &svr) {
  8581. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  8582. res.set_content("patch received", "text/plain");
  8583. });
  8584. },
  8585. [](Client &cli, const string &body, UploadProgress progress_callback) {
  8586. return cli.Patch("/test", body, "text/plain", progress_callback);
  8587. },
  8588. "patch test data for upload progress");
  8589. }
  8590. // Helper function for content provider upload progress tests
  8591. template <typename SetupHandler, typename ClientCall>
  8592. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  8593. ClientCall &&client_call) {
  8594. Server svr;
  8595. setup_handler(svr);
  8596. thread t = thread([&]() { svr.listen(HOST, PORT); });
  8597. auto se = detail::scope_exit([&] {
  8598. svr.stop();
  8599. t.join();
  8600. });
  8601. svr.wait_until_ready();
  8602. Client cli(HOST, PORT);
  8603. vector<uint64_t> progress_values;
  8604. auto res =
  8605. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  8606. progress_values.push_back(current);
  8607. return true;
  8608. });
  8609. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8610. EXPECT_EQ(200, res->status);
  8611. EXPECT_FALSE(progress_values.empty());
  8612. }
  8613. TEST(UploadProgressTest, PostContentProviderProgress) {
  8614. TestContentProviderUploadProgress(
  8615. [](Server &svr) {
  8616. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  8617. res.set_content("provider received", "text/plain");
  8618. });
  8619. },
  8620. [](Client &cli, UploadProgress progress_callback) {
  8621. return cli.Post(
  8622. "/test", 10,
  8623. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  8624. sink.os << "test data";
  8625. return true;
  8626. },
  8627. "text/plain", progress_callback);
  8628. });
  8629. }
  8630. // Helper function for multipart upload progress tests
  8631. template <typename SetupHandler, typename ClientCall>
  8632. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  8633. ClientCall &&client_call,
  8634. const string &endpoint) {
  8635. Server svr;
  8636. setup_handler(svr);
  8637. thread t = thread([&]() { svr.listen(HOST, PORT); });
  8638. auto se = detail::scope_exit([&] {
  8639. svr.stop();
  8640. t.join();
  8641. });
  8642. svr.wait_until_ready();
  8643. Client cli(HOST, PORT);
  8644. vector<uint64_t> progress_values;
  8645. UploadFormDataItems items = {
  8646. {"field1", "value1", "", ""},
  8647. {"field2", "longer value for progress tracking test", "", ""},
  8648. {"file1", "file content data for upload progress", "test.txt",
  8649. "text/plain"}};
  8650. auto res = client_call(cli, endpoint, items,
  8651. [&](uint64_t current, uint64_t /*total*/) -> bool {
  8652. progress_values.push_back(current);
  8653. return true;
  8654. });
  8655. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8656. EXPECT_EQ(200, res->status);
  8657. EXPECT_FALSE(progress_values.empty());
  8658. }
  8659. TEST(UploadProgressTest, PostMultipartProgress) {
  8660. TestMultipartUploadProgress(
  8661. [](Server &svr) {
  8662. svr.Post("/multipart", [](const Request &req, Response &res) {
  8663. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  8664. res.set_content("multipart received", "text/plain");
  8665. });
  8666. },
  8667. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  8668. UploadProgress progress_callback) {
  8669. return cli.Post(endpoint, items, progress_callback);
  8670. },
  8671. "/multipart");
  8672. }
  8673. // Helper function for basic download progress tests
  8674. template <typename SetupHandler, typename ClientCall>
  8675. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  8676. ClientCall &&client_call, const string &endpoint,
  8677. size_t expected_content_size) {
  8678. Server svr;
  8679. setup_handler(svr);
  8680. thread t = thread([&]() { svr.listen(HOST, PORT); });
  8681. auto se = detail::scope_exit([&] {
  8682. svr.stop();
  8683. t.join();
  8684. });
  8685. svr.wait_until_ready();
  8686. Client cli(HOST, PORT);
  8687. vector<uint64_t> progress_values;
  8688. auto res = client_call(cli, endpoint,
  8689. [&](uint64_t current, uint64_t /*total*/) -> bool {
  8690. progress_values.push_back(current);
  8691. return true;
  8692. });
  8693. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8694. EXPECT_EQ(200, res->status);
  8695. EXPECT_FALSE(progress_values.empty());
  8696. EXPECT_EQ(expected_content_size, res->body.size());
  8697. }
  8698. TEST(DownloadProgressTest, GetBasic) {
  8699. TestBasicDownloadProgress(
  8700. [](Server &svr) {
  8701. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  8702. string content(1000, 'D');
  8703. res.set_content(content, "text/plain");
  8704. });
  8705. },
  8706. [](Client &cli, const string &endpoint,
  8707. DownloadProgress progress_callback) {
  8708. return cli.Get(endpoint, progress_callback);
  8709. },
  8710. "/download", 1000u);
  8711. }
  8712. // Helper function for content receiver download progress tests
  8713. template <typename SetupHandler, typename ClientCall>
  8714. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  8715. ClientCall &&client_call,
  8716. const string &endpoint,
  8717. size_t expected_content_size) {
  8718. Server svr;
  8719. setup_handler(svr);
  8720. thread t = thread([&]() { svr.listen(HOST, PORT); });
  8721. auto se = detail::scope_exit([&] {
  8722. svr.stop();
  8723. t.join();
  8724. });
  8725. svr.wait_until_ready();
  8726. Client cli(HOST, PORT);
  8727. vector<uint64_t> progress_values;
  8728. string received_body;
  8729. auto res = client_call(
  8730. cli, endpoint,
  8731. [&](const char *data, size_t data_length) -> bool {
  8732. received_body.append(data, data_length);
  8733. return true;
  8734. },
  8735. [&](uint64_t current, uint64_t /*total*/) -> bool {
  8736. progress_values.push_back(current);
  8737. return true;
  8738. });
  8739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8740. EXPECT_EQ(200, res->status);
  8741. EXPECT_FALSE(progress_values.empty());
  8742. EXPECT_EQ(expected_content_size, received_body.size());
  8743. EXPECT_TRUE(res->body.empty());
  8744. }
  8745. TEST(DownloadProgressTest, GetWithContentReceiver) {
  8746. TestContentReceiverDownloadProgress(
  8747. [](Server &svr) {
  8748. svr.Get("/download-receiver",
  8749. [](const Request & /*req*/, Response &res) {
  8750. string content(2000, 'R');
  8751. res.set_content(content, "text/plain");
  8752. });
  8753. },
  8754. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  8755. DownloadProgress progress_callback) {
  8756. return cli.Get(endpoint, content_receiver, progress_callback);
  8757. },
  8758. "/download-receiver", 2000u);
  8759. }
  8760. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  8761. // A provider reaching a pass with nothing to hand over - an empty buffer
  8762. // popped off a queue, say - must not be taken to mean the body is finished.
  8763. // It used to end the loop with the terminating chunk unwritten while the
  8764. // server still considered the response complete, so the peer waited for an
  8765. // end that never arrived.
  8766. Server svr;
  8767. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  8768. auto step = std::make_shared<int>(0);
  8769. res.set_chunked_content_provider("text/plain",
  8770. [step](size_t /*offset*/, DataSink &sink) {
  8771. switch ((*step)++) {
  8772. case 0: sink.write("", 0); break;
  8773. case 1: sink.write("hello", 5); break;
  8774. default: sink.done(); break;
  8775. }
  8776. return true;
  8777. });
  8778. });
  8779. auto port = svr.bind_to_any_port(HOST);
  8780. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  8781. auto listen_se = detail::scope_exit([&] {
  8782. svr.stop();
  8783. listen_thread.join();
  8784. ASSERT_FALSE(svr.is_running());
  8785. });
  8786. svr.wait_until_ready();
  8787. Client cli(HOST, port);
  8788. // Without the fix the body is never terminated, so bound the wait rather
  8789. // than letting the test hang on the default read timeout.
  8790. cli.set_read_timeout(5, 0);
  8791. auto res = cli.Get("/stream");
  8792. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8793. EXPECT_EQ(StatusCode::OK_200, res->status);
  8794. EXPECT_EQ("hello", res->body);
  8795. }
  8796. TEST(StreamingTest, NoContentLengthStreaming) {
  8797. Server svr;
  8798. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  8799. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  8800. if (offset < 6) {
  8801. sink.os << (offset < 3 ? "a" : "b");
  8802. } else {
  8803. sink.done();
  8804. }
  8805. return true;
  8806. });
  8807. });
  8808. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8809. auto listen_se = detail::scope_exit([&] {
  8810. svr.stop();
  8811. listen_thread.join();
  8812. ASSERT_FALSE(svr.is_running());
  8813. });
  8814. svr.wait_until_ready();
  8815. Client client(HOST, PORT);
  8816. auto get_thread = std::thread([&client]() {
  8817. std::string s;
  8818. auto res =
  8819. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  8820. s += std::string(data, len);
  8821. return true;
  8822. });
  8823. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8824. EXPECT_EQ(StatusCode::OK_200, res->status);
  8825. EXPECT_EQ("aaabbb", s);
  8826. });
  8827. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  8828. // Give GET time to get a few messages.
  8829. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  8830. }
  8831. TEST(MountTest, Unmount) {
  8832. Server svr;
  8833. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8834. auto se = detail::scope_exit([&] {
  8835. svr.stop();
  8836. listen_thread.join();
  8837. ASSERT_FALSE(svr.is_running());
  8838. });
  8839. svr.wait_until_ready();
  8840. Client cli("localhost", PORT);
  8841. svr.set_mount_point("/mount2", "./www2");
  8842. auto res = cli.Get("/");
  8843. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8844. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8845. res = cli.Get("/mount2/dir/test.html");
  8846. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8847. EXPECT_EQ(StatusCode::OK_200, res->status);
  8848. svr.set_mount_point("/", "./www");
  8849. res = cli.Get("/dir/");
  8850. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8851. EXPECT_EQ(StatusCode::OK_200, res->status);
  8852. svr.remove_mount_point("/");
  8853. res = cli.Get("/dir/");
  8854. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8855. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8856. svr.remove_mount_point("/mount2");
  8857. res = cli.Get("/mount2/dir/test.html");
  8858. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8859. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8860. }
  8861. TEST(MountTest, PathSegmentBoundary) {
  8862. Server svr;
  8863. svr.set_mount_point("/mount2", "./www2");
  8864. svr.set_mount_point("/", "./www");
  8865. auto port = svr.bind_to_any_port(HOST);
  8866. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  8867. auto se = detail::scope_exit([&] {
  8868. svr.stop();
  8869. listen_thread.join();
  8870. ASSERT_FALSE(svr.is_running());
  8871. });
  8872. svr.wait_until_ready();
  8873. Client cli(HOST, port);
  8874. auto res = cli.Get("/mount2/dir/test.html");
  8875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8876. EXPECT_EQ(StatusCode::OK_200, res->status);
  8877. // "/mount2" must not match part-way through a path segment.
  8878. res = cli.Get("/mount2dir/test.html");
  8879. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8880. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8881. // A mount point ending in '/' keeps matching every path below it.
  8882. res = cli.Get("/dir/test.html");
  8883. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8884. EXPECT_EQ(StatusCode::OK_200, res->status);
  8885. }
  8886. TEST(MountTest, Redicect) {
  8887. Server svr;
  8888. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8889. auto se = detail::scope_exit([&] {
  8890. svr.stop();
  8891. listen_thread.join();
  8892. ASSERT_FALSE(svr.is_running());
  8893. });
  8894. svr.set_mount_point("/", "./www");
  8895. svr.wait_until_ready();
  8896. Client cli("localhost", PORT);
  8897. auto res = cli.Get("/dir/");
  8898. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8899. EXPECT_EQ(StatusCode::OK_200, res->status);
  8900. res = cli.Get("/dir");
  8901. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8902. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  8903. res = cli.Get("/file");
  8904. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8905. EXPECT_EQ(StatusCode::OK_200, res->status);
  8906. res = cli.Get("/file/");
  8907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8908. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8909. cli.set_follow_location(true);
  8910. res = cli.Get("/dir");
  8911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8912. EXPECT_EQ(StatusCode::OK_200, res->status);
  8913. }
  8914. TEST(MountTest, MultibytesPathName) {
  8915. Server svr;
  8916. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8917. auto se = detail::scope_exit([&] {
  8918. svr.stop();
  8919. listen_thread.join();
  8920. ASSERT_FALSE(svr.is_running());
  8921. });
  8922. svr.set_mount_point("/", "./www");
  8923. svr.wait_until_ready();
  8924. Client cli("localhost", PORT);
  8925. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  8926. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8927. EXPECT_EQ(StatusCode::OK_200, res->status);
  8928. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  8929. }
  8930. #ifdef _WIN32
  8931. // Issue #2435: mmap::open() must succeed even when another handle holds
  8932. // the file open for writing (e.g. an active log file).
  8933. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  8934. const char *path = "mmap_concurrent_writer_test.txt";
  8935. const char *content = "hello";
  8936. {
  8937. std::ofstream f(path, std::ios::binary);
  8938. f.write(content, static_cast<std::streamsize>(strlen(content)));
  8939. }
  8940. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  8941. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  8942. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  8943. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  8944. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  8945. detail::mmap m(path);
  8946. ASSERT_TRUE(m.is_open());
  8947. EXPECT_EQ(strlen(content), m.size());
  8948. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  8949. }
  8950. #endif
  8951. #ifndef _WIN32
  8952. // A failed ::mmap() must not be reported as an open mapping, otherwise data()
  8953. // hands the caller the MAP_FAILED sentinel. A directory is the easiest way to
  8954. // reach it, since ::open() and fstat() succeed for one but ::mmap() doesn't.
  8955. TEST(MmapTest, FailedMappingIsNotOpen) {
  8956. const char *path = "./mmap_failed_mapping_test_dir";
  8957. ASSERT_EQ(0, ::mkdir(path, 0755));
  8958. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  8959. detail::mmap m(path);
  8960. EXPECT_FALSE(m.is_open());
  8961. EXPECT_EQ(0U, m.size());
  8962. EXPECT_NE(static_cast<const void *>(m.data()),
  8963. static_cast<const void *>(MAP_FAILED));
  8964. }
  8965. #endif
  8966. TEST(KeepAliveTest, ReadTimeout) {
  8967. Server svr;
  8968. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  8969. std::this_thread::sleep_for(std::chrono::seconds(2));
  8970. res.set_content("a", "text/plain");
  8971. });
  8972. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  8973. res.set_content("b", "text/plain");
  8974. });
  8975. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8976. auto se = detail::scope_exit([&] {
  8977. svr.stop();
  8978. listen_thread.join();
  8979. ASSERT_FALSE(svr.is_running());
  8980. });
  8981. svr.wait_until_ready();
  8982. Client cli("localhost", PORT);
  8983. cli.set_keep_alive(true);
  8984. cli.set_read_timeout(std::chrono::seconds(1));
  8985. auto resa = cli.Get("/a");
  8986. ASSERT_FALSE(resa);
  8987. EXPECT_EQ(Error::Read, resa.error());
  8988. auto resb = cli.Get("/b");
  8989. ASSERT_TRUE(resb);
  8990. EXPECT_EQ(StatusCode::OK_200, resb->status);
  8991. EXPECT_EQ("b", resb->body);
  8992. }
  8993. TEST(KeepAliveTest, MaxCount) {
  8994. size_t keep_alive_max_count = 3;
  8995. Server svr;
  8996. svr.set_keep_alive_max_count(keep_alive_max_count);
  8997. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  8998. res.set_content("Hello World!", "text/plain");
  8999. });
  9000. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9001. auto se = detail::scope_exit([&] {
  9002. svr.stop();
  9003. listen_thread.join();
  9004. ASSERT_FALSE(svr.is_running());
  9005. });
  9006. svr.wait_until_ready();
  9007. Client cli(HOST, PORT);
  9008. cli.set_keep_alive(true);
  9009. for (size_t i = 0; i < 5; i++) {
  9010. auto result = cli.Get("/hi");
  9011. ASSERT_TRUE(result);
  9012. EXPECT_EQ(StatusCode::OK_200, result->status);
  9013. if (i == keep_alive_max_count - 1) {
  9014. EXPECT_EQ("close", result->get_header_value("Connection"));
  9015. } else {
  9016. EXPECT_FALSE(result->has_header("Connection"));
  9017. }
  9018. }
  9019. }
  9020. TEST(KeepAliveTest, Issue1041) {
  9021. Server svr;
  9022. svr.set_keep_alive_timeout(3);
  9023. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9024. res.set_content("Hello World!", "text/plain");
  9025. });
  9026. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9027. auto se = detail::scope_exit([&] {
  9028. svr.stop();
  9029. listen_thread.join();
  9030. ASSERT_FALSE(svr.is_running());
  9031. });
  9032. svr.wait_until_ready();
  9033. Client cli(HOST, PORT);
  9034. cli.set_keep_alive(true);
  9035. auto result = cli.Get("/hi");
  9036. ASSERT_TRUE(result);
  9037. EXPECT_EQ(StatusCode::OK_200, result->status);
  9038. std::this_thread::sleep_for(std::chrono::seconds(5));
  9039. result = cli.Get("/hi");
  9040. ASSERT_TRUE(result);
  9041. EXPECT_EQ(StatusCode::OK_200, result->status);
  9042. }
  9043. TEST(KeepAliveTest, Issue1959) {
  9044. Server svr;
  9045. svr.set_keep_alive_timeout(5);
  9046. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  9047. res.set_content("a", "text/plain");
  9048. });
  9049. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9050. auto se = detail::scope_exit([&] {
  9051. if (!svr.is_running()) return;
  9052. svr.stop();
  9053. listen_thread.join();
  9054. ASSERT_FALSE(svr.is_running());
  9055. });
  9056. svr.wait_until_ready();
  9057. Client cli("localhost", PORT);
  9058. cli.set_keep_alive(true);
  9059. using namespace std::chrono;
  9060. auto start = steady_clock::now();
  9061. cli.Get("/a");
  9062. svr.stop();
  9063. listen_thread.join();
  9064. auto end = steady_clock::now();
  9065. auto elapsed = duration_cast<milliseconds>(end - start).count();
  9066. EXPECT_LT(elapsed, 5000);
  9067. }
  9068. #ifdef CPPHTTPLIB_SSL_ENABLED
  9069. TEST(KeepAliveTest, SSLClientReconnection) {
  9070. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9071. ASSERT_TRUE(svr.is_valid());
  9072. svr.set_keep_alive_timeout(1);
  9073. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9074. res.set_content("Hello World!", "text/plain");
  9075. });
  9076. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9077. auto se = detail::scope_exit([&] {
  9078. svr.stop();
  9079. listen_thread.join();
  9080. ASSERT_FALSE(svr.is_running());
  9081. });
  9082. svr.wait_until_ready();
  9083. SSLClient cli(HOST, PORT);
  9084. cli.enable_server_certificate_verification(false);
  9085. cli.set_keep_alive(true);
  9086. auto result = cli.Get("/hi");
  9087. ASSERT_TRUE(result);
  9088. EXPECT_EQ(StatusCode::OK_200, result->status);
  9089. result = cli.Get("/hi");
  9090. ASSERT_TRUE(result);
  9091. EXPECT_EQ(StatusCode::OK_200, result->status);
  9092. std::this_thread::sleep_for(std::chrono::seconds(2));
  9093. // Recoonect
  9094. result = cli.Get("/hi");
  9095. ASSERT_TRUE(result);
  9096. EXPECT_EQ(StatusCode::OK_200, result->status);
  9097. result = cli.Get("/hi");
  9098. ASSERT_TRUE(result);
  9099. EXPECT_EQ(StatusCode::OK_200, result->status);
  9100. }
  9101. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  9102. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9103. ASSERT_TRUE(svr.is_valid());
  9104. svr.set_keep_alive_timeout(1);
  9105. std::string content = "reconnect";
  9106. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  9107. res.set_content("Hello World!", "text/plain");
  9108. });
  9109. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9110. auto se = detail::scope_exit([&] {
  9111. svr.stop();
  9112. listen_thread.join();
  9113. ASSERT_FALSE(svr.is_running());
  9114. });
  9115. svr.wait_until_ready();
  9116. SSLClient cli(HOST, PORT);
  9117. cli.enable_server_certificate_verification(false);
  9118. cli.set_keep_alive(true);
  9119. auto result = cli.Post(
  9120. "/hi", content.size(),
  9121. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9122. sink.write(content.c_str(), content.size());
  9123. return true;
  9124. },
  9125. "text/plain");
  9126. ASSERT_TRUE(result);
  9127. EXPECT_EQ(200, result->status);
  9128. std::this_thread::sleep_for(std::chrono::seconds(2));
  9129. // Recoonect
  9130. result = cli.Post(
  9131. "/hi", content.size(),
  9132. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9133. sink.write(content.c_str(), content.size());
  9134. return true;
  9135. },
  9136. "text/plain");
  9137. ASSERT_TRUE(result);
  9138. EXPECT_EQ(200, result->status);
  9139. result = cli.Post(
  9140. "/hi", content.size(),
  9141. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9142. sink.write(content.c_str(), content.size());
  9143. return true;
  9144. },
  9145. "text/plain");
  9146. ASSERT_TRUE(result);
  9147. EXPECT_EQ(200, result->status);
  9148. }
  9149. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  9150. using namespace httplib::tls;
  9151. {
  9152. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9153. ASSERT_TRUE(svr.is_valid());
  9154. svr.Get("/sni", [&](const Request &req, Response &res) {
  9155. std::string expected = req.sni();
  9156. EXPECT_EQ(expected, req.get_param_value("expected"));
  9157. res.set_content("ok", "text/plain");
  9158. });
  9159. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9160. auto se = detail::scope_exit([&] {
  9161. svr.stop();
  9162. listen_thread.join();
  9163. ASSERT_FALSE(svr.is_running());
  9164. });
  9165. svr.wait_until_ready();
  9166. {
  9167. SSLClient cli("localhost", PORT);
  9168. cli.enable_server_certificate_verification(false);
  9169. auto res = cli.Get("/sni?expected=localhost");
  9170. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9171. }
  9172. {
  9173. SSLClient cli("::1", PORT);
  9174. cli.enable_server_certificate_verification(false);
  9175. auto res = cli.Get("/sni?expected=");
  9176. // NOTE: This may fail if the server is listening on IPv4 only
  9177. // (e.g., when localhost resolves to 127.0.0.1 only)
  9178. if (res) {
  9179. EXPECT_EQ(StatusCode::OK_200, res->status);
  9180. } else {
  9181. EXPECT_EQ(Error::Connection, res.error());
  9182. }
  9183. }
  9184. }
  9185. }
  9186. #endif
  9187. TEST(ClientProblemDetectionTest, ContentProvider) {
  9188. Server svr;
  9189. size_t content_length = 1024 * 1024;
  9190. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9191. res.set_content_provider(
  9192. content_length, "text/plain",
  9193. [&](size_t offset, size_t length, DataSink &sink) {
  9194. auto out_len = std::min(length, static_cast<size_t>(1024));
  9195. std::string out(out_len, '@');
  9196. sink.write(out.data(), out_len);
  9197. return offset < 4096;
  9198. },
  9199. [](bool success) { ASSERT_FALSE(success); });
  9200. });
  9201. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  9202. res.set_content_provider(
  9203. 0, "text/plain",
  9204. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  9205. EXPECT_TRUE(false);
  9206. return true;
  9207. },
  9208. [](bool success) { ASSERT_FALSE(success); });
  9209. });
  9210. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9211. auto 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("localhost", PORT);
  9218. {
  9219. auto res = cli.Get("/hi", [&](const char * /*data*/,
  9220. size_t /*data_length*/) { return false; });
  9221. ASSERT_FALSE(res);
  9222. }
  9223. {
  9224. auto res = cli.Get("/empty", [&](const char * /*data*/,
  9225. size_t /*data_length*/) { return false; });
  9226. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9227. }
  9228. }
  9229. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  9230. // A provider that reports success without writing anything and without
  9231. // calling done() used to be handed the same offset and length again on every
  9232. // pass, so it spun for as long as the peer stayed connected.
  9233. Server svr;
  9234. svr.Post("/", [](const Request & /*req*/, Response &res) {
  9235. res.set_content("ok", "text/plain");
  9236. });
  9237. auto port = svr.bind_to_any_port(HOST);
  9238. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  9239. auto se = detail::scope_exit([&] {
  9240. svr.stop();
  9241. listen_thread.join();
  9242. ASSERT_FALSE(svr.is_running());
  9243. });
  9244. svr.wait_until_ready();
  9245. std::atomic<int> call_count{0};
  9246. Client cli(HOST, port);
  9247. auto res = cli.Post(
  9248. "/", 1024,
  9249. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  9250. // Give up after enough passes to show the spin, so that losing the
  9251. // check below fails this test instead of hanging it.
  9252. return ++call_count < 100;
  9253. },
  9254. "text/plain");
  9255. ASSERT_FALSE(res);
  9256. EXPECT_EQ(Error::Write, res.error());
  9257. EXPECT_EQ(1, call_count.load());
  9258. }
  9259. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  9260. // A writer only has to assign `write`. The other three used to be left as
  9261. // empty std::functions, so a provider calling one threw
  9262. // std::bad_function_call out of the thread running it and took the whole
  9263. // process down.
  9264. DataSink sink;
  9265. std::string written;
  9266. sink.write = [&](const char *data, size_t data_len) {
  9267. written.append(data, data_len);
  9268. return true;
  9269. };
  9270. EXPECT_TRUE(sink.is_writable());
  9271. sink.done();
  9272. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  9273. EXPECT_TRUE(written.empty());
  9274. }
  9275. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  9276. // A sink that cannot carry trailers still has to finish.
  9277. DataSink sink;
  9278. auto done_count = 0;
  9279. sink.done = [&]() { done_count++; };
  9280. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  9281. EXPECT_EQ(1, done_count);
  9282. }
  9283. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  9284. Server svr;
  9285. const std::string body(4096, 'x');
  9286. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  9287. res.set_content_provider(body.size(), "text/plain",
  9288. [&](size_t offset, size_t length, DataSink &sink) {
  9289. sink.write(body.data() + offset, length);
  9290. sink.done();
  9291. return true;
  9292. });
  9293. });
  9294. auto port = svr.bind_to_any_port(HOST);
  9295. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9296. auto se = detail::scope_exit([&] {
  9297. svr.stop();
  9298. listen_thread.join();
  9299. ASSERT_FALSE(svr.is_running());
  9300. });
  9301. svr.wait_until_ready();
  9302. Client cli(HOST, port);
  9303. auto res = cli.Get("/");
  9304. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9305. EXPECT_EQ(StatusCode::OK_200, res->status);
  9306. EXPECT_EQ(body, res->body);
  9307. }
  9308. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  9309. Server svr;
  9310. svr.Get("/", [](const Request & /*req*/, Response &res) {
  9311. res.set_content_provider(
  9312. 1024, "text/plain",
  9313. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9314. sink.write("hello", 5);
  9315. sink.done(); // short of the 1024 bytes the response promised
  9316. return true;
  9317. });
  9318. });
  9319. auto port = svr.bind_to_any_port(HOST);
  9320. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9321. auto se = detail::scope_exit([&] {
  9322. svr.stop();
  9323. listen_thread.join();
  9324. ASSERT_FALSE(svr.is_running());
  9325. });
  9326. svr.wait_until_ready();
  9327. Client cli(HOST, port);
  9328. cli.set_read_timeout(5, 0);
  9329. // The response is short of its Content-Length, so the client cannot read a
  9330. // complete body. What matters is that this returns at all: a no-op done()
  9331. // would leave the writer looping over a provider that never makes progress.
  9332. auto res = cli.Get("/");
  9333. EXPECT_FALSE(res);
  9334. }
  9335. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9336. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  9337. // The compressed path builds the whole body before connecting, so this
  9338. // fails client-side and never reaches a server.
  9339. Client cli(HOST, PORT);
  9340. cli.set_compress(true);
  9341. auto res = cli.Post(
  9342. "/", 1024,
  9343. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9344. sink.write("hello", 5);
  9345. sink.done(); // short of the 1024 bytes the request announced
  9346. return true;
  9347. },
  9348. "text/plain");
  9349. ASSERT_FALSE(res);
  9350. EXPECT_EQ(Error::Write, res.error());
  9351. }
  9352. #endif
  9353. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  9354. Server svr;
  9355. svr.set_error_handler([](Request const &, Response &res) -> void {
  9356. res.set_chunked_content_provider(
  9357. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  9358. sink.os << "hello";
  9359. sink.os << "world";
  9360. sink.done();
  9361. return true;
  9362. });
  9363. });
  9364. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9365. auto se = detail::scope_exit([&] {
  9366. svr.stop();
  9367. listen_thread.join();
  9368. ASSERT_FALSE(svr.is_running());
  9369. });
  9370. svr.wait_until_ready();
  9371. Client cli("localhost", PORT);
  9372. auto res = cli.Get("/");
  9373. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9374. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9375. EXPECT_EQ("helloworld", res->body);
  9376. }
  9377. TEST(LongPollingTest, ClientCloseDetection) {
  9378. Server svr;
  9379. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  9380. res.set_chunked_content_provider(
  9381. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  9382. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  9383. sink.os << "hello";
  9384. auto count = 10;
  9385. while (count > 0 && sink.is_writable()) {
  9386. this_thread::sleep_for(chrono::milliseconds(10));
  9387. count--;
  9388. }
  9389. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  9390. return true;
  9391. });
  9392. });
  9393. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9394. auto se = detail::scope_exit([&] {
  9395. svr.stop();
  9396. listen_thread.join();
  9397. ASSERT_FALSE(svr.is_running());
  9398. });
  9399. svr.wait_until_ready();
  9400. Client cli("localhost", PORT);
  9401. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  9402. EXPECT_EQ("hello", string(data, data_length));
  9403. return false; // close the socket immediately.
  9404. });
  9405. ASSERT_FALSE(res);
  9406. }
  9407. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  9408. Server svr;
  9409. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  9410. res.set_chunked_content_provider(
  9411. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  9412. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  9413. sink.os << "hello";
  9414. EXPECT_TRUE(sink.os.good());
  9415. // Wait for the client to close the connection
  9416. auto count = 10;
  9417. while (count > 0 && sink.is_writable()) {
  9418. this_thread::sleep_for(chrono::milliseconds(10));
  9419. count--;
  9420. }
  9421. // After client disconnect, write repeatedly until the socket
  9422. // write actually fails (small writes may be absorbed by the
  9423. // kernel buffer)
  9424. std::string chunk(1024, 'x');
  9425. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  9426. sink.os << chunk;
  9427. }
  9428. EXPECT_TRUE(sink.os.fail());
  9429. return true;
  9430. });
  9431. });
  9432. auto port = svr.bind_to_any_port("localhost");
  9433. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9434. auto se = detail::scope_exit([&] {
  9435. svr.stop();
  9436. listen_thread.join();
  9437. ASSERT_FALSE(svr.is_running());
  9438. });
  9439. svr.wait_until_ready();
  9440. Client cli("localhost", port);
  9441. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  9442. EXPECT_EQ("hello", string(data, data_length));
  9443. return false; // close the socket immediately.
  9444. });
  9445. ASSERT_FALSE(res);
  9446. }
  9447. TEST(GetWithParametersTest, GetWithParameters) {
  9448. Server svr;
  9449. svr.Get("/", [&](const Request &req, Response &) {
  9450. EXPECT_EQ("world", req.get_param_value("hello"));
  9451. EXPECT_EQ("world2", req.get_param_value("hello2"));
  9452. EXPECT_EQ("world3", req.get_param_value("hello3"));
  9453. });
  9454. svr.Get("/params", [&](const Request &req, Response &) {
  9455. EXPECT_EQ("world", req.get_param_value("hello"));
  9456. EXPECT_EQ("world2", req.get_param_value("hello2"));
  9457. EXPECT_EQ("world3", req.get_param_value("hello3"));
  9458. });
  9459. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  9460. EXPECT_EQ("resource-id", req.matches[1]);
  9461. EXPECT_EQ("foo", req.get_param_value("param1"));
  9462. EXPECT_EQ("bar", req.get_param_value("param2"));
  9463. });
  9464. svr.Get("/users/:id", [&](const Request &req, Response &) {
  9465. EXPECT_EQ("user-id", req.path_params.at("id"));
  9466. EXPECT_EQ("foo", req.get_param_value("param1"));
  9467. EXPECT_EQ("bar", req.get_param_value("param2"));
  9468. });
  9469. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  9470. auto se = detail::scope_exit([&] {
  9471. svr.stop();
  9472. listen_thread.join();
  9473. ASSERT_FALSE(svr.is_running());
  9474. });
  9475. svr.wait_until_ready();
  9476. {
  9477. Client cli(HOST, PORT);
  9478. Params params;
  9479. params.emplace("hello", "world");
  9480. params.emplace("hello2", "world2");
  9481. params.emplace("hello3", "world3");
  9482. auto res = cli.Get("/", params, Headers{});
  9483. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9484. EXPECT_EQ(StatusCode::OK_200, res->status);
  9485. }
  9486. {
  9487. Client cli(HOST, PORT);
  9488. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  9489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9490. EXPECT_EQ(StatusCode::OK_200, res->status);
  9491. }
  9492. {
  9493. Client cli(HOST, PORT);
  9494. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  9495. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9496. EXPECT_EQ(StatusCode::OK_200, res->status);
  9497. }
  9498. {
  9499. Client cli(HOST, PORT);
  9500. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  9501. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9502. EXPECT_EQ(StatusCode::OK_200, res->status);
  9503. }
  9504. }
  9505. TEST(GetWithParametersTest, GetWithParameters2) {
  9506. Server svr;
  9507. svr.Get("/", [&](const Request &req, Response &res) {
  9508. auto text = req.get_param_value("hello");
  9509. res.set_content(text, "text/plain");
  9510. });
  9511. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9512. auto se = detail::scope_exit([&] {
  9513. svr.stop();
  9514. listen_thread.join();
  9515. ASSERT_FALSE(svr.is_running());
  9516. });
  9517. svr.wait_until_ready();
  9518. Client cli("localhost", PORT);
  9519. Params params;
  9520. params.emplace("hello", "world");
  9521. std::string body;
  9522. auto res = cli.Get("/", params, Headers{},
  9523. [&](const char *data, size_t data_length) {
  9524. body.append(data, data_length);
  9525. return true;
  9526. });
  9527. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9528. EXPECT_EQ(StatusCode::OK_200, res->status);
  9529. EXPECT_EQ("world", body);
  9530. }
  9531. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  9532. Server svr;
  9533. svr.Get("/search", [&](const Request &req, Response &res) {
  9534. auto q = req.get_param_value("q");
  9535. res.set_content(q, "text/plain");
  9536. });
  9537. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9538. auto se = detail::scope_exit([&] {
  9539. svr.stop();
  9540. listen_thread.join();
  9541. ASSERT_FALSE(svr.is_running());
  9542. });
  9543. svr.wait_until_ready();
  9544. Client cli("localhost", PORT);
  9545. // Verify that Get(path, params) works without requiring Headers argument
  9546. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  9547. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9548. EXPECT_EQ(StatusCode::OK_200, res->status);
  9549. EXPECT_EQ("cpp-httplib", res->body);
  9550. }
  9551. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  9552. auto host = "httpbingo.org";
  9553. auto path = std::string{"/range/32"};
  9554. #ifdef CPPHTTPLIB_SSL_ENABLED
  9555. SSLClient cli(host);
  9556. #else
  9557. Client cli(host);
  9558. #endif
  9559. cli.set_default_headers({make_range_header({{1, 10}})});
  9560. cli.set_connection_timeout(5);
  9561. {
  9562. auto res = cli.Get(path);
  9563. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9564. EXPECT_EQ("bcdefghijk", res->body);
  9565. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  9566. }
  9567. {
  9568. auto res = cli.Get(path);
  9569. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9570. EXPECT_EQ("bcdefghijk", res->body);
  9571. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  9572. }
  9573. }
  9574. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  9575. Server svr;
  9576. svr.set_default_headers({{"Hello", "World"}});
  9577. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  9578. res.set_content("ok", "text/plain");
  9579. });
  9580. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9581. auto se = detail::scope_exit([&] {
  9582. svr.stop();
  9583. listen_thread.join();
  9584. ASSERT_FALSE(svr.is_running());
  9585. });
  9586. svr.wait_until_ready();
  9587. Client cli("localhost", PORT);
  9588. auto res = cli.Get("/");
  9589. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9590. EXPECT_EQ(StatusCode::OK_200, res->status);
  9591. EXPECT_EQ("ok", res->body);
  9592. EXPECT_EQ("World", res->get_header_value("Hello"));
  9593. }
  9594. #ifdef CPPHTTPLIB_SSL_ENABLED
  9595. TEST(KeepAliveTest, ReadTimeoutSSL) {
  9596. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9597. ASSERT_TRUE(svr.is_valid());
  9598. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  9599. std::this_thread::sleep_for(std::chrono::seconds(2));
  9600. res.set_content("a", "text/plain");
  9601. });
  9602. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  9603. res.set_content("b", "text/plain");
  9604. });
  9605. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9606. auto se = detail::scope_exit([&] {
  9607. svr.stop();
  9608. listen_thread.join();
  9609. ASSERT_FALSE(svr.is_running());
  9610. });
  9611. svr.wait_until_ready();
  9612. SSLClient cli("localhost", PORT);
  9613. cli.enable_server_certificate_verification(false);
  9614. cli.set_keep_alive(true);
  9615. cli.set_read_timeout(std::chrono::seconds(1));
  9616. auto resa = cli.Get("/a");
  9617. ASSERT_TRUE(!resa);
  9618. EXPECT_EQ(Error::Read, resa.error());
  9619. auto resb = cli.Get("/b");
  9620. ASSERT_TRUE(resb);
  9621. EXPECT_EQ(StatusCode::OK_200, resb->status);
  9622. EXPECT_EQ("b", resb->body);
  9623. }
  9624. #endif
  9625. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  9626. protected:
  9627. ServerTestWithAI_PASSIVE()
  9628. : cli_(HOST, PORT)
  9629. #ifdef CPPHTTPLIB_SSL_ENABLED
  9630. ,
  9631. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  9632. #endif
  9633. {
  9634. #ifdef CPPHTTPLIB_SSL_ENABLED
  9635. cli_.enable_server_certificate_verification(false);
  9636. #endif
  9637. }
  9638. virtual void SetUp() {
  9639. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9640. res.set_content("Hello World!", "text/plain");
  9641. });
  9642. t_ = thread(
  9643. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  9644. svr_.wait_until_ready();
  9645. }
  9646. virtual void TearDown() {
  9647. svr_.stop();
  9648. t_.join();
  9649. }
  9650. #ifdef CPPHTTPLIB_SSL_ENABLED
  9651. SSLClient cli_;
  9652. SSLServer svr_;
  9653. #else
  9654. Client cli_;
  9655. Server svr_;
  9656. #endif
  9657. thread t_;
  9658. };
  9659. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  9660. auto res = cli_.Get("/hi");
  9661. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9662. EXPECT_EQ(StatusCode::OK_200, res->status);
  9663. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9664. EXPECT_EQ("Hello World!", res->body);
  9665. }
  9666. class ServerUpDownTest : public ::testing::Test {
  9667. protected:
  9668. ServerUpDownTest() : cli_(HOST, PORT) {}
  9669. virtual void SetUp() {
  9670. t_ = thread([&]() {
  9671. svr_.bind_to_any_port(HOST);
  9672. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  9673. ASSERT_TRUE(svr_.listen_after_bind());
  9674. });
  9675. svr_.wait_until_ready();
  9676. }
  9677. virtual void TearDown() {
  9678. svr_.stop();
  9679. t_.join();
  9680. }
  9681. Client cli_;
  9682. Server svr_;
  9683. thread t_;
  9684. };
  9685. TEST_F(ServerUpDownTest, QuickStartStop) {
  9686. // Should not crash, especially when run with
  9687. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  9688. }
  9689. class PayloadMaxLengthTest : public ::testing::Test {
  9690. protected:
  9691. PayloadMaxLengthTest()
  9692. : cli_(HOST, PORT)
  9693. #ifdef CPPHTTPLIB_SSL_ENABLED
  9694. ,
  9695. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  9696. #endif
  9697. {
  9698. #ifdef CPPHTTPLIB_SSL_ENABLED
  9699. cli_.enable_server_certificate_verification(false);
  9700. #endif
  9701. }
  9702. virtual void SetUp() {
  9703. svr_.set_payload_max_length(8);
  9704. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  9705. res.set_content("test", "text/plain");
  9706. });
  9707. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  9708. svr_.wait_until_ready();
  9709. }
  9710. virtual void TearDown() {
  9711. svr_.stop();
  9712. t_.join();
  9713. }
  9714. #ifdef CPPHTTPLIB_SSL_ENABLED
  9715. SSLClient cli_;
  9716. SSLServer svr_;
  9717. #else
  9718. Client cli_;
  9719. Server svr_;
  9720. #endif
  9721. thread t_;
  9722. };
  9723. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  9724. auto res = cli_.Post("/test", "123456789", "text/plain");
  9725. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9726. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  9727. res = cli_.Post("/test", "12345678", "text/plain");
  9728. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9729. EXPECT_EQ(StatusCode::OK_200, res->status);
  9730. }
  9731. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  9732. // Test chunked encoding with payload exceeding the 8-byte limit
  9733. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  9734. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  9735. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9736. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  9737. }
  9738. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  9739. // Test chunked encoding with payload within the 8-byte limit
  9740. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  9741. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  9742. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9743. EXPECT_EQ(StatusCode::OK_200, res->status);
  9744. }
  9745. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  9746. // Test using send_request to send chunked data exceeding payload limit
  9747. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  9748. "Host: " +
  9749. std::string(HOST) + ":" + std::to_string(PORT) +
  9750. "\r\n"
  9751. "Transfer-Encoding: chunked\r\n"
  9752. "Connection: close\r\n"
  9753. "\r\n"
  9754. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  9755. "0123456789\r\n"
  9756. "0\r\n" // End chunk
  9757. "\r\n";
  9758. std::string response;
  9759. bool result = send_request(1, chunked_request, &response);
  9760. if (!result) {
  9761. // If send_request fails, it might be because the server closed the
  9762. // connection due to payload limit enforcement, which is acceptable
  9763. SUCCEED()
  9764. << "Server rejected oversized chunked request (connection closed)";
  9765. } else {
  9766. // If we got a response, check if it's an error response or connection was
  9767. // closed early Short response length indicates connection was closed due to
  9768. // payload limit
  9769. if (response.length() <= 10) {
  9770. SUCCEED() << "Server closed connection for oversized chunked request";
  9771. } else {
  9772. // Check for error status codes
  9773. EXPECT_TRUE(response.find("413") != std::string::npos ||
  9774. response.find("Payload Too Large") != std::string::npos ||
  9775. response.find("400") != std::string::npos);
  9776. }
  9777. }
  9778. }
  9779. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  9780. // Test request without Content-Length header exceeding payload limit
  9781. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  9782. "Host: " +
  9783. std::string(HOST) + ":" +
  9784. std::to_string(PORT) +
  9785. "\r\n"
  9786. "Connection: close\r\n"
  9787. "\r\n";
  9788. // Add payload exceeding the 8-byte limit
  9789. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  9790. request_without_content_length += large_payload;
  9791. std::string response;
  9792. bool result = send_request(1, request_without_content_length, &response);
  9793. if (!result) {
  9794. // If send_request fails, server likely closed connection due to payload
  9795. // limit
  9796. SUCCEED() << "Server rejected oversized request without Content-Length "
  9797. "(connection closed)";
  9798. } else {
  9799. // Check if server responded with error or closed connection early
  9800. if (response.length() <= 10) {
  9801. SUCCEED() << "Server closed connection for oversized request without "
  9802. "Content-Length";
  9803. } else {
  9804. // Check for error status codes
  9805. EXPECT_TRUE(response.find("413") != std::string::npos ||
  9806. response.find("Payload Too Large") != std::string::npos ||
  9807. response.find("400") != std::string::npos);
  9808. }
  9809. }
  9810. }
  9811. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  9812. // Test request without Content-Length header within payload limit
  9813. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  9814. "Host: " +
  9815. std::string(HOST) + ":" +
  9816. std::to_string(PORT) +
  9817. "\r\n"
  9818. "Connection: close\r\n"
  9819. "\r\n";
  9820. // Add payload within the 8-byte limit
  9821. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  9822. request_without_content_length += small_payload;
  9823. std::string response;
  9824. bool result = send_request(1, request_without_content_length, &response);
  9825. // For requests without Content-Length, the server may have different behavior
  9826. // The key is that it should not reject due to payload limit for small
  9827. // payloads
  9828. if (result) {
  9829. // Check for any HTTP response (success or error, but not connection closed)
  9830. if (response.length() > 10) {
  9831. SUCCEED()
  9832. << "Server processed request without Content-Length within limit";
  9833. } else {
  9834. // Short response might indicate connection closed, which is acceptable
  9835. SUCCEED() << "Server closed connection for request without "
  9836. "Content-Length (acceptable behavior)";
  9837. }
  9838. } else {
  9839. // Connection failure might be due to protocol requirements
  9840. SUCCEED() << "Connection issue with request without Content-Length "
  9841. "(environment-specific)";
  9842. }
  9843. }
  9844. class LargePayloadMaxLengthTest : public ::testing::Test {
  9845. protected:
  9846. LargePayloadMaxLengthTest()
  9847. : cli_(HOST, PORT)
  9848. #ifdef CPPHTTPLIB_SSL_ENABLED
  9849. ,
  9850. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  9851. #endif
  9852. {
  9853. #ifdef CPPHTTPLIB_SSL_ENABLED
  9854. cli_.enable_server_certificate_verification(false);
  9855. #endif
  9856. }
  9857. virtual void SetUp() {
  9858. // Set 10MB payload limit
  9859. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  9860. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  9861. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  9862. res.set_content("Large payload test", "text/plain");
  9863. });
  9864. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  9865. svr_.wait_until_ready();
  9866. }
  9867. virtual void TearDown() {
  9868. svr_.stop();
  9869. t_.join();
  9870. }
  9871. #ifdef CPPHTTPLIB_SSL_ENABLED
  9872. SSLClient cli_;
  9873. SSLServer svr_;
  9874. #else
  9875. Client cli_;
  9876. Server svr_;
  9877. #endif
  9878. thread t_;
  9879. };
  9880. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  9881. // Test chunked encoding with payload within 10MB limit
  9882. std::string medium_payload(5 * 1024 * 1024,
  9883. 'A'); // 5MB payload, within 10MB limit
  9884. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  9885. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9886. EXPECT_EQ(StatusCode::OK_200, res->status);
  9887. }
  9888. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  9889. // Test chunked encoding with payload exceeding 10MB limit
  9890. std::string large_payload(12 * 1024 * 1024,
  9891. 'B'); // 12MB payload, exceeds 10MB limit
  9892. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  9893. // Server may either return 413 or close the connection
  9894. if (res) {
  9895. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  9896. } else {
  9897. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  9898. }
  9899. }
  9900. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  9901. // Test request without Content-Length header within 10MB limit
  9902. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  9903. "Host: " +
  9904. std::string(HOST) + ":" +
  9905. std::to_string(PORT) +
  9906. "\r\n"
  9907. "Connection: close\r\n"
  9908. "\r\n";
  9909. // Add 1MB payload (within 10MB limit)
  9910. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  9911. request_without_content_length += medium_payload;
  9912. std::string response;
  9913. bool result = send_request(5, request_without_content_length, &response);
  9914. if (result) {
  9915. // Should get a proper HTTP response for payloads within limit
  9916. if (response.length() > 10) {
  9917. SUCCEED() << "Server processed 1MB request without Content-Length within "
  9918. "10MB limit";
  9919. } else {
  9920. SUCCEED() << "Server closed connection (acceptable behavior for no "
  9921. "Content-Length)";
  9922. }
  9923. } else {
  9924. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  9925. }
  9926. }
  9927. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  9928. // Test request without Content-Length header exceeding 10MB limit
  9929. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  9930. "Host: " +
  9931. std::string(HOST) + ":" +
  9932. std::to_string(PORT) +
  9933. "\r\n"
  9934. "Connection: close\r\n"
  9935. "\r\n";
  9936. // Add 12MB payload (exceeds 10MB limit)
  9937. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  9938. request_without_content_length += large_payload;
  9939. std::string response;
  9940. bool result = send_request(10, request_without_content_length, &response);
  9941. if (!result) {
  9942. // Server should close connection due to payload limit
  9943. SUCCEED() << "Server rejected 12MB request without Content-Length "
  9944. "(connection closed)";
  9945. } else {
  9946. // Check for error response
  9947. if (response.length() <= 10) {
  9948. SUCCEED()
  9949. << "Server closed connection for 12MB request exceeding 10MB limit";
  9950. } else {
  9951. EXPECT_TRUE(response.find("413") != std::string::npos ||
  9952. response.find("Payload Too Large") != std::string::npos ||
  9953. response.find("400") != std::string::npos);
  9954. }
  9955. }
  9956. }
  9957. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9958. // `payload_max_length` is not enforced on decompressed body in ContentReader
  9959. // path.
  9960. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  9961. Server svr;
  9962. const size_t LIMIT = 64 * 1024; // 64KB
  9963. svr.set_payload_max_length(LIMIT);
  9964. size_t total = 0;
  9965. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  9966. const ContentReader &content_reader) {
  9967. content_reader([&](const char * /*data*/, size_t len) {
  9968. total += len;
  9969. return true;
  9970. });
  9971. res.status = 200;
  9972. res.set_content("stream_ok", "text/plain");
  9973. });
  9974. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9975. auto se = detail::scope_exit([&] {
  9976. svr.stop();
  9977. thread.join();
  9978. ASSERT_FALSE(svr.is_running());
  9979. });
  9980. svr.wait_until_ready();
  9981. // Prepare 256KB raw data and gzip-compress it
  9982. std::string raw(256 * 1024, 'A');
  9983. std::string gz;
  9984. {
  9985. z_stream zs{};
  9986. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  9987. Z_DEFAULT_STRATEGY);
  9988. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  9989. zs.avail_in = static_cast<uInt>(raw.size());
  9990. char outbuf[4096];
  9991. int ret;
  9992. do {
  9993. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  9994. zs.avail_out = sizeof(outbuf);
  9995. ret = deflate(&zs, Z_FINISH);
  9996. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  9997. } while (ret != Z_STREAM_END);
  9998. deflateEnd(&zs);
  9999. }
  10000. Client cli(HOST, PORT);
  10001. cli.set_connection_timeout(std::chrono::seconds(5));
  10002. Headers headers = {{"Content-Encoding", "gzip"}};
  10003. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  10004. "application/octet-stream");
  10005. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10006. // Server must reject oversized decompressed payloads with 413.
  10007. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10008. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  10009. EXPECT_LE(total, LIMIT);
  10010. }
  10011. #ifndef CPPHTTPLIB_SSL_ENABLED
  10012. // For a request with neither Content-Length nor Transfer-Encoding, the
  10013. // non-SSL raw-socket fallback in read_content_core() used to hand the
  10014. // compressed wire bytes straight to the ContentReader without ever routing
  10015. // them through the decompressor, so payload_max_length_ only bounded the
  10016. // compressed size on the wire, not the decompressed size.
  10017. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  10018. Server svr;
  10019. const size_t LIMIT = 64 * 1024; // 64KB
  10020. svr.set_payload_max_length(LIMIT);
  10021. size_t total = 0;
  10022. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  10023. const ContentReader &content_reader) {
  10024. content_reader([&](const char * /*data*/, size_t len) {
  10025. total += len;
  10026. return true;
  10027. });
  10028. res.status = 200;
  10029. res.set_content("stream_ok", "text/plain");
  10030. });
  10031. auto port = svr.bind_to_any_port(HOST);
  10032. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  10033. auto se = detail::scope_exit([&] {
  10034. svr.stop();
  10035. thread.join();
  10036. ASSERT_FALSE(svr.is_running());
  10037. });
  10038. svr.wait_until_ready();
  10039. // Prepare 256KB raw data and gzip-compress it, same payload as the
  10040. // StreamingGzipDecompression test above.
  10041. std::string raw(256 * 1024, 'A');
  10042. std::string gz;
  10043. {
  10044. httplib::detail::gzip_compressor compressor;
  10045. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  10046. [&](const char *chunk, size_t len) {
  10047. gz.append(chunk, len);
  10048. return true;
  10049. });
  10050. ASSERT_TRUE(result);
  10051. }
  10052. // Send the gzip body over raw TCP with neither Content-Length nor
  10053. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  10054. // kicks in.
  10055. std::string req = "POST /stream HTTP/1.1\r\n"
  10056. "Host: " +
  10057. std::string(HOST) + ":" + std::to_string(port) +
  10058. "\r\n"
  10059. "Content-Encoding: gzip\r\n"
  10060. "Connection: close\r\n"
  10061. "\r\n" +
  10062. gz;
  10063. std::string response;
  10064. ASSERT_TRUE(send_request(5, req, &response, port));
  10065. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  10066. EXPECT_LE(total, LIMIT);
  10067. }
  10068. #endif
  10069. #endif
  10070. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  10071. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  10072. // the payload must be passed through untouched instead of being rejected.
  10073. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  10074. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  10075. Server svr;
  10076. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  10077. res.set_content(body, "image/jpeg");
  10078. res.set_header("Content-Encoding", "UTF-8");
  10079. });
  10080. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  10081. res.set_content(body, "image/jpeg");
  10082. res.set_header("Content-Encoding", "identity");
  10083. });
  10084. svr.Post("/echo", [](const Request &req, Response &res) {
  10085. res.set_content(req.body, "image/jpeg");
  10086. });
  10087. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10088. auto se = detail::scope_exit([&] {
  10089. svr.stop();
  10090. t.join();
  10091. ASSERT_FALSE(svr.is_running());
  10092. });
  10093. svr.wait_until_ready();
  10094. Client cli(HOST, PORT);
  10095. {
  10096. auto res = cli.Get("/image");
  10097. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10098. EXPECT_EQ(StatusCode::OK_200, res->status);
  10099. EXPECT_EQ(body, res->body);
  10100. }
  10101. {
  10102. auto res = cli.Get("/identity");
  10103. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10104. EXPECT_EQ(StatusCode::OK_200, res->status);
  10105. EXPECT_EQ(body, res->body);
  10106. }
  10107. {
  10108. // The same applies to a request body reaching the server.
  10109. Headers headers = {{"Content-Encoding", "UTF-8"}};
  10110. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  10111. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10112. EXPECT_EQ(StatusCode::OK_200, res->status);
  10113. EXPECT_EQ(body, res->body);
  10114. }
  10115. }
  10116. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  10117. // gzip-encoded response even when the build has no zlib support.
  10118. static const char GZIPPED_HELLO_WORLD[] = {
  10119. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  10120. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  10121. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  10122. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  10123. // A content coding is a whole token, not something the field value merely
  10124. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  10125. // as "fibre" look like Brotli, and turned a multi-coding value like
  10126. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  10127. // it was never meant to see.
  10128. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  10129. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  10130. Server svr;
  10131. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  10132. res.set_content(body, "image/jpeg");
  10133. res.set_header("Content-Encoding", "fibre");
  10134. });
  10135. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  10136. res.set_content(body, "image/jpeg");
  10137. res.set_header("Content-Encoding", "gzip, br");
  10138. });
  10139. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  10140. res.set_content(body, "image/jpeg");
  10141. res.set_header("Content-Encoding", "x-zstd-ish");
  10142. });
  10143. auto port = svr.bind_to_any_port(HOST);
  10144. thread t = thread([&]() { svr.listen_after_bind(); });
  10145. auto se = detail::scope_exit([&] {
  10146. svr.stop();
  10147. t.join();
  10148. ASSERT_FALSE(svr.is_running());
  10149. });
  10150. svr.wait_until_ready();
  10151. Client cli(HOST, port);
  10152. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  10153. auto res = cli.Get(path);
  10154. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  10155. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  10156. // Not a coding we recognize, so the payload comes back untouched
  10157. EXPECT_EQ(body, res->body) << path;
  10158. }
  10159. }
  10160. // A content coding cpp-httplib recognizes but was not built with must be
  10161. // reported as such. Handing the still-compressed payload back to the caller
  10162. // would silently corrupt it.
  10163. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  10164. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  10165. Server svr;
  10166. // "image/jpeg" keeps the server from applying a content coding of its own,
  10167. // so the hand-crafted Content-Encoding below survives.
  10168. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  10169. res.set_content(gzipped, "image/jpeg");
  10170. res.set_header("Content-Encoding", "gzip");
  10171. });
  10172. // Content codings are case-insensitive (RFC 9110 8.4.1).
  10173. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  10174. res.set_content(gzipped, "image/jpeg");
  10175. res.set_header("Content-Encoding", "GZIP");
  10176. });
  10177. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10178. auto se = detail::scope_exit([&] {
  10179. svr.stop();
  10180. t.join();
  10181. ASSERT_FALSE(svr.is_running());
  10182. });
  10183. svr.wait_until_ready();
  10184. Client cli(HOST, PORT);
  10185. {
  10186. auto res = cli.Get("/gzipped");
  10187. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10188. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10189. EXPECT_EQ("Hello World!", res->body);
  10190. #else
  10191. ASSERT_FALSE(res);
  10192. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  10193. #endif
  10194. }
  10195. {
  10196. // open_stream() must behave the same way.
  10197. auto handle = cli.open_stream("GET", "/gzipped");
  10198. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10199. ASSERT_TRUE(handle.is_valid());
  10200. std::string received;
  10201. char buf[256];
  10202. ssize_t n;
  10203. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  10204. received.append(buf, static_cast<size_t>(n));
  10205. }
  10206. EXPECT_EQ("Hello World!", received);
  10207. #else
  10208. EXPECT_FALSE(handle.is_valid());
  10209. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  10210. #endif
  10211. }
  10212. {
  10213. // A differently-cased coding must not be mistaken for an unknown one, or
  10214. // the body would be handed back still compressed.
  10215. auto res = cli.Get("/gzipped-uppercase");
  10216. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10217. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10218. EXPECT_EQ("Hello World!", res->body);
  10219. #else
  10220. ASSERT_FALSE(res);
  10221. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  10222. #endif
  10223. }
  10224. }
  10225. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  10226. // the same message as the comma-joined one, so both have to be read the same
  10227. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  10228. // single gzip coding, and a body the sender says was encoded twice was handed
  10229. // back after one pass, still compressed but presented as decoded.
  10230. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  10231. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  10232. Server svr;
  10233. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  10234. res.set_content(body, "image/jpeg");
  10235. res.headers.emplace("Content-Encoding", "gzip");
  10236. res.headers.emplace("Content-Encoding", "gzip");
  10237. });
  10238. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  10239. res.set_content(body, "image/jpeg");
  10240. res.set_header("Content-Encoding", "gzip, gzip");
  10241. });
  10242. auto port = svr.bind_to_any_port(HOST);
  10243. thread t = thread([&]() { svr.listen_after_bind(); });
  10244. auto se = detail::scope_exit([&] {
  10245. svr.stop();
  10246. t.join();
  10247. ASSERT_FALSE(svr.is_running());
  10248. });
  10249. svr.wait_until_ready();
  10250. Client cli(HOST, port);
  10251. // Two codings is not something cpp-httplib decodes, so both representations
  10252. // take the pass-through path rather than one of them being gunzipped once.
  10253. for (const char *path : {"/split", "/joined"}) {
  10254. auto res = cli.Get(path);
  10255. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  10256. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  10257. EXPECT_EQ(body, res->body) << path;
  10258. }
  10259. }
  10260. // Regression test for DoS vulnerability: a malicious server sending a response
  10261. // without Content-Length header must not cause unbounded memory consumption on
  10262. // the client side. The client should stop reading after a reasonable limit,
  10263. // similar to the server-side set_payload_max_length protection.
  10264. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  10265. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  10266. #ifndef _WIN32
  10267. signal(SIGPIPE, SIG_IGN);
  10268. #endif
  10269. auto server_thread = std::thread([] {
  10270. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  10271. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10272. default_socket_options(srv);
  10273. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  10274. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  10275. sockaddr_in addr{};
  10276. addr.sin_family = AF_INET;
  10277. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  10278. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10279. int opt = 1;
  10280. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  10281. #ifdef _WIN32
  10282. reinterpret_cast<const char *>(&opt),
  10283. #else
  10284. &opt,
  10285. #endif
  10286. sizeof(opt));
  10287. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10288. ::listen(srv, 1);
  10289. sockaddr_in cli_addr{};
  10290. socklen_t cli_len = sizeof(cli_addr);
  10291. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10292. if (cli != INVALID_SOCKET) {
  10293. char buf[4096];
  10294. ::recv(cli, buf, sizeof(buf), 0);
  10295. // Malicious response: no Content-Length, no chunked encoding
  10296. std::string response_header = "HTTP/1.1 200 OK\r\n"
  10297. "Connection: close\r\n"
  10298. "\r\n";
  10299. ::send(cli,
  10300. #ifdef _WIN32
  10301. static_cast<const char *>(response_header.c_str()),
  10302. static_cast<int>(response_header.size()),
  10303. #else
  10304. response_header.c_str(), response_header.size(),
  10305. #endif
  10306. 0);
  10307. // Send 10MB of data
  10308. std::string chunk(64 * 1024, 'A');
  10309. size_t total_sent = 0;
  10310. while (total_sent < MALICIOUS_DATA_SIZE) {
  10311. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  10312. auto sent = ::send(cli,
  10313. #ifdef _WIN32
  10314. static_cast<const char *>(chunk.c_str()),
  10315. static_cast<int>(to_send),
  10316. #else
  10317. chunk.c_str(), to_send,
  10318. #endif
  10319. 0);
  10320. if (sent <= 0) break;
  10321. total_sent += static_cast<size_t>(sent);
  10322. }
  10323. detail::close_socket(cli);
  10324. }
  10325. detail::close_socket(srv);
  10326. });
  10327. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10328. size_t total_read = 0;
  10329. {
  10330. Client cli("127.0.0.1", PORT + 2);
  10331. cli.set_read_timeout(5, 0);
  10332. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  10333. auto stream = cli.open_stream("GET", "/malicious");
  10334. ASSERT_TRUE(stream.is_valid());
  10335. char buffer[64 * 1024];
  10336. ssize_t n;
  10337. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  10338. total_read += static_cast<size_t>(n);
  10339. }
  10340. } // StreamHandle and Client destroyed here, closing the socket
  10341. server_thread.join();
  10342. // With set_payload_max_length, the client must stop reading before consuming
  10343. // all 10MB. The read loop should be cut off at or near the configured limit.
  10344. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  10345. << "Client read " << total_read << " bytes, exceeding the configured "
  10346. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  10347. }
  10348. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  10349. // the entire response body without truncation.
  10350. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  10351. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  10352. #ifndef _WIN32
  10353. signal(SIGPIPE, SIG_IGN);
  10354. #endif
  10355. auto server_thread = std::thread([] {
  10356. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10357. default_socket_options(srv);
  10358. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  10359. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  10360. sockaddr_in addr{};
  10361. addr.sin_family = AF_INET;
  10362. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  10363. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10364. int opt = 1;
  10365. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  10366. #ifdef _WIN32
  10367. reinterpret_cast<const char *>(&opt),
  10368. #else
  10369. &opt,
  10370. #endif
  10371. sizeof(opt));
  10372. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10373. ::listen(srv, 1);
  10374. sockaddr_in cli_addr{};
  10375. socklen_t cli_len = sizeof(cli_addr);
  10376. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10377. if (cli != INVALID_SOCKET) {
  10378. char buf[4096];
  10379. ::recv(cli, buf, sizeof(buf), 0);
  10380. std::string response_header = "HTTP/1.1 200 OK\r\n"
  10381. "Connection: close\r\n"
  10382. "\r\n";
  10383. ::send(cli,
  10384. #ifdef _WIN32
  10385. static_cast<const char *>(response_header.c_str()),
  10386. static_cast<int>(response_header.size()),
  10387. #else
  10388. response_header.c_str(), response_header.size(),
  10389. #endif
  10390. 0);
  10391. std::string chunk(64 * 1024, 'A');
  10392. size_t total_sent = 0;
  10393. while (total_sent < DATA_SIZE) {
  10394. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  10395. auto sent = ::send(cli,
  10396. #ifdef _WIN32
  10397. static_cast<const char *>(chunk.c_str()),
  10398. static_cast<int>(to_send),
  10399. #else
  10400. chunk.c_str(), to_send,
  10401. #endif
  10402. 0);
  10403. if (sent <= 0) break;
  10404. total_sent += static_cast<size_t>(sent);
  10405. }
  10406. #ifdef _WIN32
  10407. ::shutdown(cli, SD_SEND);
  10408. #else
  10409. ::shutdown(cli, SHUT_WR);
  10410. #endif
  10411. // Drain until the client closes its end, ensuring all data is delivered
  10412. char drain[1024];
  10413. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  10414. detail::close_socket(cli);
  10415. }
  10416. detail::close_socket(srv);
  10417. });
  10418. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10419. size_t total_read = 0;
  10420. {
  10421. Client cli("127.0.0.1", PORT + 2);
  10422. cli.set_read_timeout(5, 0);
  10423. cli.set_payload_max_length(0); // 0 means no limit
  10424. auto stream = cli.open_stream("GET", "/data");
  10425. ASSERT_TRUE(stream.is_valid());
  10426. char buffer[64 * 1024];
  10427. ssize_t n;
  10428. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  10429. total_read += static_cast<size_t>(n);
  10430. }
  10431. }
  10432. server_thread.join();
  10433. EXPECT_EQ(total_read, DATA_SIZE)
  10434. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  10435. << " bytes without truncation, but only read " << total_read << " bytes.";
  10436. }
  10437. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  10438. // enormous Content-Length must not cause the client to pre-allocate a huge
  10439. // response body buffer. The reservation is capped at payload_max_length_, and
  10440. // the read itself fails when the body exceeds the limit.
  10441. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  10442. #ifndef _WIN32
  10443. signal(SIGPIPE, SIG_IGN);
  10444. #endif
  10445. auto server_thread = std::thread([] {
  10446. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10447. default_socket_options(srv);
  10448. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  10449. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  10450. sockaddr_in addr{};
  10451. addr.sin_family = AF_INET;
  10452. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  10453. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10454. int opt = 1;
  10455. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  10456. #ifdef _WIN32
  10457. reinterpret_cast<const char *>(&opt),
  10458. #else
  10459. &opt,
  10460. #endif
  10461. sizeof(opt));
  10462. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10463. ::listen(srv, 1);
  10464. sockaddr_in cli_addr{};
  10465. socklen_t cli_len = sizeof(cli_addr);
  10466. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10467. if (cli != INVALID_SOCKET) {
  10468. char buf[4096];
  10469. ::recv(cli, buf, sizeof(buf), 0);
  10470. // Malicious response: claim a 20GB body but send only a tiny payload.
  10471. std::string response = "HTTP/1.1 200 OK\r\n"
  10472. "Content-Length: 20000000000\r\n"
  10473. "\r\n"
  10474. "abc";
  10475. ::send(cli,
  10476. #ifdef _WIN32
  10477. static_cast<const char *>(response.c_str()),
  10478. static_cast<int>(response.size()),
  10479. #else
  10480. response.c_str(), response.size(),
  10481. #endif
  10482. 0);
  10483. detail::close_socket(cli);
  10484. }
  10485. detail::close_socket(srv);
  10486. });
  10487. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10488. {
  10489. Client cli("127.0.0.1", PORT + 2);
  10490. cli.set_read_timeout(5, 0);
  10491. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  10492. // result in a 20GB pre-allocation. The Get() call is expected to fail
  10493. // (server claims more bytes than payload_max_length permits), but it must
  10494. // not exhaust memory before getting there.
  10495. auto res = cli.Get("/malicious");
  10496. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  10497. }
  10498. server_thread.join();
  10499. }
  10500. // Verify that content_receiver bypasses the default payload_max_length,
  10501. // allowing streaming downloads larger than 100MB without requiring an explicit
  10502. // set_payload_max_length call.
  10503. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  10504. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  10505. #ifndef _WIN32
  10506. signal(SIGPIPE, SIG_IGN);
  10507. #endif
  10508. auto server_thread = std::thread([] {
  10509. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10510. default_socket_options(srv);
  10511. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  10512. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  10513. sockaddr_in addr{};
  10514. addr.sin_family = AF_INET;
  10515. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  10516. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10517. int opt = 1;
  10518. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  10519. #ifdef _WIN32
  10520. reinterpret_cast<const char *>(&opt),
  10521. #else
  10522. &opt,
  10523. #endif
  10524. sizeof(opt));
  10525. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10526. ::listen(srv, 1);
  10527. sockaddr_in cli_addr{};
  10528. socklen_t cli_len = sizeof(cli_addr);
  10529. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10530. if (cli != INVALID_SOCKET) {
  10531. char buf[4096];
  10532. ::recv(cli, buf, sizeof(buf), 0);
  10533. // Response with Content-Length larger than default 100MB limit
  10534. auto content_length = std::to_string(DATA_SIZE);
  10535. std::string response_header = "HTTP/1.1 200 OK\r\n"
  10536. "Content-Length: " +
  10537. content_length +
  10538. "\r\n"
  10539. "Connection: close\r\n"
  10540. "\r\n";
  10541. ::send(cli,
  10542. #ifdef _WIN32
  10543. static_cast<const char *>(response_header.c_str()),
  10544. static_cast<int>(response_header.size()),
  10545. #else
  10546. response_header.c_str(), response_header.size(),
  10547. #endif
  10548. 0);
  10549. std::string chunk(64 * 1024, 'A');
  10550. size_t total_sent = 0;
  10551. while (total_sent < DATA_SIZE) {
  10552. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  10553. auto sent = ::send(cli,
  10554. #ifdef _WIN32
  10555. static_cast<const char *>(chunk.c_str()),
  10556. static_cast<int>(to_send),
  10557. #else
  10558. chunk.c_str(), to_send,
  10559. #endif
  10560. 0);
  10561. if (sent <= 0) break;
  10562. total_sent += static_cast<size_t>(sent);
  10563. }
  10564. detail::close_socket(cli);
  10565. }
  10566. detail::close_socket(srv);
  10567. });
  10568. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10569. size_t total_received = 0;
  10570. {
  10571. Client cli("127.0.0.1", PORT + 2);
  10572. cli.set_read_timeout(10, 0);
  10573. // Do NOT call set_payload_max_length — use the default 100MB limit
  10574. auto res =
  10575. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  10576. total_received += data_length;
  10577. return true;
  10578. });
  10579. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10580. EXPECT_EQ(StatusCode::OK_200, res->status);
  10581. }
  10582. server_thread.join();
  10583. EXPECT_EQ(total_received, DATA_SIZE)
  10584. << "With content_receiver, the client should read all " << DATA_SIZE
  10585. << " bytes despite the default 100MB payload_max_length, but only read "
  10586. << total_received << " bytes.";
  10587. }
  10588. // Verify that an explicit set_payload_max_length smaller than the response is
  10589. // enforced even when a content_receiver is used.
  10590. TEST(ClientVulnerabilityTest,
  10591. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  10592. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  10593. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  10594. #ifndef _WIN32
  10595. signal(SIGPIPE, SIG_IGN);
  10596. #endif
  10597. auto server_thread = std::thread([] {
  10598. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10599. default_socket_options(srv);
  10600. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  10601. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  10602. sockaddr_in addr{};
  10603. addr.sin_family = AF_INET;
  10604. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  10605. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10606. int opt = 1;
  10607. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  10608. #ifdef _WIN32
  10609. reinterpret_cast<const char *>(&opt),
  10610. #else
  10611. &opt,
  10612. #endif
  10613. sizeof(opt));
  10614. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10615. ::listen(srv, 1);
  10616. sockaddr_in cli_addr{};
  10617. socklen_t cli_len = sizeof(cli_addr);
  10618. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10619. if (cli != INVALID_SOCKET) {
  10620. char buf[4096];
  10621. ::recv(cli, buf, sizeof(buf), 0);
  10622. auto content_length = std::to_string(DATA_SIZE);
  10623. std::string response_header = "HTTP/1.1 200 OK\r\n"
  10624. "Content-Length: " +
  10625. content_length +
  10626. "\r\n"
  10627. "Connection: close\r\n"
  10628. "\r\n";
  10629. ::send(cli,
  10630. #ifdef _WIN32
  10631. static_cast<const char *>(response_header.c_str()),
  10632. static_cast<int>(response_header.size()),
  10633. #else
  10634. response_header.c_str(), response_header.size(),
  10635. #endif
  10636. 0);
  10637. std::string chunk(64 * 1024, 'A');
  10638. size_t total_sent = 0;
  10639. while (total_sent < DATA_SIZE) {
  10640. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  10641. auto sent = ::send(cli,
  10642. #ifdef _WIN32
  10643. static_cast<const char *>(chunk.c_str()),
  10644. static_cast<int>(to_send),
  10645. #else
  10646. chunk.c_str(), to_send,
  10647. #endif
  10648. 0);
  10649. if (sent <= 0) break;
  10650. total_sent += static_cast<size_t>(sent);
  10651. }
  10652. detail::close_socket(cli);
  10653. }
  10654. detail::close_socket(srv);
  10655. });
  10656. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10657. size_t total_received = 0;
  10658. {
  10659. Client cli("127.0.0.1", PORT + 2);
  10660. cli.set_read_timeout(10, 0);
  10661. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  10662. auto res =
  10663. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  10664. total_received += data_length;
  10665. return true;
  10666. });
  10667. // Should fail because 200MB exceeds the explicit 150MB limit
  10668. EXPECT_FALSE(res);
  10669. }
  10670. server_thread.join();
  10671. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  10672. << "Client with content_receiver should respect the explicit "
  10673. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  10674. << total_received << " bytes.";
  10675. }
  10676. // Verify that an explicit set_payload_max_length larger than the response
  10677. // allows the content_receiver to read all data successfully.
  10678. TEST(ClientVulnerabilityTest,
  10679. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  10680. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  10681. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  10682. #ifndef _WIN32
  10683. signal(SIGPIPE, SIG_IGN);
  10684. #endif
  10685. auto server_thread = std::thread([] {
  10686. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10687. default_socket_options(srv);
  10688. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  10689. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  10690. sockaddr_in addr{};
  10691. addr.sin_family = AF_INET;
  10692. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  10693. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10694. int opt = 1;
  10695. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  10696. #ifdef _WIN32
  10697. reinterpret_cast<const char *>(&opt),
  10698. #else
  10699. &opt,
  10700. #endif
  10701. sizeof(opt));
  10702. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10703. ::listen(srv, 1);
  10704. sockaddr_in cli_addr{};
  10705. socklen_t cli_len = sizeof(cli_addr);
  10706. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10707. if (cli != INVALID_SOCKET) {
  10708. char buf[4096];
  10709. ::recv(cli, buf, sizeof(buf), 0);
  10710. auto content_length = std::to_string(DATA_SIZE);
  10711. std::string response_header = "HTTP/1.1 200 OK\r\n"
  10712. "Content-Length: " +
  10713. content_length +
  10714. "\r\n"
  10715. "Connection: close\r\n"
  10716. "\r\n";
  10717. ::send(cli,
  10718. #ifdef _WIN32
  10719. static_cast<const char *>(response_header.c_str()),
  10720. static_cast<int>(response_header.size()),
  10721. #else
  10722. response_header.c_str(), response_header.size(),
  10723. #endif
  10724. 0);
  10725. std::string chunk(64 * 1024, 'A');
  10726. size_t total_sent = 0;
  10727. while (total_sent < DATA_SIZE) {
  10728. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  10729. auto sent = ::send(cli,
  10730. #ifdef _WIN32
  10731. static_cast<const char *>(chunk.c_str()),
  10732. static_cast<int>(to_send),
  10733. #else
  10734. chunk.c_str(), to_send,
  10735. #endif
  10736. 0);
  10737. if (sent <= 0) break;
  10738. total_sent += static_cast<size_t>(sent);
  10739. }
  10740. #ifdef _WIN32
  10741. ::shutdown(cli, SD_SEND);
  10742. #else
  10743. ::shutdown(cli, SHUT_WR);
  10744. #endif
  10745. char drain[1024];
  10746. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  10747. detail::close_socket(cli);
  10748. }
  10749. detail::close_socket(srv);
  10750. });
  10751. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10752. size_t total_received = 0;
  10753. {
  10754. Client cli("127.0.0.1", PORT + 2);
  10755. cli.set_read_timeout(10, 0);
  10756. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  10757. auto res =
  10758. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  10759. total_received += data_length;
  10760. return true;
  10761. });
  10762. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10763. EXPECT_EQ(StatusCode::OK_200, res->status);
  10764. }
  10765. server_thread.join();
  10766. EXPECT_EQ(total_received, DATA_SIZE)
  10767. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  10768. << " bytes (larger than " << DATA_SIZE
  10769. << " bytes response), content_receiver should read all data, but only "
  10770. "read "
  10771. << total_received << " bytes.";
  10772. }
  10773. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  10774. // Regression test for "zip bomb" attack on the client side: a malicious server
  10775. // sends a small gzip-compressed response that decompresses to a huge payload.
  10776. // The client must enforce payload_max_length on the decompressed size.
  10777. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  10778. constexpr size_t DECOMPRESSED_SIZE =
  10779. 10 * 1024 * 1024; // 10MB after decompression
  10780. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  10781. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  10782. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  10783. std::string compressed;
  10784. {
  10785. httplib::detail::gzip_compressor compressor;
  10786. bool ok =
  10787. compressor.compress(uncompressed.data(), uncompressed.size(),
  10788. /*last=*/true, [&](const char *buf, size_t len) {
  10789. compressed.append(buf, len);
  10790. return true;
  10791. });
  10792. ASSERT_TRUE(ok);
  10793. }
  10794. // Sanity: compressed data should be much smaller than the decompressed size
  10795. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  10796. #ifndef _WIN32
  10797. signal(SIGPIPE, SIG_IGN);
  10798. #endif
  10799. // Set up the listening socket in the main thread so the server is guaranteed
  10800. // to be ready before the client connects (eliminates race condition).
  10801. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10802. default_socket_options(srv);
  10803. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  10804. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  10805. sockaddr_in addr{};
  10806. addr.sin_family = AF_INET;
  10807. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  10808. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10809. int opt = 1;
  10810. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  10811. #ifdef _WIN32
  10812. reinterpret_cast<const char *>(&opt),
  10813. #else
  10814. &opt,
  10815. #endif
  10816. sizeof(opt));
  10817. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  10818. ASSERT_EQ(0, ::listen(srv, 1));
  10819. auto server_thread = std::thread([&compressed, srv] {
  10820. sockaddr_in cli_addr{};
  10821. socklen_t cli_len = sizeof(cli_addr);
  10822. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10823. if (cli != INVALID_SOCKET) {
  10824. // Read the full HTTP request (until \r\n\r\n)
  10825. char buf[4096];
  10826. size_t total = 0;
  10827. while (total < sizeof(buf)) {
  10828. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  10829. if (n <= 0) break;
  10830. total += static_cast<size_t>(n);
  10831. // Check for end of headers
  10832. if (total >= 4) {
  10833. std::string req(buf, total);
  10834. if (req.find("\r\n\r\n") != std::string::npos) break;
  10835. }
  10836. }
  10837. // Malicious response: gzip-compressed body, no Content-Length
  10838. std::string response_header = "HTTP/1.1 200 OK\r\n"
  10839. "Content-Encoding: gzip\r\n"
  10840. "Connection: close\r\n"
  10841. "\r\n";
  10842. ::send(cli,
  10843. #ifdef _WIN32
  10844. static_cast<const char *>(response_header.c_str()),
  10845. static_cast<int>(response_header.size()),
  10846. #else
  10847. response_header.c_str(), response_header.size(),
  10848. #endif
  10849. 0);
  10850. // Send the compressed payload (small on the wire, huge when decompressed)
  10851. size_t total_sent = 0;
  10852. while (total_sent < compressed.size()) {
  10853. auto to_send = std::min(compressed.size() - total_sent,
  10854. static_cast<size_t>(64 * 1024));
  10855. auto sent =
  10856. ::send(cli,
  10857. #ifdef _WIN32
  10858. static_cast<const char *>(compressed.c_str() + total_sent),
  10859. static_cast<int>(to_send),
  10860. #else
  10861. compressed.c_str() + total_sent, to_send,
  10862. #endif
  10863. 0);
  10864. if (sent <= 0) break;
  10865. total_sent += static_cast<size_t>(sent);
  10866. }
  10867. detail::close_socket(cli);
  10868. }
  10869. });
  10870. auto se = detail::scope_exit([&] {
  10871. detail::close_socket(srv);
  10872. server_thread.join();
  10873. });
  10874. size_t total_decompressed = 0;
  10875. {
  10876. Client cli("127.0.0.1", PORT + 3);
  10877. cli.set_read_timeout(5, 0);
  10878. cli.set_decompress(true);
  10879. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  10880. auto stream = cli.open_stream("GET", "/zipbomb");
  10881. ASSERT_TRUE(stream.is_valid());
  10882. char buffer[64 * 1024];
  10883. ssize_t n;
  10884. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  10885. total_decompressed += static_cast<size_t>(n);
  10886. }
  10887. }
  10888. // The decompressed size must be capped by payload_max_length. Without
  10889. // protection, the client would decompress the full 10MB from a tiny
  10890. // compressed payload, enabling a zip bomb DoS attack.
  10891. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  10892. << "Client decompressed " << total_decompressed
  10893. << " bytes from a gzip response. The decompressed size should be "
  10894. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  10895. }
  10896. #endif
  10897. TEST(HostAndPortPropertiesTest, NoSSL) {
  10898. httplib::Client cli("www.google.com", 1234);
  10899. ASSERT_EQ("www.google.com", cli.host());
  10900. ASSERT_EQ(1234, cli.port());
  10901. }
  10902. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  10903. httplib::Client cli("www.google.com:1234");
  10904. ASSERT_EQ("www.google.com", cli.host());
  10905. ASSERT_EQ(1234, cli.port());
  10906. }
  10907. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  10908. // Port number that overflows int — should not crash, client becomes invalid
  10909. httplib::Client cli("http://www.google.com:99999999999999999999");
  10910. ASSERT_FALSE(cli.is_valid());
  10911. }
  10912. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  10913. // Port 99999 exceeds valid range (1-65535) — should not crash
  10914. httplib::Client cli("http://www.google.com:99999");
  10915. ASSERT_FALSE(cli.is_valid());
  10916. }
  10917. #ifdef CPPHTTPLIB_SSL_ENABLED
  10918. TEST(HostAndPortPropertiesTest, SSL) {
  10919. httplib::SSLClient cli("www.google.com");
  10920. ASSERT_EQ("www.google.com", cli.host());
  10921. ASSERT_EQ(443, cli.port());
  10922. }
  10923. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  10924. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  10925. std::string cert;
  10926. read_file(CA_CERT_FILE, cert);
  10927. httplib::SSLClient httplib_client("www.google.com");
  10928. // Load CA store first time
  10929. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  10930. // Load CA store second time (update)
  10931. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  10932. // Verify client is still valid and can make connections
  10933. httplib_client.enable_server_certificate_verification(true);
  10934. auto res = httplib_client.Get("/");
  10935. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10936. // Google may return 200 or 301 depending on various factors
  10937. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  10938. res->status == StatusCode::MovedPermanently_301);
  10939. }
  10940. TEST(SSLClientTest, ServerNameIndication_Online) {
  10941. auto host = "httpbingo.org";
  10942. auto path = std::string{"/get"};
  10943. SSLClient cli(host, 443);
  10944. auto res = cli.Get(path);
  10945. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10946. ASSERT_EQ(StatusCode::OK_200, res->status);
  10947. }
  10948. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  10949. // Use a site that will cause SSL verification failure due to self-signed cert
  10950. SSLClient cli("self-signed.badssl.com", 443);
  10951. cli.enable_server_certificate_verification(true);
  10952. auto res = cli.Get("/");
  10953. ASSERT_TRUE(!res);
  10954. EXPECT_EQ(Error::SSLServerVerification, res.error());
  10955. // Verify backend error is captured for SSLServerVerification
  10956. // This occurs when certificate verification fails
  10957. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  10958. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  10959. EXPECT_NE(0UL, res.ssl_backend_error());
  10960. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10961. // For OpenSSL, ssl_error is 0 for verification errors
  10962. EXPECT_EQ(0, res.ssl_error());
  10963. #if !defined(_WIN32) || \
  10964. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  10965. // On non-Windows or when Windows Schannel is disabled, the error comes
  10966. // from OpenSSL's verification
  10967. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  10968. res.ssl_backend_error());
  10969. #endif
  10970. #endif
  10971. }
  10972. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  10973. // Use a site where hostname doesn't match the certificate
  10974. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  10975. SSLClient cli("wrong.host.badssl.com", 443);
  10976. cli.enable_server_certificate_verification(true);
  10977. cli.enable_server_hostname_verification(true);
  10978. auto res = cli.Get("/");
  10979. ASSERT_TRUE(!res);
  10980. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  10981. // Verify backend error is captured for hostname verification failure
  10982. EXPECT_NE(0UL, res.ssl_backend_error());
  10983. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10984. // For OpenSSL, ssl_error is 0 for verification errors
  10985. EXPECT_EQ(0, res.ssl_error());
  10986. #if !defined(_WIN32) || \
  10987. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  10988. // On non-Windows or when Windows Schannel is disabled, the error comes
  10989. // from OpenSSL's hostname verification
  10990. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  10991. res.ssl_backend_error());
  10992. #endif
  10993. #endif
  10994. }
  10995. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  10996. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  10997. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  10998. SSLClient cli("www.google.com", 443);
  10999. cli.enable_server_certificate_verification(true);
  11000. auto res = cli.Get("/");
  11001. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  11002. }
  11003. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  11004. SSLClient cli("www.google.com", 443);
  11005. cli.enable_server_certificate_verification(true);
  11006. cli.enable_windows_certificate_verification(false);
  11007. auto res = cli.Get("/");
  11008. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  11009. }
  11010. #endif
  11011. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  11012. Client cli("https://google.com");
  11013. auto res = cli.Get("/");
  11014. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11015. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11016. }
  11017. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  11018. SSLClient cli("google.com");
  11019. cli.set_ca_cert_path(CA_CERT_FILE);
  11020. auto res = cli.Get("/");
  11021. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11022. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11023. }
  11024. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  11025. SSLClient cli("google.com");
  11026. cli.enable_server_certificate_verification(true);
  11027. cli.set_ca_cert_path("hello");
  11028. auto res = cli.Get("/");
  11029. ASSERT_TRUE(!res);
  11030. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  11031. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  11032. // should be set
  11033. EXPECT_EQ(0, res.ssl_error());
  11034. // Verify backend error is captured for SSLLoadingCerts
  11035. // This error occurs when loading CA certificates fails
  11036. EXPECT_NE(0UL, res.ssl_backend_error());
  11037. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11038. // OpenSSL specific error codes:
  11039. // > openssl errstr 0x80000002
  11040. // error:80000002:system library::No such file or directory
  11041. // > openssl errstr 0xA000126
  11042. // error:0A000126:SSL routines::unexpected eof while reading
  11043. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  11044. res.ssl_backend_error() == 0xA000126);
  11045. #endif
  11046. }
  11047. TEST(SSLClientTest, ServerCertificateVerification4) {
  11048. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11049. ASSERT_TRUE(svr.is_valid());
  11050. svr.Get("/test", [&](const Request &, Response &res) {
  11051. res.set_content("test", "text/plain");
  11052. svr.stop();
  11053. ASSERT_TRUE(true);
  11054. });
  11055. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11056. auto se = detail::scope_exit([&] {
  11057. t.join();
  11058. ASSERT_FALSE(svr.is_running());
  11059. });
  11060. svr.wait_until_ready();
  11061. SSLClient cli("127.0.0.1", PORT);
  11062. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  11063. cli.enable_server_certificate_verification(true);
  11064. cli.set_connection_timeout(30);
  11065. auto res = cli.Get("/test");
  11066. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11067. ASSERT_EQ(StatusCode::OK_200, res->status);
  11068. }
  11069. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  11070. std::string cert;
  11071. read_file(CA_CERT_FILE, cert);
  11072. SSLClient cli("google.com");
  11073. cli.load_ca_cert_store(cert.data(), cert.size());
  11074. const auto res = cli.Get("/");
  11075. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11076. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11077. }
  11078. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  11079. // clang-format off
  11080. static constexpr char cert[] =
  11081. "GlobalSign Root CA\n"
  11082. "==================\n"
  11083. "-----BEGIN CERTIFICATE-----\n"
  11084. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  11085. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  11086. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  11087. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  11088. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  11089. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  11090. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  11091. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  11092. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  11093. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  11094. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  11095. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  11096. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  11097. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  11098. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  11099. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  11100. "-----END CERTIFICATE-----\n";
  11101. // clang-format on
  11102. SSLClient cli("google.com");
  11103. cli.load_ca_cert_store(cert, sizeof(cert));
  11104. const auto res = cli.Get("/");
  11105. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11106. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11107. }
  11108. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  11109. SSLClient cli("www.youtube.com");
  11110. cli.set_ca_cert_path(CA_CERT_FILE);
  11111. cli.enable_server_certificate_verification(true);
  11112. cli.set_follow_location(true);
  11113. auto res = cli.Get("/");
  11114. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11115. ASSERT_EQ(StatusCode::OK_200, res->status);
  11116. }
  11117. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  11118. SSLClient cli("wWw.YouTube.Com");
  11119. cli.set_ca_cert_path(CA_CERT_FILE);
  11120. cli.enable_server_certificate_verification(true);
  11121. cli.enable_server_hostname_verification(true);
  11122. cli.set_follow_location(true);
  11123. auto res = cli.Get("/");
  11124. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11125. ASSERT_EQ(StatusCode::OK_200, res->status);
  11126. }
  11127. TEST(SSLClientTest, HostNameMatchCase_Online) {
  11128. SSLClient cli("gOoGlE.COm");
  11129. cli.enable_server_certificate_verification(true);
  11130. cli.enable_server_hostname_verification(true);
  11131. cli.set_follow_location(true);
  11132. auto res = cli.Get("/");
  11133. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11134. ASSERT_EQ(StatusCode::OK_200, res->status);
  11135. }
  11136. TEST(SSLClientTest, Issue2004_Online) {
  11137. Client client("https://google.com");
  11138. client.set_follow_location(true);
  11139. auto res = client.Get("/");
  11140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11141. ASSERT_EQ(StatusCode::OK_200, res->status);
  11142. auto body = res->body;
  11143. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  11144. }
  11145. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  11146. // Create SSLClient with invalid cert/key to make is_valid() return false
  11147. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  11148. "nonexistent_key.pem");
  11149. // is_valid() should be false due to cert loading failure
  11150. ASSERT_FALSE(cli.is_valid());
  11151. auto res = cli.Get("/");
  11152. ASSERT_FALSE(res);
  11153. EXPECT_EQ(Error::SSLConnection, res.error());
  11154. }
  11155. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  11156. // Test for Issue #2251: SSL error not properly reported when client cert
  11157. // and key paths are swapped or mismatched
  11158. // This simulates the scenario where user accidentally swaps the cert and key
  11159. // files
  11160. // Using client cert file as private key and vice versa (completely wrong)
  11161. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  11162. // Should fail validation due to cert/key mismatch
  11163. ASSERT_FALSE(cli.is_valid());
  11164. // Attempt to make a request should fail with proper error
  11165. auto res = cli.Get("/");
  11166. ASSERT_FALSE(res);
  11167. EXPECT_EQ(Error::SSLConnection, res.error());
  11168. // SSL error should be recorded in the Result object (this is the key fix for
  11169. // Issue #2251)
  11170. auto backend_error = res.ssl_backend_error();
  11171. EXPECT_NE(0u, backend_error);
  11172. }
  11173. // Tests cert/key mismatch detection at the TLS context level
  11174. TEST(TlsApiTest, ClientCertKeyMismatch) {
  11175. // Test that using mismatched cert/key causes connection failure.
  11176. // We verify this at the SSLClient level rather than through internal
  11177. // TLS API functions.
  11178. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  11179. cli.enable_server_certificate_verification(false);
  11180. cli.set_connection_timeout(2);
  11181. // The mismatch should cause a connection or handshake error
  11182. auto res = cli.Get("/test");
  11183. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  11184. // Either way, the request should fail
  11185. EXPECT_FALSE(res);
  11186. }
  11187. #endif
  11188. #if 0
  11189. TEST(SSLClientTest, SetInterfaceWithINET6) {
  11190. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  11191. ASSERT_TRUE(cli != nullptr);
  11192. cli->set_address_family(AF_INET6);
  11193. cli->set_interface("en0");
  11194. auto res = cli->Get("/get");
  11195. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11196. ASSERT_EQ(StatusCode::OK_200, res->status);
  11197. }
  11198. #endif
  11199. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  11200. #ifdef CPPHTTPLIB_SSL_ENABLED
  11201. void ClientCertPresent(
  11202. const std::string &client_cert_file,
  11203. const std::string &client_private_key_file,
  11204. const std::string &client_encrypted_private_key_pass = std::string()) {
  11205. using namespace httplib::tls;
  11206. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  11207. CLIENT_CA_CERT_DIR);
  11208. ASSERT_TRUE(svr.is_valid());
  11209. svr.Get("/test", [&](const Request &req, Response &res) {
  11210. res.set_content("test", "text/plain");
  11211. auto cert = req.peer_cert();
  11212. ASSERT_TRUE(static_cast<bool>(cert));
  11213. std::string common_name = cert.subject_cn();
  11214. EXPECT_EQ("Common Name", common_name);
  11215. });
  11216. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11217. auto se = detail::scope_exit([&] {
  11218. svr.stop();
  11219. t.join();
  11220. ASSERT_FALSE(svr.is_running());
  11221. });
  11222. svr.wait_until_ready();
  11223. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  11224. client_encrypted_private_key_pass);
  11225. cli.enable_server_certificate_verification(false);
  11226. cli.set_connection_timeout(30);
  11227. auto res = cli.Get("/test");
  11228. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11229. ASSERT_EQ(StatusCode::OK_200, res->status);
  11230. }
  11231. TEST(SSLClientServerTest, ClientCertPresent) {
  11232. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11233. }
  11234. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  11235. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  11236. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  11237. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  11238. }
  11239. // PEM memory-based constructor tests (works with all TLS backends)
  11240. void PemMemoryClientCertPresent(
  11241. const std::string &client_cert_file,
  11242. const std::string &client_private_key_file,
  11243. const std::string &client_encrypted_private_key_pass = std::string()) {
  11244. // Read PEM files into memory
  11245. std::string server_cert_pem, server_key_pem;
  11246. std::string client_ca_pem;
  11247. std::string client_cert_pem, client_key_pem;
  11248. read_file(SERVER_CERT_FILE, server_cert_pem);
  11249. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  11250. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  11251. read_file(client_cert_file, client_cert_pem);
  11252. read_file(client_private_key_file, client_key_pem);
  11253. // Create server with PEM memory
  11254. SSLServer::PemMemory server_pem = {
  11255. server_cert_pem.c_str(),
  11256. server_cert_pem.size(),
  11257. server_key_pem.c_str(),
  11258. server_key_pem.size(),
  11259. client_ca_pem.c_str(),
  11260. client_ca_pem.size(),
  11261. nullptr // no password for server key
  11262. };
  11263. SSLServer svr(server_pem);
  11264. ASSERT_TRUE(svr.is_valid());
  11265. svr.Get("/test", [&](const Request &, Response &res) {
  11266. res.set_content("test", "text/plain");
  11267. });
  11268. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11269. auto se = detail::scope_exit([&] {
  11270. svr.stop();
  11271. t.join();
  11272. ASSERT_FALSE(svr.is_running());
  11273. });
  11274. svr.wait_until_ready();
  11275. // Create client with PEM memory
  11276. const char *password = client_encrypted_private_key_pass.empty()
  11277. ? nullptr
  11278. : client_encrypted_private_key_pass.c_str();
  11279. SSLClient::PemMemory client_pem = {
  11280. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  11281. client_key_pem.size(), password};
  11282. SSLClient cli(HOST, PORT, client_pem);
  11283. cli.enable_server_certificate_verification(false);
  11284. cli.set_connection_timeout(30);
  11285. auto res = cli.Get("/test");
  11286. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11287. ASSERT_EQ(StatusCode::OK_200, res->status);
  11288. }
  11289. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  11290. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11291. }
  11292. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  11293. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  11294. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  11295. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  11296. }
  11297. TEST(SSLClientServerTest, ClientCertMissing) {
  11298. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  11299. CLIENT_CA_CERT_DIR);
  11300. ASSERT_TRUE(svr.is_valid());
  11301. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  11302. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11303. auto se = detail::scope_exit([&] {
  11304. svr.stop();
  11305. t.join();
  11306. ASSERT_FALSE(svr.is_running());
  11307. });
  11308. svr.wait_until_ready();
  11309. SSLClient cli(HOST, PORT);
  11310. cli.set_connection_timeout(30);
  11311. auto res = cli.Get("/test");
  11312. ASSERT_TRUE(!res);
  11313. // When client cert is missing and server requires it, connection fails
  11314. // Error type depends on backend implementation
  11315. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  11316. res.error() == Error::SSLConnection);
  11317. // Verify backend error is captured
  11318. // Note: This test may have different error codes depending on the exact
  11319. // verification failure
  11320. EXPECT_NE(0UL, res.ssl_backend_error());
  11321. }
  11322. TEST(SSLClientServerTest, TrustDirOptional) {
  11323. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  11324. ASSERT_TRUE(svr.is_valid());
  11325. svr.Get("/test", [&](const Request &, Response &res) {
  11326. res.set_content("test", "text/plain");
  11327. });
  11328. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11329. auto se = detail::scope_exit([&] {
  11330. svr.stop();
  11331. t.join();
  11332. ASSERT_FALSE(svr.is_running());
  11333. });
  11334. svr.wait_until_ready();
  11335. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11336. cli.enable_server_certificate_verification(false);
  11337. cli.set_connection_timeout(30);
  11338. auto res = cli.Get("/test");
  11339. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11340. ASSERT_EQ(StatusCode::OK_200, res->status);
  11341. }
  11342. TEST(SSLClientServerTest, SSLConnectTimeout) {
  11343. class NoListenSSLServer : public SSLServer {
  11344. public:
  11345. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  11346. const char *client_ca_cert_file_path,
  11347. const char *client_ca_cert_dir_path = nullptr)
  11348. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  11349. client_ca_cert_dir_path),
  11350. stop_(false) {}
  11351. std::atomic_bool stop_;
  11352. private:
  11353. bool process_and_close_socket(socket_t /*sock*/) override {
  11354. // Don't create SSL context
  11355. while (!stop_.load()) {
  11356. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  11357. }
  11358. return true;
  11359. }
  11360. };
  11361. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  11362. CLIENT_CA_CERT_FILE);
  11363. ASSERT_TRUE(svr.is_valid());
  11364. svr.Get("/test", [&](const Request &, Response &res) {
  11365. res.set_content("test", "text/plain");
  11366. });
  11367. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11368. auto se = detail::scope_exit([&] {
  11369. svr.stop_ = true;
  11370. svr.stop();
  11371. t.join();
  11372. ASSERT_FALSE(svr.is_running());
  11373. });
  11374. svr.wait_until_ready();
  11375. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11376. cli.enable_server_certificate_verification(false);
  11377. cli.set_connection_timeout(1);
  11378. auto res = cli.Get("/test");
  11379. ASSERT_TRUE(!res);
  11380. EXPECT_EQ(Error::SSLConnection, res.error());
  11381. // Timeout results in WantRead error code (maps to backend-specific value)
  11382. EXPECT_NE(0, res.ssl_error());
  11383. }
  11384. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  11385. // Test SSLServer with client certificate verification using the standard
  11386. // constructor (ContextSetupCallback is tested by backend-specific tests)
  11387. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  11388. CLIENT_CA_CERT_DIR);
  11389. ASSERT_TRUE(svr.is_valid());
  11390. svr.Get("/test", [&](const Request &req, Response &res) {
  11391. res.set_content("test", "text/plain");
  11392. auto cert = req.peer_cert();
  11393. ASSERT_TRUE(static_cast<bool>(cert));
  11394. auto common_name = cert.subject_cn();
  11395. EXPECT_EQ("Common Name", common_name);
  11396. });
  11397. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11398. auto se = detail::scope_exit([&] {
  11399. svr.stop();
  11400. t.join();
  11401. ASSERT_FALSE(svr.is_running());
  11402. });
  11403. svr.wait_until_ready();
  11404. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11405. cli.enable_server_certificate_verification(false);
  11406. cli.set_connection_timeout(30);
  11407. auto res = cli.Get("/test");
  11408. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11409. ASSERT_EQ(StatusCode::OK_200, res->status);
  11410. }
  11411. // Test verify_hostname for both OpenSSL and MbedTLS backends
  11412. // Verifies that wildcard matching and exact matching work consistently
  11413. TEST(SSLClientServerTest, TlsVerifyHostname) {
  11414. using namespace httplib::tls;
  11415. // We need a running server to test against
  11416. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11417. ASSERT_TRUE(svr.is_valid());
  11418. svr.Get("/test", [](const Request &, Response &res) {
  11419. res.set_content("ok", "text/plain");
  11420. });
  11421. thread t([&]() { svr.listen(HOST, PORT); });
  11422. auto se = detail::scope_exit([&] {
  11423. svr.stop();
  11424. t.join();
  11425. });
  11426. svr.wait_until_ready();
  11427. bool verify_callback_called = false;
  11428. bool verify_result_wrong = false;
  11429. SSLClient cli(HOST, PORT);
  11430. cli.enable_server_certificate_verification(true);
  11431. cli.set_ca_cert_path(CA_CERT_FILE);
  11432. cli.set_connection_timeout(5);
  11433. // Note: Test certificate has CN="Common Name", not "localhost"
  11434. bool verify_result_cn = false;
  11435. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  11436. verify_callback_called = true;
  11437. if (!ctx.cert) return false;
  11438. // Test 1: "Common Name" should match (our test server cert CN)
  11439. verify_result_cn = ctx.check_hostname("Common Name");
  11440. // Test 2: wrong hostname should not match
  11441. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  11442. return true; // Accept for the purpose of this test
  11443. });
  11444. auto res = cli.Get("/test");
  11445. // The request may succeed or fail depending on cert configuration
  11446. // but the callback should have been called
  11447. ASSERT_TRUE(verify_callback_called)
  11448. << "Verify callback should have been called";
  11449. // CN="Common Name" should match our test certificate
  11450. //
  11451. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  11452. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  11453. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  11454. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  11455. // <openssl/base.h>, which is included transitively when
  11456. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  11457. #if defined(OPENSSL_IS_BORINGSSL)
  11458. EXPECT_FALSE(verify_result_cn)
  11459. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  11460. #else
  11461. EXPECT_TRUE(verify_result_cn)
  11462. << "verify_hostname should match 'Common Name' (certificate CN)";
  11463. #endif
  11464. // Wrong hostname should not match
  11465. EXPECT_FALSE(verify_result_wrong)
  11466. << "verify_hostname should not match 'wronghost.example.com'";
  11467. }
  11468. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  11469. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  11470. // X509_check_ip behavior and must hold for every backend.
  11471. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  11472. using namespace httplib::tls;
  11473. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  11474. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  11475. ASSERT_TRUE(svr.is_valid());
  11476. svr.Get("/test", [](const Request &, Response &res) {
  11477. res.set_content("ok", "text/plain");
  11478. });
  11479. thread t([&]() { svr.listen(HOST, PORT); });
  11480. auto se = detail::scope_exit([&] {
  11481. svr.stop();
  11482. t.join();
  11483. });
  11484. svr.wait_until_ready();
  11485. bool verify_callback_called = false;
  11486. bool ip_matched_via_cn = true;
  11487. SSLClient cli(HOST, PORT);
  11488. cli.enable_server_certificate_verification(true);
  11489. cli.set_ca_cert_path(CA_CERT_FILE);
  11490. cli.set_connection_timeout(5);
  11491. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  11492. verify_callback_called = true;
  11493. if (!ctx.cert) return false;
  11494. // The IP appears only in the CN, so it must NOT be accepted.
  11495. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  11496. return true; // Accept for the purpose of this test
  11497. });
  11498. cli.Get("/test");
  11499. ASSERT_TRUE(verify_callback_called)
  11500. << "Verify callback should have been called";
  11501. EXPECT_FALSE(ip_matched_via_cn)
  11502. << "An IP host must not be authenticated via the certificate CN";
  11503. }
  11504. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  11505. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  11506. using namespace httplib::tls;
  11507. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  11508. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  11509. ASSERT_TRUE(svr.is_valid());
  11510. svr.Get("/test", [](const Request &, Response &res) {
  11511. res.set_content("ok", "text/plain");
  11512. });
  11513. thread t([&]() { svr.listen(HOST, PORT); });
  11514. auto se = detail::scope_exit([&] {
  11515. svr.stop();
  11516. t.join();
  11517. });
  11518. svr.wait_until_ready();
  11519. bool verify_callback_called = false;
  11520. bool san_matched = false;
  11521. bool wrong_ipv6_matched = true;
  11522. bool cn_ipv6_matched = true;
  11523. SSLClient cli(HOST, PORT);
  11524. cli.enable_server_certificate_verification(true);
  11525. cli.set_ca_cert_path(CA_CERT_FILE);
  11526. cli.set_connection_timeout(5);
  11527. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  11528. verify_callback_called = true;
  11529. if (!ctx.cert) return false;
  11530. // Matches the IPv6 iPAddress SAN.
  11531. san_matched = ctx.check_hostname("2001:db8::1");
  11532. // A different IPv6 address must not match.
  11533. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  11534. // "::1" lives only in the CN, so it must not be accepted.
  11535. cn_ipv6_matched = ctx.check_hostname("::1");
  11536. return true; // Accept for the purpose of this test
  11537. });
  11538. cli.Get("/test");
  11539. ASSERT_TRUE(verify_callback_called)
  11540. << "Verify callback should have been called";
  11541. EXPECT_TRUE(san_matched)
  11542. << "verify_hostname should match an IPv6 iPAddress SAN";
  11543. EXPECT_FALSE(wrong_ipv6_matched)
  11544. << "verify_hostname should not match a non-matching IPv6 address";
  11545. EXPECT_FALSE(cn_ipv6_matched)
  11546. << "An IPv6 host must not be authenticated via the certificate CN";
  11547. }
  11548. #endif
  11549. // mbedTLS-specific callback constructor test
  11550. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  11551. #ifdef CPPHTTPLIB_SSL_ENABLED
  11552. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  11553. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  11554. ASSERT_TRUE(svr.is_valid());
  11555. // Set up a handler to verify client certificate is present
  11556. bool client_cert_verified = false;
  11557. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  11558. // Verify that client certificate was provided
  11559. client_cert_verified = true;
  11560. res.set_content("success", "text/plain");
  11561. });
  11562. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11563. auto se = detail::scope_exit([&] {
  11564. svr.stop();
  11565. t.join();
  11566. ASSERT_FALSE(svr.is_running());
  11567. });
  11568. svr.wait_until_ready();
  11569. // Client with certificate
  11570. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11571. cli.enable_server_certificate_verification(false);
  11572. cli.set_connection_timeout(30);
  11573. auto res = cli.Get("/test");
  11574. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11575. ASSERT_EQ(StatusCode::OK_200, res->status);
  11576. ASSERT_TRUE(client_cert_verified);
  11577. EXPECT_EQ("success", res->body);
  11578. }
  11579. #endif
  11580. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  11581. // backends
  11582. #ifdef CPPHTTPLIB_SSL_ENABLED
  11583. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  11584. using namespace httplib::tls;
  11585. // Test that when client CA cert file is provided,
  11586. // the server properly requests and validates client certificates
  11587. // Create a server with client authentication
  11588. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  11589. ASSERT_TRUE(svr.is_valid());
  11590. bool handler_called = false;
  11591. svr.Get("/test", [&](const Request &req, Response &res) {
  11592. handler_called = true;
  11593. // Verify that a client certificate was provided
  11594. auto cert = req.peer_cert();
  11595. ASSERT_TRUE(static_cast<bool>(cert));
  11596. // Get the issuer name
  11597. std::string issuer_str = cert.issuer_name();
  11598. ASSERT_FALSE(issuer_str.empty());
  11599. // The client certificate should be issued by our test CA
  11600. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  11601. res.set_content("authenticated", "text/plain");
  11602. });
  11603. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11604. auto se = detail::scope_exit([&] {
  11605. svr.stop();
  11606. t.join();
  11607. ASSERT_FALSE(svr.is_running());
  11608. });
  11609. svr.wait_until_ready();
  11610. // Connect with a client certificate issued by the CA
  11611. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11612. cli.enable_server_certificate_verification(false);
  11613. cli.set_connection_timeout(30);
  11614. auto res = cli.Get("/test");
  11615. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11616. ASSERT_EQ(StatusCode::OK_200, res->status);
  11617. ASSERT_TRUE(handler_called);
  11618. EXPECT_EQ("authenticated", res->body);
  11619. }
  11620. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  11621. using namespace httplib::tls;
  11622. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11623. ASSERT_TRUE(svr.is_valid());
  11624. svr.Get("/test", [](const Request &, Response &res) {
  11625. res.set_content("ok", "text/plain");
  11626. });
  11627. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11628. auto se = detail::scope_exit([&] {
  11629. svr.stop();
  11630. t.join();
  11631. });
  11632. svr.wait_until_ready();
  11633. SSLClient cli(HOST, PORT);
  11634. cli.enable_server_certificate_verification(false);
  11635. cli.set_connection_timeout(30);
  11636. bool cert_checked = false;
  11637. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  11638. if (ctx.cert) {
  11639. auto sans = ctx.sans();
  11640. // Test certificate may or may not have SANs - just verify the API
  11641. // works If SANs exist, verify the types are valid
  11642. for (const auto &san : sans) {
  11643. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  11644. san.type == SanType::EMAIL || san.type == SanType::URI ||
  11645. san.type == SanType::OTHER);
  11646. EXPECT_FALSE(san.value.empty());
  11647. }
  11648. cert_checked = true;
  11649. }
  11650. return true;
  11651. });
  11652. auto res = cli.Get("/test");
  11653. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11654. EXPECT_TRUE(cert_checked);
  11655. }
  11656. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  11657. using namespace httplib::tls;
  11658. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11659. ASSERT_TRUE(svr.is_valid());
  11660. svr.Get("/test", [](const Request &, Response &res) {
  11661. res.set_content("ok", "text/plain");
  11662. });
  11663. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11664. auto se = detail::scope_exit([&] {
  11665. svr.stop();
  11666. t.join();
  11667. });
  11668. svr.wait_until_ready();
  11669. SSLClient cli(HOST, PORT);
  11670. cli.enable_server_certificate_verification(false);
  11671. cli.set_connection_timeout(30);
  11672. bool validity_checked = false;
  11673. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  11674. if (ctx.cert) {
  11675. time_t not_before = 0, not_after = 0;
  11676. bool result = ctx.validity(not_before, not_after);
  11677. EXPECT_TRUE(result);
  11678. // Verify that not_before < now < not_after for a valid cert
  11679. time_t now = time(nullptr);
  11680. EXPECT_LT(not_before, now);
  11681. EXPECT_GT(not_after, now);
  11682. validity_checked = true;
  11683. }
  11684. return true;
  11685. });
  11686. auto res = cli.Get("/test");
  11687. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11688. EXPECT_TRUE(validity_checked);
  11689. }
  11690. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  11691. using namespace httplib::tls;
  11692. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11693. ASSERT_TRUE(svr.is_valid());
  11694. svr.Get("/test", [](const Request &, Response &res) {
  11695. res.set_content("ok", "text/plain");
  11696. });
  11697. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11698. auto se = detail::scope_exit([&] {
  11699. svr.stop();
  11700. t.join();
  11701. });
  11702. svr.wait_until_ready();
  11703. SSLClient cli(HOST, PORT);
  11704. cli.enable_server_certificate_verification(false);
  11705. cli.set_connection_timeout(30);
  11706. bool serial_checked = false;
  11707. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  11708. if (ctx.cert) {
  11709. std::string serial = ctx.serial();
  11710. EXPECT_FALSE(serial.empty());
  11711. // Serial should be a hex string
  11712. for (char c : serial) {
  11713. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  11714. (c >= 'a' && c <= 'f'));
  11715. }
  11716. serial_checked = true;
  11717. }
  11718. return true;
  11719. });
  11720. auto res = cli.Get("/test");
  11721. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11722. EXPECT_TRUE(serial_checked);
  11723. }
  11724. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  11725. // Test 1: Valid CA file - no error should be recorded
  11726. {
  11727. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  11728. CLIENT_CA_CERT_FILE);
  11729. ASSERT_TRUE(svr.is_valid());
  11730. // With valid setup, last_ssl_error should be 0
  11731. EXPECT_EQ(0, svr.ssl_last_error());
  11732. }
  11733. // Test 2: Invalid CA file content
  11734. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  11735. {
  11736. // Create a temporary file with completely invalid content
  11737. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  11738. {
  11739. std::ofstream ofs(temp_invalid_ca);
  11740. ofs << "This is not a certificate file at all\n";
  11741. ofs << "Just plain text content\n";
  11742. }
  11743. // Create server with invalid CA file
  11744. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  11745. // Clean up temporary file
  11746. std::remove(temp_invalid_ca);
  11747. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  11748. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  11749. // Note: SSL_CTX_load_verify_locations typically fails first,
  11750. // but our error handling code path is still exercised
  11751. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  11752. }
  11753. }
  11754. TEST(VerifyCallbackTest, VerifyContextFields) {
  11755. using namespace httplib::tls;
  11756. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11757. ASSERT_TRUE(svr.is_valid());
  11758. svr.Get("/test", [](const Request &, Response &res) {
  11759. res.set_content("ok", "text/plain");
  11760. });
  11761. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11762. auto se = detail::scope_exit([&] {
  11763. svr.stop();
  11764. t.join();
  11765. });
  11766. svr.wait_until_ready();
  11767. SSLClient cli(HOST, PORT);
  11768. cli.enable_server_certificate_verification(false);
  11769. cli.set_connection_timeout(30);
  11770. int callback_count = 0;
  11771. bool saw_leaf_cert = false;
  11772. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  11773. if (ctx.cert) {
  11774. callback_count++;
  11775. // We should see at least one certificate (the leaf)
  11776. std::string cn = ctx.subject_cn();
  11777. if (!cn.empty()) { saw_leaf_cert = true; }
  11778. // Verify context fields are populated
  11779. EXPECT_NE(ctx.session, nullptr);
  11780. EXPECT_GE(ctx.depth, 0);
  11781. }
  11782. return true;
  11783. });
  11784. auto res = cli.Get("/test");
  11785. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11786. EXPECT_GT(callback_count, 0);
  11787. EXPECT_TRUE(saw_leaf_cert);
  11788. }
  11789. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  11790. using httplib::tls::TlsError;
  11791. // Test that verify_error_to_string returns empty for success
  11792. std::string success_str = TlsError::verify_error_to_string(0);
  11793. EXPECT_TRUE(success_str.empty());
  11794. // Test that verify_error_to_string returns non-empty for error codes
  11795. // Using a common error code (certificate expired)
  11796. std::string error_str =
  11797. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  11798. EXPECT_FALSE(error_str.empty());
  11799. }
  11800. TEST(SessionVerifierTest, CertificateAccepted) {
  11801. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11802. ASSERT_TRUE(svr.is_valid());
  11803. svr.Get("/test", [](const Request &, Response &res) {
  11804. res.set_content("ok", "text/plain");
  11805. });
  11806. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11807. auto se = detail::scope_exit([&] {
  11808. svr.stop();
  11809. t.join();
  11810. });
  11811. svr.wait_until_ready();
  11812. SSLClient cli(HOST, PORT);
  11813. cli.enable_server_certificate_verification(false);
  11814. cli.set_connection_timeout(30);
  11815. bool callback_called = false;
  11816. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  11817. EXPECT_NE(session, nullptr);
  11818. callback_called = true;
  11819. return SSLVerifierResponse::CertificateAccepted;
  11820. });
  11821. auto res = cli.Get("/test");
  11822. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11823. EXPECT_EQ(200, res->status);
  11824. EXPECT_TRUE(callback_called);
  11825. }
  11826. TEST(SessionVerifierTest, CertificateRejected) {
  11827. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11828. ASSERT_TRUE(svr.is_valid());
  11829. svr.Get("/test", [](const Request &, Response &res) {
  11830. res.set_content("ok", "text/plain");
  11831. });
  11832. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11833. auto se = detail::scope_exit([&] {
  11834. svr.stop();
  11835. t.join();
  11836. });
  11837. svr.wait_until_ready();
  11838. SSLClient cli(HOST, PORT);
  11839. cli.enable_server_certificate_verification(false);
  11840. cli.set_connection_timeout(30);
  11841. bool callback_called = false;
  11842. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  11843. EXPECT_NE(session, nullptr);
  11844. callback_called = true;
  11845. return SSLVerifierResponse::CertificateRejected;
  11846. });
  11847. auto res = cli.Get("/test");
  11848. EXPECT_FALSE(res);
  11849. EXPECT_TRUE(callback_called);
  11850. }
  11851. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  11852. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11853. ASSERT_TRUE(svr.is_valid());
  11854. svr.Get("/test", [](const Request &, Response &res) {
  11855. res.set_content("ok", "text/plain");
  11856. });
  11857. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11858. auto se = detail::scope_exit([&] {
  11859. svr.stop();
  11860. t.join();
  11861. });
  11862. svr.wait_until_ready();
  11863. // NoDecisionMade with verification disabled should succeed (no default check)
  11864. SSLClient cli(HOST, PORT);
  11865. cli.enable_server_certificate_verification(false);
  11866. cli.set_connection_timeout(30);
  11867. bool callback_called = false;
  11868. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  11869. EXPECT_NE(session, nullptr);
  11870. callback_called = true;
  11871. return SSLVerifierResponse::NoDecisionMade;
  11872. });
  11873. auto res = cli.Get("/test");
  11874. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11875. EXPECT_EQ(200, res->status);
  11876. EXPECT_TRUE(callback_called);
  11877. }
  11878. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  11879. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11880. ASSERT_TRUE(svr.is_valid());
  11881. svr.Get("/test", [](const Request &, Response &res) {
  11882. res.set_content("ok", "text/plain");
  11883. });
  11884. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11885. auto se = detail::scope_exit([&] {
  11886. svr.stop();
  11887. t.join();
  11888. });
  11889. svr.wait_until_ready();
  11890. // NoDecisionMade with verification enabled should fail (self-signed cert).
  11891. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  11892. // so we only check that the request fails, not whether the callback was
  11893. // called.
  11894. SSLClient cli(HOST, PORT);
  11895. cli.enable_server_certificate_verification(true);
  11896. cli.set_connection_timeout(30);
  11897. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  11898. EXPECT_NE(session, nullptr);
  11899. return SSLVerifierResponse::NoDecisionMade;
  11900. });
  11901. auto res = cli.Get("/test");
  11902. EXPECT_FALSE(res);
  11903. }
  11904. TEST(SSLClientServerTest, ClientCAListFromPem) {
  11905. // Test SSL server using PemMemory constructor with client CA certificates
  11906. // Read PEM files
  11907. std::string server_cert_pem, server_key_pem, client_ca_pem;
  11908. read_file(SERVER_CERT_FILE, server_cert_pem);
  11909. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  11910. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  11911. // Create SSLServer with PemMemory constructor including client CA
  11912. SSLServer::PemMemory server_pem = {
  11913. server_cert_pem.c_str(),
  11914. server_cert_pem.size(),
  11915. server_key_pem.c_str(),
  11916. server_key_pem.size(),
  11917. client_ca_pem.c_str(),
  11918. client_ca_pem.size(),
  11919. nullptr // no password for server key
  11920. };
  11921. SSLServer svr(server_pem);
  11922. ASSERT_TRUE(svr.is_valid());
  11923. // No SSL error should be recorded for valid setup
  11924. EXPECT_EQ(0, svr.ssl_last_error());
  11925. // Set up server endpoints
  11926. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  11927. res.set_content("ok", "text/plain");
  11928. });
  11929. // Start server in a thread
  11930. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  11931. svr.wait_until_ready();
  11932. // Connect with client certificate (using constructor with paths)
  11933. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11934. cli.enable_server_certificate_verification(false);
  11935. auto res = cli.Get("/test-pem-ca");
  11936. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11937. EXPECT_EQ(200, res->status);
  11938. EXPECT_EQ("ok", res->body);
  11939. svr.stop();
  11940. server_thread.join();
  11941. }
  11942. #endif
  11943. #ifdef _WIN32
  11944. TEST(CleanupTest, WSACleanup) {
  11945. int ret = WSACleanup();
  11946. ASSERT_EQ(0, ret);
  11947. }
  11948. #endif
  11949. #ifndef CPPHTTPLIB_SSL_ENABLED
  11950. TEST(NoSSLSupport, SimpleInterface) {
  11951. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  11952. }
  11953. #endif
  11954. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  11955. TEST(InvalidScheme, SimpleInterface) {
  11956. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  11957. }
  11958. #endif
  11959. TEST(NoScheme, SimpleInterface) {
  11960. Client cli("yahoo.com:80");
  11961. ASSERT_TRUE(cli.is_valid());
  11962. }
  11963. TEST(SendAPI, SimpleInterface_Online) {
  11964. Client cli("http://yahoo.com");
  11965. Request req;
  11966. req.method = "GET";
  11967. req.path = "/";
  11968. auto res = cli.send(req);
  11969. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11970. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11971. }
  11972. TEST(SendAPI, WithParamsInRequest) {
  11973. Server svr;
  11974. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  11975. EXPECT_TRUE(req.has_param("test"));
  11976. EXPECT_EQ("test_value", req.get_param_value("test"));
  11977. });
  11978. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11979. auto se = detail::scope_exit([&] {
  11980. svr.stop();
  11981. t.join();
  11982. ASSERT_FALSE(svr.is_running());
  11983. });
  11984. svr.wait_until_ready();
  11985. Client cli(HOST, PORT);
  11986. {
  11987. Request req;
  11988. req.method = "GET";
  11989. req.path = "/";
  11990. req.params.emplace("test", "test_value");
  11991. auto res = cli.send(req);
  11992. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11993. }
  11994. {
  11995. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  11996. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11997. }
  11998. }
  11999. TEST(ClientImplMethods, GetSocketTest) {
  12000. httplib::Server svr;
  12001. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  12002. res.status = StatusCode::OK_200;
  12003. });
  12004. auto port = svr.bind_to_any_port("127.0.0.1");
  12005. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  12006. auto se = detail::scope_exit([&] {
  12007. svr.stop();
  12008. thread.join();
  12009. ASSERT_FALSE(svr.is_running());
  12010. });
  12011. svr.wait_until_ready();
  12012. {
  12013. httplib::Client cli("127.0.0.1", port);
  12014. cli.set_keep_alive(true);
  12015. // Use the behavior of cpp-httplib of opening the connection
  12016. // only when the first request happens. If that changes,
  12017. // this test would be obsolete.
  12018. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  12019. // This also implicitly tests the server. But other tests would fail much
  12020. // earlier than this one to be considered.
  12021. auto res = cli.Get("/");
  12022. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12023. EXPECT_EQ(StatusCode::OK_200, res->status);
  12024. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  12025. }
  12026. }
  12027. #ifdef CPPHTTPLIB_SSL_ENABLED
  12028. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  12029. Client cli("http://yahoo.com");
  12030. auto res = cli.Get("/");
  12031. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12032. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  12033. cli.set_follow_location(true);
  12034. res = cli.Get("/");
  12035. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12036. EXPECT_EQ(StatusCode::OK_200, res->status);
  12037. EXPECT_EQ("https://www.yahoo.com/", res->location);
  12038. }
  12039. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  12040. Client cli("https://yahoo.com");
  12041. auto res = cli.Get("/");
  12042. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12043. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  12044. cli.set_follow_location(true);
  12045. res = cli.Get("/");
  12046. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12047. EXPECT_EQ(StatusCode::OK_200, res->status);
  12048. EXPECT_EQ("https://www.yahoo.com/", res->location);
  12049. }
  12050. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  12051. Client cli("https://yahoo.com");
  12052. auto res = cli.Get("/");
  12053. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12054. ASSERT_FALSE(!res);
  12055. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12056. ASSERT_FALSE(res == nullptr);
  12057. ASSERT_TRUE(res != nullptr);
  12058. EXPECT_EQ(Error::Success, res.error());
  12059. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  12060. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  12061. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  12062. cli.set_follow_location(true);
  12063. res = cli.Get("/");
  12064. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12065. EXPECT_EQ(Error::Success, res.error());
  12066. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  12067. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  12068. EXPECT_EQ(StatusCode::OK_200, res->status);
  12069. EXPECT_EQ("https://www.yahoo.com/", res->location);
  12070. }
  12071. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  12072. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  12073. Client cli("https://cdnjs.cloudflare.com");
  12074. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  12075. Headers{{"Accept-Encoding", "br"}});
  12076. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12077. EXPECT_EQ(StatusCode::OK_200, res->status);
  12078. EXPECT_EQ(287630U, res->body.size());
  12079. EXPECT_EQ("application/javascript; charset=utf-8",
  12080. res->get_header_value("Content-Type"));
  12081. }
  12082. #endif
  12083. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  12084. #undef REDIR_HOST // Silence compiler warning
  12085. #define REDIR_HOST "https://httpbingo.org"
  12086. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  12087. Client cli(REDIR_HOST);
  12088. cli.set_follow_location(true);
  12089. auto res =
  12090. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  12091. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12092. EXPECT_EQ(StatusCode::OK_200, res->status);
  12093. }
  12094. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  12095. Client cli(REDIR_HOST);
  12096. cli.set_follow_location(true);
  12097. Params params;
  12098. params.emplace("url", "http://example.com");
  12099. params.emplace("status_code", "302");
  12100. auto res = cli.Get(REDIR_PATH, params, Headers{});
  12101. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12102. EXPECT_EQ(StatusCode::OK_200, res->status);
  12103. }
  12104. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  12105. Client cli(REDIR_HOST);
  12106. cli.set_follow_location(true);
  12107. Params params;
  12108. params.emplace("url", "http://example.com");
  12109. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  12110. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12111. EXPECT_EQ(StatusCode::OK_200, res->status);
  12112. }
  12113. TEST(HttpToHttpsRedirectTest, CertFile) {
  12114. auto ssl_port = PORT + 1;
  12115. Server svr;
  12116. ASSERT_TRUE(svr.is_valid());
  12117. svr.Get("/index", [&](const Request &, Response &res) {
  12118. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  12119. "/index");
  12120. svr.stop();
  12121. });
  12122. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12123. ASSERT_TRUE(ssl_svr.is_valid());
  12124. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  12125. res.set_content("test", "text/plain");
  12126. ssl_svr.stop();
  12127. });
  12128. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12129. thread t2 =
  12130. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  12131. auto se = detail::scope_exit([&] {
  12132. t2.join();
  12133. t.join();
  12134. ASSERT_FALSE(svr.is_running());
  12135. });
  12136. svr.wait_until_ready();
  12137. ssl_svr.wait_until_ready();
  12138. Client cli("127.0.0.1", PORT);
  12139. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  12140. cli.enable_server_certificate_verification(true);
  12141. cli.set_follow_location(true);
  12142. cli.set_connection_timeout(30);
  12143. auto res = cli.Get("/index");
  12144. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12145. ASSERT_EQ(StatusCode::OK_200, res->status);
  12146. }
  12147. TEST(SSLClientRedirectTest, CertFile) {
  12148. auto ssl_port = PORT + 1;
  12149. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12150. ASSERT_TRUE(ssl_svr1.is_valid());
  12151. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  12152. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  12153. "/index");
  12154. ssl_svr1.stop();
  12155. });
  12156. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12157. ASSERT_TRUE(ssl_svr2.is_valid());
  12158. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  12159. res.set_content("test", "text/plain");
  12160. ssl_svr2.stop();
  12161. });
  12162. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  12163. thread t2 =
  12164. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  12165. auto se = detail::scope_exit([&] {
  12166. t2.join();
  12167. t.join();
  12168. ASSERT_FALSE(ssl_svr1.is_running());
  12169. });
  12170. ssl_svr1.wait_until_ready();
  12171. ssl_svr2.wait_until_ready();
  12172. SSLClient cli("127.0.0.1", PORT);
  12173. std::string cert;
  12174. read_file(SERVER_CERT2_FILE, cert);
  12175. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12176. cli.enable_server_certificate_verification(true);
  12177. cli.set_follow_location(true);
  12178. cli.set_connection_timeout(30);
  12179. auto res = cli.Get("/index");
  12180. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12181. ASSERT_EQ(StatusCode::OK_200, res->status);
  12182. }
  12183. #endif
  12184. #ifdef CPPHTTPLIB_SSL_ENABLED
  12185. // Test that set_ca_cert_store() skips system certs (consistent with
  12186. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  12187. // should be trusted - system certs should NOT be loaded.
  12188. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  12189. // Load a specific cert that is NOT a system CA cert
  12190. std::string cert;
  12191. read_file(SERVER_CERT2_FILE, cert);
  12192. SSLClient cli("google.com");
  12193. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12194. cli.enable_server_certificate_verification(true);
  12195. // This should FAIL because:
  12196. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  12197. // 2. System certs should NOT be loaded when custom store is set
  12198. // If system certs WERE loaded, this would succeed
  12199. auto res = cli.Get("/");
  12200. ASSERT_FALSE(res);
  12201. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12202. }
  12203. // Same as above, but through the native store handle path. Regression test:
  12204. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  12205. // merged system certs into the user-provided store.
  12206. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  12207. std::string cert;
  12208. read_file(SERVER_CERT2_FILE, cert);
  12209. SSLClient cli("google.com");
  12210. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  12211. cli.enable_server_certificate_verification(true);
  12212. auto res = cli.Get("/");
  12213. ASSERT_FALSE(res);
  12214. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12215. }
  12216. // A custom store set via the native handle must still verify a server whose
  12217. // cert it does contain.
  12218. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  12219. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12220. ASSERT_TRUE(svr.is_valid());
  12221. svr.Get("/test", [&](const Request &, Response &res) {
  12222. res.set_content("test", "text/plain");
  12223. });
  12224. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12225. auto se = detail::scope_exit([&] {
  12226. svr.stop();
  12227. t.join();
  12228. ASSERT_FALSE(svr.is_running());
  12229. });
  12230. svr.wait_until_ready();
  12231. SSLClient cli("127.0.0.1", PORT);
  12232. std::string cert;
  12233. read_file(SERVER_CERT2_FILE, cert);
  12234. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  12235. cli.enable_server_certificate_verification(true);
  12236. cli.set_connection_timeout(30);
  12237. auto res = cli.Get("/test");
  12238. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12239. ASSERT_EQ(StatusCode::OK_200, res->status);
  12240. }
  12241. // CA certs loaded through the universal Client must be transferred to the
  12242. // client created internally for following an HTTPS redirect. Regression test:
  12243. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  12244. // the CA data for redirect transfer.
  12245. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  12246. auto ssl_port = PORT + 1;
  12247. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12248. ASSERT_TRUE(ssl_svr1.is_valid());
  12249. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  12250. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  12251. "/index");
  12252. });
  12253. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12254. ASSERT_TRUE(ssl_svr2.is_valid());
  12255. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  12256. res.set_content("test", "text/plain");
  12257. });
  12258. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  12259. thread t2 =
  12260. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  12261. auto se = detail::scope_exit([&] {
  12262. ssl_svr2.stop();
  12263. ssl_svr1.stop();
  12264. t2.join();
  12265. t.join();
  12266. ASSERT_FALSE(ssl_svr1.is_running());
  12267. });
  12268. ssl_svr1.wait_until_ready();
  12269. ssl_svr2.wait_until_ready();
  12270. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  12271. std::string cert;
  12272. read_file(SERVER_CERT2_FILE, cert);
  12273. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12274. cli.enable_server_certificate_verification(true);
  12275. cli.set_follow_location(true);
  12276. cli.set_connection_timeout(30);
  12277. auto res = cli.Get("/index");
  12278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12279. ASSERT_EQ(StatusCode::OK_200, res->status);
  12280. }
  12281. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  12282. // so a host signed by a system CA verifies even though a custom CA is set
  12283. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  12284. std::string cert;
  12285. read_file(SERVER_CERT2_FILE, cert);
  12286. SSLClient cli("google.com");
  12287. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12288. cli.enable_system_ca(true);
  12289. cli.enable_server_certificate_verification(true);
  12290. auto res = cli.Get("/");
  12291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12292. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12293. }
  12294. // The custom CA remains effective when combined with the system CA
  12295. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  12296. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12297. ASSERT_TRUE(svr.is_valid());
  12298. svr.Get("/test", [&](const Request &, Response &res) {
  12299. res.set_content("test", "text/plain");
  12300. });
  12301. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12302. auto se = detail::scope_exit([&] {
  12303. svr.stop();
  12304. t.join();
  12305. ASSERT_FALSE(svr.is_running());
  12306. });
  12307. svr.wait_until_ready();
  12308. SSLClient cli("127.0.0.1", PORT);
  12309. std::string cert;
  12310. read_file(SERVER_CERT2_FILE, cert);
  12311. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12312. cli.enable_system_ca(true);
  12313. cli.enable_server_certificate_verification(true);
  12314. cli.set_connection_timeout(30);
  12315. auto res = cli.Get("/test");
  12316. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12317. ASSERT_EQ(StatusCode::OK_200, res->status);
  12318. }
  12319. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  12320. // skip chain verification entirely (only the certificate identity was
  12321. // checked), so a server presenting an untrusted certificate with a matching
  12322. // IP SAN was accepted. The chain must be validated for IP hosts too.
  12323. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  12324. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12325. ASSERT_TRUE(svr.is_valid());
  12326. svr.Get("/test", [&](const Request &, Response &res) {
  12327. res.set_content("test", "text/plain");
  12328. });
  12329. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12330. auto se = detail::scope_exit([&] {
  12331. svr.stop();
  12332. t.join();
  12333. ASSERT_FALSE(svr.is_running());
  12334. });
  12335. svr.wait_until_ready();
  12336. SSLClient cli("127.0.0.1", PORT);
  12337. std::string cert;
  12338. // A trusted CA that did not sign the server certificate. The server cert
  12339. // (cert2) carries the matching IP SAN, so only chain validation can reject
  12340. // this connection.
  12341. read_file(CLIENT_CA_CERT_FILE, cert);
  12342. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12343. cli.enable_server_certificate_verification(true);
  12344. cli.set_connection_timeout(30);
  12345. auto res = cli.Get("/test");
  12346. ASSERT_FALSE(res);
  12347. }
  12348. // enable_system_ca(false) prevents system CA loading entirely
  12349. TEST(SSLClientTest, DisableSystemCa_Online) {
  12350. SSLClient cli("google.com");
  12351. cli.enable_system_ca(false);
  12352. cli.enable_server_certificate_verification(true);
  12353. auto res = cli.Get("/");
  12354. ASSERT_FALSE(res);
  12355. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  12356. // itself when the CA chain is empty
  12357. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  12358. res.error() == Error::SSLConnection);
  12359. }
  12360. // The universal Client forwards enable_system_ca()
  12361. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  12362. std::string cert;
  12363. read_file(SERVER_CERT2_FILE, cert);
  12364. Client cli("https://google.com");
  12365. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12366. cli.enable_system_ca(true);
  12367. cli.enable_server_certificate_verification(true);
  12368. auto res = cli.Get("/");
  12369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12370. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12371. }
  12372. // The system CA policy must carry over to the client created internally for
  12373. // following a cross-host HTTPS redirect
  12374. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  12375. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12376. ASSERT_TRUE(svr.is_valid());
  12377. svr.Get("/index", [&](const Request &, Response &res) {
  12378. res.set_redirect("https://www.google.com/");
  12379. });
  12380. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12381. auto se = detail::scope_exit([&] {
  12382. svr.stop();
  12383. t.join();
  12384. ASSERT_FALSE(svr.is_running());
  12385. });
  12386. svr.wait_until_ready();
  12387. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  12388. std::string cert;
  12389. read_file(SERVER_CERT2_FILE, cert);
  12390. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12391. cli.enable_system_ca(true);
  12392. cli.enable_server_certificate_verification(true);
  12393. cli.set_follow_location(true);
  12394. cli.set_connection_timeout(30);
  12395. // Receiving any response proves the redirect client completed the TLS
  12396. // handshake with a system-CA-signed host
  12397. auto res = cli.Get("/index");
  12398. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12399. }
  12400. TEST(MultipartFormDataTest, LargeData) {
  12401. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12402. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  12403. const ContentReader &content_reader) {
  12404. if (req.is_multipart_form_data()) {
  12405. std::vector<FormData> items;
  12406. content_reader(
  12407. [&](const FormData &file) {
  12408. items.push_back(file);
  12409. return true;
  12410. },
  12411. [&](const char *data, size_t data_length) {
  12412. items.back().content.append(data, data_length);
  12413. return true;
  12414. });
  12415. EXPECT_TRUE(std::string(items[0].name) == "document");
  12416. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  12417. EXPECT_TRUE(items[0].filename == "2MB_data");
  12418. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  12419. EXPECT_TRUE(items[1].name == "hello");
  12420. EXPECT_TRUE(items[1].content == "world");
  12421. EXPECT_TRUE(items[1].filename == "");
  12422. EXPECT_TRUE(items[1].content_type == "");
  12423. } else {
  12424. std::string body;
  12425. content_reader([&](const char *data, size_t data_length) {
  12426. body.append(data, data_length);
  12427. return true;
  12428. });
  12429. }
  12430. });
  12431. auto port = svr.bind_to_any_port(HOST);
  12432. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12433. auto se = detail::scope_exit([&] {
  12434. svr.stop();
  12435. t.join();
  12436. ASSERT_FALSE(svr.is_running());
  12437. });
  12438. svr.wait_until_ready();
  12439. {
  12440. std::string data(1024 * 1024 * 2, '.');
  12441. std::stringstream buffer;
  12442. buffer << data;
  12443. SSLClient cli(HOST, port);
  12444. cli.enable_server_certificate_verification(false);
  12445. UploadFormDataItems items{
  12446. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  12447. {"hello", "world", "", ""},
  12448. };
  12449. auto res = cli.Post("/post", items);
  12450. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12451. ASSERT_EQ(StatusCode::OK_200, res->status);
  12452. }
  12453. }
  12454. TEST(MultipartFormDataTest, DataProviderItems) {
  12455. std::random_device seed_gen;
  12456. std::mt19937 random(seed_gen());
  12457. std::string rand1;
  12458. rand1.resize(1000);
  12459. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  12460. std::string rand2;
  12461. rand2.resize(3000);
  12462. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  12463. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12464. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  12465. const ContentReader &content_reader) {
  12466. ASSERT_FALSE(req.is_multipart_form_data());
  12467. std::string body;
  12468. content_reader([&](const char *data, size_t data_length) {
  12469. body.append(data, data_length);
  12470. return true;
  12471. });
  12472. EXPECT_EQ(body, "");
  12473. });
  12474. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  12475. const ContentReader &content_reader) {
  12476. ASSERT_TRUE(req.is_multipart_form_data());
  12477. std::vector<FormData> items;
  12478. content_reader(
  12479. [&](const FormData &file) {
  12480. items.push_back(file);
  12481. return true;
  12482. },
  12483. [&](const char *data, size_t data_length) {
  12484. items.back().content.append(data, data_length);
  12485. return true;
  12486. });
  12487. ASSERT_TRUE(items.size() == 2);
  12488. EXPECT_EQ(std::string(items[0].name), "name1");
  12489. EXPECT_EQ(items[0].content, "Testing123");
  12490. EXPECT_EQ(items[0].filename, "filename1");
  12491. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  12492. EXPECT_EQ(items[1].name, "name2");
  12493. EXPECT_EQ(items[1].content, "Testing456");
  12494. EXPECT_EQ(items[1].filename, "");
  12495. EXPECT_EQ(items[1].content_type, "");
  12496. });
  12497. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  12498. const ContentReader &content_reader) {
  12499. ASSERT_TRUE(req.is_multipart_form_data());
  12500. std::vector<FormData> items;
  12501. content_reader(
  12502. [&](const FormData &file) {
  12503. items.push_back(file);
  12504. return true;
  12505. },
  12506. [&](const char *data, size_t data_length) {
  12507. items.back().content.append(data, data_length);
  12508. return true;
  12509. });
  12510. ASSERT_TRUE(items.size() == 2);
  12511. EXPECT_EQ(items[0].name, "name3");
  12512. EXPECT_EQ(items[0].content, rand1);
  12513. EXPECT_EQ(items[0].filename, "filename3");
  12514. EXPECT_EQ(items[0].content_type, "");
  12515. EXPECT_EQ(items[1].name, "name4");
  12516. EXPECT_EQ(items[1].content, rand2);
  12517. EXPECT_EQ(items[1].filename, "filename4");
  12518. EXPECT_EQ(items[1].content_type, "");
  12519. });
  12520. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  12521. const ContentReader &content_reader) {
  12522. ASSERT_TRUE(req.is_multipart_form_data());
  12523. std::vector<FormData> items;
  12524. content_reader(
  12525. [&](const FormData &file) {
  12526. items.push_back(file);
  12527. return true;
  12528. },
  12529. [&](const char *data, size_t data_length) {
  12530. items.back().content.append(data, data_length);
  12531. return true;
  12532. });
  12533. ASSERT_TRUE(items.size() == 4);
  12534. EXPECT_EQ(std::string(items[0].name), "name1");
  12535. EXPECT_EQ(items[0].content, "Testing123");
  12536. EXPECT_EQ(items[0].filename, "filename1");
  12537. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  12538. EXPECT_EQ(items[1].name, "name2");
  12539. EXPECT_EQ(items[1].content, "Testing456");
  12540. EXPECT_EQ(items[1].filename, "");
  12541. EXPECT_EQ(items[1].content_type, "");
  12542. EXPECT_EQ(items[2].name, "name3");
  12543. EXPECT_EQ(items[2].content, rand1);
  12544. EXPECT_EQ(items[2].filename, "filename3");
  12545. EXPECT_EQ(items[2].content_type, "");
  12546. EXPECT_EQ(items[3].name, "name4");
  12547. EXPECT_EQ(items[3].content, rand2);
  12548. EXPECT_EQ(items[3].filename, "filename4");
  12549. EXPECT_EQ(items[3].content_type, "");
  12550. });
  12551. auto port = svr.bind_to_any_port("localhost");
  12552. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12553. auto se = detail::scope_exit([&] {
  12554. svr.stop();
  12555. t.join();
  12556. ASSERT_FALSE(svr.is_running());
  12557. });
  12558. svr.wait_until_ready();
  12559. {
  12560. SSLClient cli("localhost", port);
  12561. cli.enable_server_certificate_verification(false);
  12562. UploadFormDataItems items{
  12563. {"name1", "Testing123", "filename1", "application/octet-stream"},
  12564. {"name2", "Testing456", "", ""}, // not a file
  12565. };
  12566. {
  12567. auto res = cli.Post("/post-none", {}, {}, {});
  12568. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12569. ASSERT_EQ(StatusCode::OK_200, res->status);
  12570. }
  12571. FormDataProviderItems providers;
  12572. {
  12573. auto res =
  12574. cli.Post("/post-items", {}, items, providers); // empty providers
  12575. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12576. ASSERT_EQ(StatusCode::OK_200, res->status);
  12577. }
  12578. providers.push_back({"name3",
  12579. [&](size_t offset, httplib::DataSink &sink) -> bool {
  12580. // test the offset is given correctly at each step
  12581. if (!offset)
  12582. sink.os.write(rand1.data(), 30);
  12583. else if (offset == 30)
  12584. sink.os.write(rand1.data() + 30, 300);
  12585. else if (offset == 330)
  12586. sink.os.write(rand1.data() + 330, 670);
  12587. else if (offset == rand1.size())
  12588. sink.done();
  12589. return true;
  12590. },
  12591. "filename3",
  12592. {}});
  12593. providers.push_back({"name4",
  12594. [&](size_t offset, httplib::DataSink &sink) -> bool {
  12595. // test the offset is given correctly at each step
  12596. if (!offset)
  12597. sink.os.write(rand2.data(), 2000);
  12598. else if (offset == 2000)
  12599. sink.os.write(rand2.data() + 2000, 1);
  12600. else if (offset == 2001)
  12601. sink.os.write(rand2.data() + 2001, 999);
  12602. else if (offset == rand2.size())
  12603. sink.done();
  12604. return true;
  12605. },
  12606. "filename4",
  12607. {}});
  12608. {
  12609. auto res = cli.Post("/post-providers", {}, {}, providers);
  12610. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12611. ASSERT_EQ(StatusCode::OK_200, res->status);
  12612. }
  12613. {
  12614. auto res = cli.Post("/post-both", {}, items, providers);
  12615. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12616. ASSERT_EQ(StatusCode::OK_200, res->status);
  12617. }
  12618. }
  12619. }
  12620. TEST(MultipartFormDataTest, BadHeader) {
  12621. Server svr;
  12622. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  12623. res.set_content("ok", "text/plain");
  12624. });
  12625. thread t = thread([&] { svr.listen(HOST, PORT); });
  12626. auto se = detail::scope_exit([&] {
  12627. svr.stop();
  12628. t.join();
  12629. ASSERT_FALSE(svr.is_running());
  12630. });
  12631. svr.wait_until_ready();
  12632. const std::string body =
  12633. "This is the preamble. It is to be ignored, though it\r\n"
  12634. "is a handy place for composition agents to include an\r\n"
  12635. "explanatory note to non-MIME conformant readers.\r\n"
  12636. "\r\n"
  12637. "\r\n"
  12638. "--simple boundary\r\n"
  12639. "Content-Disposition: form-data; name=\"field1\"\r\n"
  12640. ": BAD...\r\n"
  12641. "\r\n"
  12642. "value1\r\n"
  12643. "--simple boundary\r\n"
  12644. "Content-Disposition: form-data; name=\"field2\"; "
  12645. "filename=\"example.txt\"\r\n"
  12646. "\r\n"
  12647. "value2\r\n"
  12648. "--simple boundary--\r\n"
  12649. "This is the epilogue. It is also to be ignored.\r\n";
  12650. std::string content_type =
  12651. R"(multipart/form-data; boundary="simple boundary")";
  12652. Client cli(HOST, PORT);
  12653. auto res = cli.Post("/post", body, content_type.c_str());
  12654. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12655. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  12656. }
  12657. TEST(MultipartFormDataTest, WithPreamble) {
  12658. Server svr;
  12659. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  12660. res.set_content("ok", "text/plain");
  12661. });
  12662. thread t = thread([&] { svr.listen(HOST, PORT); });
  12663. auto se = detail::scope_exit([&] {
  12664. svr.stop();
  12665. t.join();
  12666. ASSERT_FALSE(svr.is_running());
  12667. });
  12668. svr.wait_until_ready();
  12669. const std::string body =
  12670. "This is the preamble. It is to be ignored, though it\r\n"
  12671. "is a handy place for composition agents to include an\r\n"
  12672. "explanatory note to non-MIME conformant readers.\r\n"
  12673. "\r\n"
  12674. "\r\n"
  12675. "--simple boundary\r\n"
  12676. "Content-Disposition: form-data; name=\"field1\"\r\n"
  12677. "\r\n"
  12678. "value1\r\n"
  12679. "--simple boundary\r\n"
  12680. "Content-Disposition: form-data; name=\"field2\"; "
  12681. "filename=\"example.txt\"\r\n"
  12682. "\r\n"
  12683. "value2\r\n"
  12684. "--simple boundary--\r\n"
  12685. "This is the epilogue. It is also to be ignored.\r\n";
  12686. std::string content_type =
  12687. R"(multipart/form-data; boundary="simple boundary")";
  12688. Client cli(HOST, PORT);
  12689. auto res = cli.Post("/post", body, content_type.c_str());
  12690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12691. EXPECT_EQ(StatusCode::OK_200, res->status);
  12692. }
  12693. TEST(MultipartFormDataTest, PostCustomBoundary) {
  12694. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12695. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  12696. const ContentReader &content_reader) {
  12697. if (req.is_multipart_form_data()) {
  12698. std::vector<FormData> items;
  12699. content_reader(
  12700. [&](const FormData &file) {
  12701. items.push_back(file);
  12702. return true;
  12703. },
  12704. [&](const char *data, size_t data_length) {
  12705. items.back().content.append(data, data_length);
  12706. return true;
  12707. });
  12708. EXPECT_TRUE(std::string(items[0].name) == "document");
  12709. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  12710. EXPECT_TRUE(items[0].filename == "2MB_data");
  12711. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  12712. EXPECT_TRUE(items[1].name == "hello");
  12713. EXPECT_TRUE(items[1].content == "world");
  12714. EXPECT_TRUE(items[1].filename == "");
  12715. EXPECT_TRUE(items[1].content_type == "");
  12716. } else {
  12717. std::string body;
  12718. content_reader([&](const char *data, size_t data_length) {
  12719. body.append(data, data_length);
  12720. return true;
  12721. });
  12722. }
  12723. });
  12724. auto port = svr.bind_to_any_port("localhost");
  12725. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12726. auto se = detail::scope_exit([&] {
  12727. svr.stop();
  12728. t.join();
  12729. ASSERT_FALSE(svr.is_running());
  12730. });
  12731. svr.wait_until_ready();
  12732. {
  12733. std::string data(1024 * 1024 * 2, '.');
  12734. std::stringstream buffer;
  12735. buffer << data;
  12736. SSLClient cli("localhost", port);
  12737. cli.enable_server_certificate_verification(false);
  12738. UploadFormDataItems items{
  12739. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  12740. {"hello", "world", "", ""},
  12741. };
  12742. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  12743. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12744. ASSERT_EQ(StatusCode::OK_200, res->status);
  12745. }
  12746. }
  12747. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  12748. std::string data(1024 * 1024 * 2, '&');
  12749. std::stringstream buffer;
  12750. buffer << data;
  12751. Client cli("https://localhost:8080");
  12752. UploadFormDataItems items{
  12753. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  12754. {"hello", "world", "", ""},
  12755. };
  12756. for (const char &c : " \t\r\n") {
  12757. auto res =
  12758. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  12759. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  12760. ASSERT_FALSE(res);
  12761. }
  12762. }
  12763. TEST(MultipartFormDataTest, PutFormData) {
  12764. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12765. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  12766. const ContentReader &content_reader) {
  12767. if (req.is_multipart_form_data()) {
  12768. std::vector<FormData> items;
  12769. content_reader(
  12770. [&](const FormData &file) {
  12771. items.push_back(file);
  12772. return true;
  12773. },
  12774. [&](const char *data, size_t data_length) {
  12775. items.back().content.append(data, data_length);
  12776. return true;
  12777. });
  12778. EXPECT_TRUE(std::string(items[0].name) == "document");
  12779. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  12780. EXPECT_TRUE(items[0].filename == "2MB_data");
  12781. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  12782. EXPECT_TRUE(items[1].name == "hello");
  12783. EXPECT_TRUE(items[1].content == "world");
  12784. EXPECT_TRUE(items[1].filename == "");
  12785. EXPECT_TRUE(items[1].content_type == "");
  12786. } else {
  12787. std::string body;
  12788. content_reader([&](const char *data, size_t data_length) {
  12789. body.append(data, data_length);
  12790. return true;
  12791. });
  12792. }
  12793. });
  12794. auto port = svr.bind_to_any_port("localhost");
  12795. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12796. auto se = detail::scope_exit([&] {
  12797. svr.stop();
  12798. t.join();
  12799. ASSERT_FALSE(svr.is_running());
  12800. });
  12801. svr.wait_until_ready();
  12802. {
  12803. std::string data(1024 * 1024 * 2, '&');
  12804. std::stringstream buffer;
  12805. buffer << data;
  12806. SSLClient cli("localhost", port);
  12807. cli.enable_server_certificate_verification(false);
  12808. UploadFormDataItems items{
  12809. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  12810. {"hello", "world", "", ""},
  12811. };
  12812. auto res = cli.Put("/put", items);
  12813. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12814. ASSERT_EQ(StatusCode::OK_200, res->status);
  12815. }
  12816. }
  12817. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  12818. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12819. svr.Put("/put_customboundary",
  12820. [&](const Request &req, const Response & /*res*/,
  12821. const ContentReader &content_reader) {
  12822. if (req.is_multipart_form_data()) {
  12823. std::vector<FormData> items;
  12824. content_reader(
  12825. [&](const FormData &file) {
  12826. items.push_back(file);
  12827. return true;
  12828. },
  12829. [&](const char *data, size_t data_length) {
  12830. items.back().content.append(data, data_length);
  12831. return true;
  12832. });
  12833. EXPECT_TRUE(std::string(items[0].name) == "document");
  12834. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  12835. EXPECT_TRUE(items[0].filename == "2MB_data");
  12836. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  12837. EXPECT_TRUE(items[1].name == "hello");
  12838. EXPECT_TRUE(items[1].content == "world");
  12839. EXPECT_TRUE(items[1].filename == "");
  12840. EXPECT_TRUE(items[1].content_type == "");
  12841. } else {
  12842. std::string body;
  12843. content_reader([&](const char *data, size_t data_length) {
  12844. body.append(data, data_length);
  12845. return true;
  12846. });
  12847. }
  12848. });
  12849. auto port = svr.bind_to_any_port("localhost");
  12850. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12851. auto se = detail::scope_exit([&] {
  12852. svr.stop();
  12853. t.join();
  12854. ASSERT_FALSE(svr.is_running());
  12855. });
  12856. svr.wait_until_ready();
  12857. {
  12858. std::string data(1024 * 1024 * 2, '&');
  12859. std::stringstream buffer;
  12860. buffer << data;
  12861. SSLClient cli("localhost", port);
  12862. cli.enable_server_certificate_verification(false);
  12863. UploadFormDataItems items{
  12864. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  12865. {"hello", "world", "", ""},
  12866. };
  12867. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  12868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12869. ASSERT_EQ(StatusCode::OK_200, res->status);
  12870. }
  12871. }
  12872. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  12873. std::string data(1024 * 1024 * 2, '&');
  12874. std::stringstream buffer;
  12875. buffer << data;
  12876. Client cli("https://localhost:8080");
  12877. cli.enable_server_certificate_verification(false);
  12878. UploadFormDataItems items{
  12879. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  12880. {"hello", "world", "", ""},
  12881. };
  12882. for (const char &c : " \t\r\n") {
  12883. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  12884. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  12885. ASSERT_FALSE(res);
  12886. }
  12887. }
  12888. TEST(MultipartFormDataTest, AlternateFilename) {
  12889. auto handled = false;
  12890. Server svr;
  12891. svr.Post("/test", [&](const Request &req, Response &res) {
  12892. ASSERT_EQ(2u, req.form.files.size());
  12893. ASSERT_EQ(1u, req.form.fields.size());
  12894. // Test files
  12895. const auto &file1 = req.form.get_file("file1");
  12896. ASSERT_EQ("file1", file1.name);
  12897. ASSERT_EQ("A.txt", file1.filename);
  12898. ASSERT_EQ("text/plain", file1.content_type);
  12899. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  12900. const auto &file2 = req.form.get_file("file2");
  12901. ASSERT_EQ("file2", file2.name);
  12902. ASSERT_EQ("a.html", file2.filename);
  12903. ASSERT_EQ("text/html", file2.content_type);
  12904. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  12905. file2.content);
  12906. // Test text field
  12907. const auto &text = req.form.get_field("text");
  12908. ASSERT_EQ("text default", text);
  12909. res.set_content("ok", "text/plain");
  12910. handled = true;
  12911. });
  12912. thread t = thread([&] { svr.listen(HOST, PORT); });
  12913. auto se = detail::scope_exit([&] {
  12914. svr.stop();
  12915. t.join();
  12916. ASSERT_FALSE(svr.is_running());
  12917. ASSERT_TRUE(handled);
  12918. });
  12919. svr.wait_until_ready();
  12920. auto req = "POST /test HTTP/1.1\r\n"
  12921. "Content-Type: multipart/form-data;boundary=--------\r\n"
  12922. "Content-Length: 399\r\n"
  12923. "\r\n"
  12924. "----------\r\n"
  12925. "Content-Disposition: form-data; name=\"text\"\r\n"
  12926. "\r\n"
  12927. "text default\r\n"
  12928. "----------\r\n"
  12929. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  12930. "filename=\"a.txt\"; name=\"file1\"\r\n"
  12931. "Content-Type: text/plain\r\n"
  12932. "\r\n"
  12933. "Content of a.txt.\r\n"
  12934. "\r\n"
  12935. "----------\r\n"
  12936. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  12937. "\"a.html\"\r\n"
  12938. "Content-Type: text/html\r\n"
  12939. "\r\n"
  12940. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  12941. "\r\n"
  12942. "------------\r\n";
  12943. ASSERT_TRUE(send_request(1, req));
  12944. }
  12945. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  12946. auto handled = false;
  12947. Server svr;
  12948. svr.Post("/test", [&](const Request &req, Response &res) {
  12949. // Case-insensitive "utf-8''" prefix with a long value
  12950. const auto &file = req.form.get_file("file1");
  12951. ASSERT_EQ("file1", file.name);
  12952. // 8000 chars exercises both the Content-Disposition parser and the
  12953. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  12954. // Prior to the fix, std::regex_match on this header would cause O(N)
  12955. // stack recursion in libstdc++, leading to SIGSEGV.
  12956. std::string expected_filename(8000, 'A');
  12957. ASSERT_EQ(expected_filename, file.filename);
  12958. res.set_content("ok", "text/plain");
  12959. handled = true;
  12960. });
  12961. thread t = thread([&] { svr.listen(HOST, PORT); });
  12962. auto se = detail::scope_exit([&] {
  12963. svr.stop();
  12964. t.join();
  12965. ASSERT_FALSE(svr.is_running());
  12966. ASSERT_TRUE(handled);
  12967. });
  12968. svr.wait_until_ready();
  12969. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  12970. // Regression test for GHSA-qq6v-r583-3h69
  12971. std::string long_filename(8000, 'A');
  12972. std::string body = "----------\r\n"
  12973. "Content-Disposition: form-data; name=\"file1\"; "
  12974. "filename*=\"Utf-8''" +
  12975. long_filename +
  12976. "\"\r\n"
  12977. "\r\n"
  12978. "hello\r\n"
  12979. "------------\r\n";
  12980. auto req = "POST /test HTTP/1.1\r\n"
  12981. "Content-Type: multipart/form-data;boundary=--------\r\n"
  12982. "Content-Length: " +
  12983. std::to_string(body.size()) + "\r\n\r\n" + body;
  12984. ASSERT_TRUE(send_request(1, req));
  12985. }
  12986. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  12987. auto handled = false;
  12988. Server svr;
  12989. svr.Post("/test", [&](const Request &req, Response &) {
  12990. ASSERT_EQ(2u, req.form.fields.size());
  12991. const auto &text1 = req.form.get_field("text1");
  12992. ASSERT_EQ("text1", text1);
  12993. const auto &text2 = req.form.get_field("text2");
  12994. ASSERT_EQ("text2", text2);
  12995. handled = true;
  12996. });
  12997. thread t = thread([&] { svr.listen(HOST, PORT); });
  12998. auto se = detail::scope_exit([&] {
  12999. svr.stop();
  13000. t.join();
  13001. ASSERT_FALSE(svr.is_running());
  13002. ASSERT_TRUE(handled);
  13003. });
  13004. svr.wait_until_ready();
  13005. auto req = "POST /test HTTP/1.1\r\n"
  13006. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13007. "Content-Length: 146\r\n"
  13008. "\r\n----------\r\n"
  13009. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13010. "\r\n"
  13011. "text1"
  13012. "\r\n----------\r\n"
  13013. "Content-Disposition: form-data; name=\"text2\"\r\n"
  13014. "\r\n"
  13015. "text2"
  13016. "\r\n------------";
  13017. std::string response;
  13018. ASSERT_TRUE(send_request(1, req, &response));
  13019. ASSERT_EQ("200", response.substr(9, 3));
  13020. }
  13021. TEST(MultipartFormDataTest, ContentLength) {
  13022. auto handled = false;
  13023. Server svr;
  13024. svr.Post("/test", [&](const Request &req, Response &) {
  13025. ASSERT_EQ(2u, req.form.fields.size());
  13026. const auto &text1 = req.form.get_field("text1");
  13027. ASSERT_EQ("text1", text1);
  13028. const auto &text2 = req.form.get_field("text2");
  13029. ASSERT_EQ("text2", text2);
  13030. handled = true;
  13031. });
  13032. thread t = thread([&] { svr.listen(HOST, PORT); });
  13033. auto se = detail::scope_exit([&] {
  13034. svr.stop();
  13035. t.join();
  13036. ASSERT_FALSE(svr.is_running());
  13037. ASSERT_TRUE(handled);
  13038. });
  13039. svr.wait_until_ready();
  13040. auto req = "POST /test HTTP/1.1\r\n"
  13041. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13042. "Content-Length: 167\r\n"
  13043. "\r\n----------\r\n"
  13044. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13045. "Content-Length: 5\r\n"
  13046. "\r\n"
  13047. "text1"
  13048. "\r\n----------\r\n"
  13049. "Content-Disposition: form-data; name=\"text2\"\r\n"
  13050. "\r\n"
  13051. "text2"
  13052. "\r\n------------\r\n";
  13053. std::string response;
  13054. ASSERT_TRUE(send_request(1, req, &response));
  13055. ASSERT_EQ("200", response.substr(9, 3));
  13056. }
  13057. TEST(MultipartFormDataTest, AccessPartHeaders) {
  13058. auto handled = false;
  13059. Server svr;
  13060. svr.Post("/test", [&](const Request &req, Response &) {
  13061. ASSERT_EQ(2u, req.form.fields.size());
  13062. const auto &text1 = req.form.get_field("text1");
  13063. ASSERT_EQ("text1", text1);
  13064. // TODO: Add header access for text fields if needed
  13065. const auto &text2 = req.form.get_field("text2");
  13066. ASSERT_EQ("text2", text2);
  13067. // TODO: Header access for text fields needs to be implemented
  13068. // auto &headers = it->second.headers;
  13069. // ASSERT_EQ(3U, headers.size());
  13070. // auto custom_header = headers.find("x-whatever");
  13071. // ASSERT_TRUE(custom_header != headers.end());
  13072. // ASSERT_NE("customvalue", custom_header->second);
  13073. // ASSERT_EQ("CustomValue", custom_header->second);
  13074. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  13075. handled = true;
  13076. });
  13077. thread t = thread([&] { svr.listen(HOST, PORT); });
  13078. auto se = detail::scope_exit([&] {
  13079. svr.stop();
  13080. t.join();
  13081. ASSERT_FALSE(svr.is_running());
  13082. ASSERT_TRUE(handled);
  13083. });
  13084. svr.wait_until_ready();
  13085. auto req = "POST /test HTTP/1.1\r\n"
  13086. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13087. "Content-Length: 232\r\n"
  13088. "\r\n----------\r\n"
  13089. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13090. "Content-Length: 5\r\n"
  13091. "X-Test: 1\r\n"
  13092. "\r\n"
  13093. "text1"
  13094. "\r\n----------\r\n"
  13095. "Content-Disposition: form-data; name=\"text2\"\r\n"
  13096. "Content-Type: text/plain\r\n"
  13097. "X-Whatever: CustomValue\r\n"
  13098. "\r\n"
  13099. "text2"
  13100. "\r\n------------\r\n"
  13101. "That should be disregarded. Not even read";
  13102. std::string response;
  13103. ASSERT_TRUE(send_request(1, req, &response));
  13104. ASSERT_EQ("200", response.substr(9, 3));
  13105. }
  13106. TEST(MultipartFormDataTest, LargeHeader) {
  13107. auto handled = false;
  13108. Server svr;
  13109. svr.Post("/test", [&](const Request &req, Response &) {
  13110. ASSERT_EQ(1u, req.form.fields.size());
  13111. const auto &text = req.form.get_field("name1");
  13112. ASSERT_EQ("text1", text);
  13113. handled = true;
  13114. });
  13115. thread t = thread([&] { svr.listen(HOST, PORT); });
  13116. auto se = detail::scope_exit([&] {
  13117. svr.stop();
  13118. t.join();
  13119. ASSERT_FALSE(svr.is_running());
  13120. ASSERT_TRUE(handled);
  13121. });
  13122. svr.wait_until_ready();
  13123. auto boundary = std::string("cpp-httplib-multipart-data");
  13124. std::string content = "--" + boundary +
  13125. "\r\n"
  13126. "Content-Disposition: form-data; name=\"name1\"\r\n"
  13127. "\r\n"
  13128. "text1\r\n"
  13129. "--" +
  13130. boundary + "--\r\n";
  13131. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  13132. "Content-Type: multipart/form-data;boundary=" +
  13133. boundary +
  13134. "\r\n"
  13135. "Content-Length: " +
  13136. std::to_string(content.size()) +
  13137. "\r\n"
  13138. "Dummy-Header: ";
  13139. std::string header_suffix = "\r\n"
  13140. "\r\n";
  13141. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  13142. size_t header_dummy_size =
  13143. read_buff_size -
  13144. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  13145. auto header_dummy = std::string(header_dummy_size, '@');
  13146. auto req = header_prefix + header_dummy + header_suffix + content;
  13147. std::string response;
  13148. ASSERT_TRUE(send_request(1, req, &response));
  13149. ASSERT_EQ("200", response.substr(9, 3));
  13150. }
  13151. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  13152. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  13153. // (not chunked Transfer-Encoding) after the streaming refactor.
  13154. auto handled = false;
  13155. Server svr;
  13156. svr.Post("/upload", [&](const Request &req, Response &res) {
  13157. auto cl_it = req.headers.find("Content-Length");
  13158. EXPECT_TRUE(cl_it != req.headers.end());
  13159. auto te_it = req.headers.find("Transfer-Encoding");
  13160. EXPECT_TRUE(te_it == req.headers.end());
  13161. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  13162. res.set_content("ok", "text/plain");
  13163. handled = true;
  13164. });
  13165. auto port = svr.bind_to_any_port(HOST);
  13166. auto t = thread([&] { svr.listen_after_bind(); });
  13167. auto se = detail::scope_exit([&] {
  13168. svr.stop();
  13169. t.join();
  13170. ASSERT_FALSE(svr.is_running());
  13171. ASSERT_TRUE(handled);
  13172. });
  13173. svr.wait_until_ready();
  13174. UploadFormDataItems items = {
  13175. {"field1", "hello", "", "text/plain"},
  13176. {"file1", "world", "test.txt", "application/octet-stream"},
  13177. };
  13178. Client cli(HOST, port);
  13179. auto res = cli.Post("/upload", {}, items);
  13180. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13181. EXPECT_EQ(StatusCode::OK_200, res->status);
  13182. }
  13183. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  13184. // Verify that make_multipart_content_provider coalesces many small segments
  13185. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  13186. constexpr size_t kItemCount = 1000;
  13187. UploadFormDataItems items;
  13188. items.reserve(kItemCount);
  13189. for (size_t i = 0; i < kItemCount; i++) {
  13190. items.push_back(
  13191. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  13192. }
  13193. const std::string boundary = "----test-boundary";
  13194. auto content_length = detail::get_multipart_content_length(items, boundary);
  13195. auto provider = detail::make_multipart_content_provider(items, boundary);
  13196. // Drive the provider the same way write_content_with_progress does
  13197. size_t write_count = 0;
  13198. size_t total_bytes = 0;
  13199. DataSink sink;
  13200. size_t offset = 0;
  13201. sink.write = [&](const char *d, size_t l) -> bool {
  13202. (void)d;
  13203. write_count++;
  13204. total_bytes += l;
  13205. offset += l;
  13206. return true;
  13207. };
  13208. sink.is_writable = []() -> bool { return true; };
  13209. while (offset < content_length) {
  13210. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  13211. }
  13212. EXPECT_EQ(content_length, total_bytes);
  13213. // The total number of segments is 3 * kItemCount + 1 = 3001.
  13214. // With buffering into 64KB blocks, write_count should be much smaller.
  13215. auto segment_count = 3 * kItemCount + 1;
  13216. EXPECT_LT(write_count, segment_count / 10);
  13217. }
  13218. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  13219. // Integration test: send many UploadFormDataItems and verify the server
  13220. // receives all of them correctly (#2410).
  13221. constexpr size_t kItemCount = 500;
  13222. auto handled = false;
  13223. Server svr;
  13224. svr.Post("/upload", [&](const Request &req, Response &res) {
  13225. EXPECT_EQ(kItemCount, req.form.fields.size());
  13226. for (size_t i = 0; i < kItemCount; i++) {
  13227. auto key = "field" + std::to_string(i);
  13228. auto val = "value" + std::to_string(i);
  13229. auto it = req.form.fields.find(key);
  13230. if (it != req.form.fields.end()) {
  13231. EXPECT_EQ(val, it->second.content);
  13232. } else {
  13233. ADD_FAILURE() << "Missing field: " << key;
  13234. }
  13235. }
  13236. res.set_content("ok", "text/plain");
  13237. handled = true;
  13238. });
  13239. auto port = svr.bind_to_any_port(HOST);
  13240. auto t = thread([&] { svr.listen_after_bind(); });
  13241. auto se = detail::scope_exit([&] {
  13242. svr.stop();
  13243. t.join();
  13244. ASSERT_FALSE(svr.is_running());
  13245. ASSERT_TRUE(handled);
  13246. });
  13247. svr.wait_until_ready();
  13248. UploadFormDataItems items;
  13249. items.reserve(kItemCount);
  13250. for (size_t i = 0; i < kItemCount; i++) {
  13251. items.push_back(
  13252. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  13253. }
  13254. Client cli(HOST, port);
  13255. auto res = cli.Post("/upload", items);
  13256. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13257. EXPECT_EQ(StatusCode::OK_200, res->status);
  13258. }
  13259. TEST(MultipartFormDataTest, MakeFileProvider) {
  13260. // Verify make_file_provider sends a file's contents correctly.
  13261. const std::string file_content(4096, 'Z');
  13262. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  13263. {
  13264. std::ofstream ofs(tmp_path, std::ios::binary);
  13265. ofs.write(file_content.data(),
  13266. static_cast<std::streamsize>(file_content.size()));
  13267. }
  13268. auto handled = false;
  13269. Server svr;
  13270. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  13271. const ContentReader &content_reader) {
  13272. ASSERT_TRUE(req.is_multipart_form_data());
  13273. std::vector<FormData> items;
  13274. content_reader(
  13275. [&](const FormData &file) {
  13276. items.push_back(file);
  13277. return true;
  13278. },
  13279. [&](const char *data, size_t data_length) {
  13280. items.back().content.append(data, data_length);
  13281. return true;
  13282. });
  13283. ASSERT_EQ(1u, items.size());
  13284. EXPECT_EQ("myfile", items[0].name);
  13285. EXPECT_EQ("data.bin", items[0].filename);
  13286. EXPECT_EQ("application/octet-stream", items[0].content_type);
  13287. EXPECT_EQ(file_content, items[0].content);
  13288. handled = true;
  13289. });
  13290. auto port = svr.bind_to_any_port(HOST);
  13291. auto t = thread([&] { svr.listen_after_bind(); });
  13292. auto se = detail::scope_exit([&] {
  13293. svr.stop();
  13294. t.join();
  13295. ASSERT_FALSE(svr.is_running());
  13296. ASSERT_TRUE(handled);
  13297. std::remove(tmp_path.c_str());
  13298. });
  13299. svr.wait_until_ready();
  13300. FormDataProviderItems providers;
  13301. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  13302. "application/octet-stream"));
  13303. Client cli(HOST, port);
  13304. auto res = cli.Post("/upload", {}, {}, providers);
  13305. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13306. EXPECT_EQ(StatusCode::OK_200, res->status);
  13307. }
  13308. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  13309. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  13310. // (100) headers is rejected with a 400 Bad Request response.
  13311. Server svr;
  13312. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  13313. res.set_content("ok", "text/plain");
  13314. });
  13315. thread t = thread([&] { svr.listen(HOST, PORT); });
  13316. auto se = detail::scope_exit([&] {
  13317. svr.stop();
  13318. t.join();
  13319. ASSERT_FALSE(svr.is_running());
  13320. });
  13321. svr.wait_until_ready();
  13322. // Build a multipart part with 101 custom headers (exceeding
  13323. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  13324. std::stringstream body;
  13325. body << "--simpleboundary\r\n"
  13326. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  13327. for (int i = 0; i < 101; i++) {
  13328. body << "X-Custom-Header-" << i << ": value\r\n";
  13329. }
  13330. body << "\r\n"
  13331. << "value1\r\n"
  13332. << "--simpleboundary--\r\n";
  13333. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  13334. Client cli(HOST, PORT);
  13335. auto res = cli.Post("/post", body.str(), content_type.c_str());
  13336. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13337. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  13338. }
  13339. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  13340. // A body that never contains the declared boundary must not be accumulated
  13341. // while the parser waits for it. Buffering it would also make every read
  13342. // rescan everything seen so far, which is quadratic in the body size.
  13343. Server svr;
  13344. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  13345. res.set_content("ok", "text/plain");
  13346. });
  13347. auto port = svr.bind_to_any_port(HOST);
  13348. thread t = thread([&] { svr.listen_after_bind(); });
  13349. auto se = detail::scope_exit([&] {
  13350. svr.stop();
  13351. t.join();
  13352. ASSERT_FALSE(svr.is_running());
  13353. });
  13354. svr.wait_until_ready();
  13355. Client cli(HOST, port);
  13356. cli.set_read_timeout(60, 0);
  13357. cli.set_write_timeout(60, 0);
  13358. // '-' is the worst case: it matches the first character of the boundary, so
  13359. // every position has to be checked against it.
  13360. auto post_dashes = [&](size_t size) {
  13361. const std::string body(size, '-');
  13362. auto start = std::chrono::steady_clock::now();
  13363. auto res =
  13364. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  13365. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  13366. std::chrono::steady_clock::now() - start)
  13367. .count();
  13368. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  13369. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  13370. return ms;
  13371. };
  13372. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  13373. // Windows.
  13374. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  13375. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  13376. // Comparing the two sizes rather than checking an absolute duration keeps
  13377. // this meaningful across build types and CI load, both of which move the
  13378. // absolute numbers by more than an order of magnitude. Four times the bytes
  13379. // costs about four times the time when parsing is linear, and about sixteen
  13380. // times when the body is buffered and rescanned.
  13381. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  13382. EXPECT_LT(ms_16mb, ms_4mb * 10)
  13383. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  13384. << "ms, which suggests the body is being buffered and rescanned";
  13385. }
  13386. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  13387. // A boundary can only be followed by CRLF or by "--", so anything else is
  13388. // malformed no matter what comes next. The parser must say so right away
  13389. // instead of buffering the rest of the declared body.
  13390. Server svr;
  13391. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  13392. res.set_content("ok", "text/plain");
  13393. });
  13394. auto port = svr.bind_to_any_port(HOST);
  13395. thread t = thread([&] { svr.listen_after_bind(); });
  13396. auto se = detail::scope_exit([&] {
  13397. svr.stop();
  13398. t.join();
  13399. ASSERT_FALSE(svr.is_running());
  13400. });
  13401. svr.wait_until_ready();
  13402. // Announce a 1 MB body but send only the malformed prefix. A parser that
  13403. // buffers instead of failing would still be waiting for the remaining bytes.
  13404. const std::string body = "--zzzz\r\n"
  13405. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13406. "\r\n"
  13407. "text1"
  13408. "\r\n--zzzzXX";
  13409. const std::string req = "POST /post HTTP/1.1\r\n"
  13410. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  13411. "Content-Length: 1048576\r\n"
  13412. "\r\n" +
  13413. body;
  13414. std::string response;
  13415. ASSERT_TRUE(send_request(3, req, &response, port));
  13416. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  13417. EXPECT_EQ("400", response.substr(9, 3));
  13418. }
  13419. // Posts a multipart body split into two writes, so that the server sees the
  13420. // split at whatever offset the caller chose, and expects the single "text1"
  13421. // field to come through.
  13422. static void expect_split_multipart_ok(const std::string &body1,
  13423. const std::string &body2) {
  13424. auto handled = false;
  13425. Server svr;
  13426. svr.Post("/post", [&](const Request &req, Response &) {
  13427. EXPECT_EQ(1u, req.form.fields.size());
  13428. EXPECT_EQ("text1", req.form.get_field("text1"));
  13429. handled = true;
  13430. });
  13431. auto port = svr.bind_to_any_port(HOST);
  13432. thread t = thread([&] { svr.listen_after_bind(); });
  13433. auto se = detail::scope_exit([&] {
  13434. svr.stop();
  13435. t.join();
  13436. ASSERT_FALSE(svr.is_running());
  13437. ASSERT_TRUE(handled);
  13438. });
  13439. svr.wait_until_ready();
  13440. // "Connection: close" makes the server close once it has answered, so the
  13441. // response drain ends immediately instead of idling until the read timeout.
  13442. const std::string head =
  13443. "POST /post HTTP/1.1\r\n"
  13444. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  13445. "Connection: close\r\n"
  13446. "Content-Length: " +
  13447. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  13448. std::string response;
  13449. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  13450. ASSERT_GE(response.size(), 12u) << "no response";
  13451. EXPECT_EQ("200", response.substr(9, 3));
  13452. }
  13453. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  13454. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  13455. // ignored, including when it does not arrive in the same read as the
  13456. // close-delimiter itself.
  13457. expect_split_multipart_ok("--zzzz\r\n"
  13458. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13459. "\r\n"
  13460. "text1"
  13461. "\r\n--zzzz--",
  13462. "\r\nthis epilogue must be ignored\r\n");
  13463. }
  13464. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  13465. // The initial boundary may be preceded by a preamble of any length and may
  13466. // straddle a read boundary. Discarding data while waiting for it must not
  13467. // throw away a partial boundary sitting at the end of the buffer.
  13468. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  13469. "zz\r\n"
  13470. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13471. "\r\n"
  13472. "text1"
  13473. "\r\n--zzzz--\r\n");
  13474. }
  13475. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  13476. // The received boundary was only checked for being non-empty, so it could be
  13477. // as long as a header is allowed to be. The parser scans the body for
  13478. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  13479. // costs a nearly full comparison at nearly every position, making the
  13480. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  13481. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  13482. Server svr;
  13483. svr.Post("/post", [](const Request &req, Response &res) {
  13484. EXPECT_EQ(1u, req.form.fields.size());
  13485. EXPECT_EQ("text1", req.form.get_field("text1"));
  13486. res.set_content("ok", "text/plain");
  13487. });
  13488. auto port = svr.bind_to_any_port(HOST);
  13489. thread t = thread([&] { svr.listen_after_bind(); });
  13490. auto se = detail::scope_exit([&] {
  13491. svr.stop();
  13492. t.join();
  13493. ASSERT_FALSE(svr.is_running());
  13494. });
  13495. svr.wait_until_ready();
  13496. Client cli(HOST, port);
  13497. auto post_with_boundary_of_length = [&](size_t len) {
  13498. const std::string boundary(len, 'a');
  13499. const std::string body =
  13500. "--" + boundary +
  13501. "\r\n"
  13502. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13503. "\r\n"
  13504. "text1"
  13505. "\r\n--" +
  13506. boundary + "--\r\n";
  13507. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  13508. };
  13509. auto res = post_with_boundary_of_length(70);
  13510. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13511. EXPECT_EQ(StatusCode::OK_200, res->status);
  13512. res = post_with_boundary_of_length(71);
  13513. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13514. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  13515. }
  13516. TEST(MakeFileBodyTest, Basic) {
  13517. const std::string file_content(4096, 'Z');
  13518. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  13519. {
  13520. std::ofstream ofs(tmp_path, std::ios::binary);
  13521. ofs.write(file_content.data(),
  13522. static_cast<std::streamsize>(file_content.size()));
  13523. }
  13524. auto handled = false;
  13525. Server svr;
  13526. svr.Post("/upload", [&](const Request &req, Response &res) {
  13527. EXPECT_EQ(file_content, req.body);
  13528. handled = true;
  13529. res.status = StatusCode::OK_200;
  13530. });
  13531. auto port = svr.bind_to_any_port(HOST);
  13532. auto t = thread([&] { svr.listen_after_bind(); });
  13533. auto se = detail::scope_exit([&] {
  13534. svr.stop();
  13535. t.join();
  13536. ASSERT_FALSE(svr.is_running());
  13537. ASSERT_TRUE(handled);
  13538. std::remove(tmp_path.c_str());
  13539. });
  13540. svr.wait_until_ready();
  13541. auto fb = make_file_body(tmp_path);
  13542. ASSERT_GT(fb.first, 0u);
  13543. Client cli(HOST, port);
  13544. auto res =
  13545. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  13546. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13547. EXPECT_EQ(StatusCode::OK_200, res->status);
  13548. }
  13549. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  13550. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  13551. {
  13552. std::ofstream ofs(path, std::ios::binary);
  13553. const std::string content(100, 'A');
  13554. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  13555. }
  13556. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  13557. auto body = make_file_body(path);
  13558. ASSERT_EQ(100u, body.first);
  13559. ASSERT_TRUE(static_cast<bool>(body.second));
  13560. // Rewritten shorter after its length was measured - and, on a server, after
  13561. // that length has already gone out as Content-Length.
  13562. {
  13563. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  13564. const std::string content(10, 'A');
  13565. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  13566. }
  13567. std::string written;
  13568. DataSink sink;
  13569. sink.write = [&](const char *d, size_t l) {
  13570. written.append(d, l);
  13571. return true;
  13572. };
  13573. // The provider has to report failure. write_content_with_progress() advances
  13574. // its offset only by what was written, so a provider that returns true
  13575. // without completing the length it promised is called again straight away,
  13576. // and again.
  13577. EXPECT_FALSE(body.second(0, body.first, sink));
  13578. EXPECT_EQ(std::string(10, 'A'), written);
  13579. }
  13580. TEST(MakeFileBodyTest, WholeFileIsSent) {
  13581. const std::string path = "./httplib_test_make_file_body_whole.bin";
  13582. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  13583. {
  13584. std::ofstream ofs(path, std::ios::binary);
  13585. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  13586. }
  13587. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  13588. auto body = make_file_body(path);
  13589. ASSERT_EQ(content.size(), body.first);
  13590. ASSERT_TRUE(static_cast<bool>(body.second));
  13591. std::string written;
  13592. DataSink sink;
  13593. sink.write = [&](const char *d, size_t l) {
  13594. written.append(d, l);
  13595. return true;
  13596. };
  13597. EXPECT_TRUE(body.second(0, body.first, sink));
  13598. EXPECT_EQ(content, written);
  13599. }
  13600. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  13601. static constexpr unsigned int number_of_tasks{1000000};
  13602. std::atomic_uint count{0};
  13603. std::unique_ptr<TaskQueue> task_queue{
  13604. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  13605. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  13606. auto queued = task_queue->enqueue(
  13607. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  13608. EXPECT_TRUE(queued);
  13609. }
  13610. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  13611. task_queue->shutdown();
  13612. #else
  13613. EXPECT_NO_THROW(task_queue->shutdown());
  13614. #endif
  13615. EXPECT_EQ(number_of_tasks, count.load());
  13616. }
  13617. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  13618. static constexpr unsigned int number_of_tasks{1000000};
  13619. static constexpr unsigned int qlimit{2};
  13620. unsigned int queued_count{0};
  13621. std::atomic_uint count{0};
  13622. std::unique_ptr<TaskQueue> task_queue{
  13623. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  13624. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  13625. if (task_queue->enqueue(
  13626. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  13627. queued_count++;
  13628. }
  13629. }
  13630. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  13631. task_queue->shutdown();
  13632. #else
  13633. EXPECT_NO_THROW(task_queue->shutdown());
  13634. #endif
  13635. EXPECT_EQ(queued_count, count.load());
  13636. EXPECT_TRUE(queued_count <= number_of_tasks);
  13637. EXPECT_TRUE(queued_count >= qlimit);
  13638. }
  13639. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  13640. // Use a short idle timeout so a dynamic thread spawns, times out and
  13641. // exits during the test, and the pool keeps working afterwards.
  13642. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  13643. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  13644. /*idle_timeout_sec=*/1}};
  13645. std::atomic_uint count{0};
  13646. std::condition_variable cv;
  13647. std::mutex mtx;
  13648. bool release = false;
  13649. // Block the base thread so the second task spawns a dynamic thread.
  13650. EXPECT_TRUE(task_queue->enqueue([&] {
  13651. std::unique_lock<std::mutex> lock(mtx);
  13652. while (!release) {
  13653. cv.wait(lock);
  13654. }
  13655. count++;
  13656. }));
  13657. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  13658. // Let the dynamic thread finish its task and exceed the idle timeout.
  13659. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  13660. {
  13661. std::unique_lock<std::mutex> lock(mtx);
  13662. release = true;
  13663. }
  13664. cv.notify_all();
  13665. // The pool must still accept and run tasks after the dynamic thread exited.
  13666. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  13667. task_queue->shutdown();
  13668. EXPECT_EQ(3u, count.load());
  13669. }
  13670. TEST(TaskQueueTest, MaxQueuedRequests) {
  13671. static constexpr unsigned int qlimit{3};
  13672. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  13673. std::condition_variable sem_cv;
  13674. std::mutex sem_mtx;
  13675. int credits = 0;
  13676. bool queued;
  13677. /* Fill up the queue with tasks that will block until we give them credits to
  13678. * complete. */
  13679. for (unsigned int n = 0; n <= qlimit;) {
  13680. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  13681. std::unique_lock<std::mutex> lock(sem_mtx);
  13682. while (credits <= 0) {
  13683. sem_cv.wait(lock);
  13684. }
  13685. /* Consume the credit and signal the test code if they are all gone. */
  13686. if (--credits == 0) { sem_cv.notify_one(); }
  13687. });
  13688. if (n < qlimit) {
  13689. /* The first qlimit enqueues must succeed. */
  13690. EXPECT_TRUE(queued);
  13691. } else {
  13692. /* The last one will succeed only when the worker thread
  13693. * starts and dequeues the first blocking task. Although
  13694. * not necessary for the correctness of this test, we sleep for
  13695. * a short while to avoid busy waiting. */
  13696. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  13697. }
  13698. if (queued) { n++; }
  13699. }
  13700. /* Further enqueues must fail since the queue is full. */
  13701. for (auto i = 0; i < 4; i++) {
  13702. queued = task_queue->enqueue([] {});
  13703. EXPECT_FALSE(queued);
  13704. }
  13705. /* Give the credits to allow the previous tasks to complete. */
  13706. {
  13707. std::unique_lock<std::mutex> lock(sem_mtx);
  13708. credits += qlimit + 1;
  13709. }
  13710. sem_cv.notify_all();
  13711. /* Wait for all the credits to be consumed. */
  13712. {
  13713. std::unique_lock<std::mutex> lock(sem_mtx);
  13714. while (credits > 0) {
  13715. sem_cv.wait(lock);
  13716. }
  13717. }
  13718. /* Check that we are able again to enqueue at least qlimit tasks. */
  13719. for (unsigned int i = 0; i < qlimit; i++) {
  13720. queued = task_queue->enqueue([] {});
  13721. EXPECT_TRUE(queued);
  13722. }
  13723. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  13724. task_queue->shutdown();
  13725. #else
  13726. EXPECT_NO_THROW(task_queue->shutdown());
  13727. #endif
  13728. }
  13729. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  13730. Server svr;
  13731. svr.Get("/", [](const Request & /*req*/, Response &res) {
  13732. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  13733. });
  13734. svr.Get("/hello", [](const Request &req, Response &res) {
  13735. res.set_content(req.get_param_value("key"), "text/plain");
  13736. });
  13737. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13738. auto se = detail::scope_exit([&] {
  13739. svr.stop();
  13740. thread.join();
  13741. ASSERT_FALSE(svr.is_running());
  13742. });
  13743. svr.wait_until_ready();
  13744. {
  13745. Client cli(HOST, PORT);
  13746. cli.set_follow_location(true);
  13747. auto res = cli.Get("/");
  13748. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13749. EXPECT_EQ(StatusCode::OK_200, res->status);
  13750. EXPECT_EQ("val&key2=val2", res->body);
  13751. }
  13752. }
  13753. #endif
  13754. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  13755. Server svr;
  13756. svr.Get("/", [](const Request & /*req*/, Response &res) {
  13757. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  13758. });
  13759. svr.Get("/hello", [](const Request &req, Response &res) {
  13760. res.set_content(req.get_param_value("key"), "text/plain");
  13761. });
  13762. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13763. auto se = detail::scope_exit([&] {
  13764. svr.stop();
  13765. thread.join();
  13766. ASSERT_FALSE(svr.is_running());
  13767. });
  13768. svr.wait_until_ready();
  13769. {
  13770. Client cli(HOST, PORT);
  13771. cli.set_follow_location(true);
  13772. auto res = cli.Get("/");
  13773. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13774. EXPECT_EQ(StatusCode::OK_200, res->status);
  13775. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  13776. }
  13777. }
  13778. TEST(RedirectTest, RedirectWithPlusInPath) {
  13779. Server svr;
  13780. svr.Get("/", [](const Request & /*req*/, Response &res) {
  13781. res.set_redirect("/a+b");
  13782. });
  13783. // Route pattern uses regex; escape + as \\+
  13784. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  13785. res.set_content(req.path, "text/plain");
  13786. });
  13787. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13788. auto se = detail::scope_exit([&] {
  13789. svr.stop();
  13790. thread.join();
  13791. ASSERT_FALSE(svr.is_running());
  13792. });
  13793. svr.wait_until_ready();
  13794. {
  13795. Client cli(HOST, PORT);
  13796. cli.set_follow_location(true);
  13797. auto res = cli.Get("/");
  13798. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13799. EXPECT_EQ(StatusCode::OK_200, res->status);
  13800. EXPECT_EQ("/a+b", res->body);
  13801. }
  13802. }
  13803. #ifdef CPPHTTPLIB_SSL_ENABLED
  13804. TEST(RedirectTest, Issue2185_Online) {
  13805. SSLClient client("github.com");
  13806. client.set_follow_location(true);
  13807. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  13808. "Coollab-Windows.zip");
  13809. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13810. EXPECT_EQ(StatusCode::OK_200, res->status);
  13811. EXPECT_EQ(9920427U, res->body.size());
  13812. }
  13813. #endif
  13814. TEST(VulnerabilityTest, CRLFInjection) {
  13815. Server svr;
  13816. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  13817. res.set_content("Hello 1", "text/plain");
  13818. });
  13819. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  13820. res.set_content("Hello 2", "text/plain");
  13821. });
  13822. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  13823. res.set_content("Hello 3", "text/plain");
  13824. });
  13825. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  13826. res.set_content("Hello 4", "text/plain");
  13827. });
  13828. svr.set_logger([](const Request &req, const Response & /*res*/) {
  13829. for (const auto &x : req.headers) {
  13830. auto key = x.first;
  13831. EXPECT_STRNE("evil", key.c_str());
  13832. }
  13833. });
  13834. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13835. auto se = detail::scope_exit([&] {
  13836. svr.stop();
  13837. thread.join();
  13838. ASSERT_FALSE(svr.is_running());
  13839. });
  13840. svr.wait_until_ready();
  13841. {
  13842. Client cli(HOST, PORT);
  13843. cli.Post("/test1", "A=B",
  13844. "application/x-www-form-urlencoded\r\nevil: hello1");
  13845. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  13846. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  13847. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  13848. }
  13849. }
  13850. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  13851. auto server_thread = std::thread([] {
  13852. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13853. default_socket_options(srv);
  13854. sockaddr_in addr{};
  13855. addr.sin_family = AF_INET;
  13856. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  13857. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13858. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13859. ::listen(srv, 1);
  13860. sockaddr_in cli_addr{};
  13861. socklen_t cli_len = sizeof(cli_addr);
  13862. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13863. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  13864. std::string buf_all;
  13865. char buf[2048];
  13866. ssize_t n;
  13867. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  13868. buf_all.append(buf, static_cast<size_t>(n));
  13869. size_t pos;
  13870. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  13871. auto request_block = buf_all.substr(0, pos + 4); // include separator
  13872. auto e = request_block.find("\r\n");
  13873. if (e != std::string::npos) {
  13874. auto request_line = request_block.substr(0, e);
  13875. std::string msg =
  13876. "CRLF injection detected in request line: '" + request_line + "'";
  13877. EXPECT_FALSE(true) << msg;
  13878. }
  13879. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  13880. ::send(cli,
  13881. #ifdef _WIN32
  13882. static_cast<const char *>(resp.c_str()),
  13883. static_cast<int>(resp.size()),
  13884. #else
  13885. resp.c_str(), resp.size(),
  13886. #endif
  13887. 0);
  13888. buf_all.erase(0, pos + 4);
  13889. }
  13890. }
  13891. detail::close_socket(cli);
  13892. detail::close_socket(srv);
  13893. });
  13894. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13895. auto cli = Client("127.0.0.1", PORT + 1);
  13896. auto headers = Headers{
  13897. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  13898. {"Connection", "keep-alive"}};
  13899. auto res = cli.Get("/hi", headers);
  13900. EXPECT_FALSE(res);
  13901. EXPECT_EQ(Error::InvalidHeaders, res.error());
  13902. server_thread.join();
  13903. }
  13904. TEST(PathParamsTest, StaticMatch) {
  13905. const auto pattern = "/users/all";
  13906. detail::PathParamsMatcher matcher(pattern);
  13907. Request request;
  13908. request.path = "/users/all";
  13909. ASSERT_TRUE(matcher.match(request));
  13910. std::unordered_map<std::string, std::string> expected_params = {};
  13911. EXPECT_EQ(request.path_params, expected_params);
  13912. }
  13913. TEST(PathParamsTest, StaticMismatch) {
  13914. const auto pattern = "/users/all";
  13915. detail::PathParamsMatcher matcher(pattern);
  13916. Request request;
  13917. request.path = "/users/1";
  13918. ASSERT_FALSE(matcher.match(request));
  13919. }
  13920. TEST(PathParamsTest, SingleParamInTheMiddle) {
  13921. const auto pattern = "/users/:id/subscriptions";
  13922. detail::PathParamsMatcher matcher(pattern);
  13923. Request request;
  13924. request.path = "/users/42/subscriptions";
  13925. ASSERT_TRUE(matcher.match(request));
  13926. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  13927. EXPECT_EQ(request.path_params, expected_params);
  13928. }
  13929. TEST(PathParamsTest, SingleParamInTheEnd) {
  13930. const auto pattern = "/users/:id";
  13931. detail::PathParamsMatcher matcher(pattern);
  13932. Request request;
  13933. request.path = "/users/24";
  13934. ASSERT_TRUE(matcher.match(request));
  13935. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  13936. EXPECT_EQ(request.path_params, expected_params);
  13937. }
  13938. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  13939. const auto pattern = "/users/:id/";
  13940. detail::PathParamsMatcher matcher(pattern);
  13941. Request request;
  13942. request.path = "/users/42/";
  13943. ASSERT_TRUE(matcher.match(request));
  13944. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  13945. EXPECT_EQ(request.path_params, expected_params);
  13946. }
  13947. TEST(PathParamsTest, EmptyParam) {
  13948. const auto pattern = "/users/:id/";
  13949. detail::PathParamsMatcher matcher(pattern);
  13950. Request request;
  13951. request.path = "/users//";
  13952. ASSERT_TRUE(matcher.match(request));
  13953. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  13954. EXPECT_EQ(request.path_params, expected_params);
  13955. }
  13956. TEST(PathParamsTest, FragmentMismatch) {
  13957. const auto pattern = "/users/:id/";
  13958. detail::PathParamsMatcher matcher(pattern);
  13959. Request request;
  13960. request.path = "/admins/24/";
  13961. ASSERT_FALSE(matcher.match(request));
  13962. }
  13963. TEST(PathParamsTest, ExtraFragments) {
  13964. const auto pattern = "/users/:id";
  13965. detail::PathParamsMatcher matcher(pattern);
  13966. Request request;
  13967. request.path = "/users/42/subscriptions";
  13968. ASSERT_FALSE(matcher.match(request));
  13969. }
  13970. TEST(PathParamsTest, MissingTrailingParam) {
  13971. const auto pattern = "/users/:id";
  13972. detail::PathParamsMatcher matcher(pattern);
  13973. Request request;
  13974. request.path = "/users";
  13975. ASSERT_FALSE(matcher.match(request));
  13976. }
  13977. TEST(PathParamsTest, MissingParamInTheMiddle) {
  13978. const auto pattern = "/users/:id/subscriptions";
  13979. detail::PathParamsMatcher matcher(pattern);
  13980. Request request;
  13981. request.path = "/users/subscriptions";
  13982. ASSERT_FALSE(matcher.match(request));
  13983. }
  13984. TEST(PathParamsTest, MultipleParams) {
  13985. const auto pattern = "/users/:userid/subscriptions/:subid";
  13986. detail::PathParamsMatcher matcher(pattern);
  13987. Request request;
  13988. request.path = "/users/42/subscriptions/2";
  13989. ASSERT_TRUE(matcher.match(request));
  13990. std::unordered_map<std::string, std::string> expected_params = {
  13991. {"userid", "42"}, {"subid", "2"}};
  13992. EXPECT_EQ(request.path_params, expected_params);
  13993. }
  13994. TEST(PathParamsTest, SequenceOfParams) {
  13995. const auto pattern = "/values/:x/:y/:z";
  13996. detail::PathParamsMatcher matcher(pattern);
  13997. Request request;
  13998. request.path = "/values/1/2/3";
  13999. ASSERT_TRUE(matcher.match(request));
  14000. std::unordered_map<std::string, std::string> expected_params = {
  14001. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  14002. EXPECT_EQ(request.path_params, expected_params);
  14003. }
  14004. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  14005. const auto pattern = "/prefix:suffix";
  14006. detail::PathParamsMatcher matcher(pattern);
  14007. Request request;
  14008. request.path = "/prefix:suffix";
  14009. ASSERT_TRUE(matcher.match(request));
  14010. const std::unordered_map<std::string, std::string> expected_params = {};
  14011. EXPECT_EQ(request.path_params, expected_params);
  14012. }
  14013. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  14014. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  14015. // calling thread's stack on a long enough path for a quantified pattern;
  14016. // RegexMatcher must refuse to run regex matching on paths beyond
  14017. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  14018. detail::RegexMatcher matcher("/files/(.*)");
  14019. Request within_limit;
  14020. within_limit.path = "/files/" + std::string(10, 'A');
  14021. EXPECT_TRUE(matcher.match(within_limit));
  14022. Request over_limit;
  14023. over_limit.path =
  14024. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  14025. EXPECT_FALSE(matcher.match(over_limit));
  14026. }
  14027. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  14028. Server svr;
  14029. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  14030. res.set_content("ok", "text/plain");
  14031. });
  14032. auto port = svr.bind_to_any_port(HOST);
  14033. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  14034. auto se = detail::scope_exit([&] {
  14035. svr.stop();
  14036. thread.join();
  14037. ASSERT_FALSE(svr.is_running());
  14038. });
  14039. svr.wait_until_ready();
  14040. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  14041. // request URI limit; this used to be able to crash the process.
  14042. std::string path =
  14043. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  14044. std::string req = "GET " + path +
  14045. " HTTP/1.1\r\n"
  14046. "Host: " +
  14047. std::string(HOST) + ":" + std::to_string(port) +
  14048. "\r\n"
  14049. "Connection: close\r\n"
  14050. "\r\n";
  14051. std::string response;
  14052. ASSERT_TRUE(send_request(5, req, &response, port));
  14053. EXPECT_NE(std::string::npos, response.find("404"));
  14054. }
  14055. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  14056. Server svr;
  14057. auto handler = [](const Request & /*req*/, Response &res) {
  14058. res.set_content("hit", "text/plain");
  14059. };
  14060. // No regex metacharacter, so this one is compared literally
  14061. svr.Get("/literal/route", handler);
  14062. // '.' is a regex metacharacter, so this one must keep regex semantics
  14063. svr.Get("/a.c", handler);
  14064. auto port = svr.bind_to_any_port(HOST);
  14065. std::thread t([&]() { svr.listen_after_bind(); });
  14066. auto se = detail::scope_exit([&] {
  14067. svr.stop();
  14068. t.join();
  14069. ASSERT_FALSE(svr.is_running());
  14070. });
  14071. svr.wait_until_ready();
  14072. Client cli(HOST, port);
  14073. struct {
  14074. const char *path;
  14075. int status;
  14076. } cases[] = {
  14077. {"/literal/route", StatusCode::OK_200},
  14078. {"/literal/routes", StatusCode::NotFound_404},
  14079. {"/literal/rout", StatusCode::NotFound_404},
  14080. {"/abc", StatusCode::OK_200},
  14081. {"/a.c", StatusCode::OK_200},
  14082. };
  14083. for (const auto &x : cases) {
  14084. auto res = cli.Get(x.path);
  14085. ASSERT_TRUE(res) << x.path;
  14086. EXPECT_EQ(x.status, res->status) << x.path;
  14087. }
  14088. }
  14089. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  14090. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  14091. // from exhausting the stack, so it must only constrain routes that actually
  14092. // run a regular expression. A literal route is matched by comparison and
  14093. // stays usable at any length.
  14094. Server svr;
  14095. const std::string pattern =
  14096. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  14097. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  14098. res.set_content("hit", "text/plain");
  14099. });
  14100. auto port = svr.bind_to_any_port(HOST);
  14101. std::thread t([&]() { svr.listen_after_bind(); });
  14102. auto se = detail::scope_exit([&] {
  14103. svr.stop();
  14104. t.join();
  14105. ASSERT_FALSE(svr.is_running());
  14106. });
  14107. svr.wait_until_ready();
  14108. Client cli(HOST, port);
  14109. auto res = cli.Get(pattern);
  14110. ASSERT_TRUE(res);
  14111. EXPECT_EQ(StatusCode::OK_200, res->status);
  14112. }
  14113. TEST(ParseUrlTest, VariousPatterns) {
  14114. {
  14115. detail::UrlComponents uc;
  14116. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  14117. EXPECT_EQ("http", uc.scheme);
  14118. EXPECT_EQ("example.com", uc.host);
  14119. EXPECT_EQ("8080", uc.port);
  14120. EXPECT_EQ("/path", uc.path);
  14121. EXPECT_EQ("?q=1", uc.query);
  14122. }
  14123. {
  14124. detail::UrlComponents uc;
  14125. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  14126. EXPECT_EQ("https", uc.scheme);
  14127. EXPECT_EQ("example.com", uc.host);
  14128. EXPECT_TRUE(uc.port.empty());
  14129. EXPECT_EQ("/path", uc.path);
  14130. }
  14131. {
  14132. detail::UrlComponents uc;
  14133. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  14134. EXPECT_EQ("::1", uc.host);
  14135. EXPECT_EQ("8080", uc.port);
  14136. EXPECT_EQ("/path", uc.path);
  14137. }
  14138. {
  14139. detail::UrlComponents uc;
  14140. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  14141. }
  14142. {
  14143. // Bytes after the IPv6 literal must be a delimiter, not folded into
  14144. // the path while the connection still targets the bracketed host.
  14145. detail::UrlComponents uc;
  14146. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  14147. }
  14148. {
  14149. detail::UrlComponents uc;
  14150. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  14151. }
  14152. {
  14153. detail::UrlComponents uc;
  14154. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  14155. EXPECT_EQ("::1", uc.host);
  14156. EXPECT_TRUE(uc.port.empty());
  14157. EXPECT_EQ("/path", uc.path);
  14158. }
  14159. {
  14160. detail::UrlComponents uc;
  14161. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  14162. EXPECT_TRUE(uc.scheme.empty());
  14163. EXPECT_EQ("example.com", uc.host);
  14164. EXPECT_EQ("/path", uc.path);
  14165. EXPECT_EQ("?q=1", uc.query);
  14166. }
  14167. {
  14168. detail::UrlComponents uc;
  14169. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  14170. EXPECT_TRUE(uc.host.empty());
  14171. EXPECT_EQ("/path", uc.path);
  14172. EXPECT_EQ("?q=1", uc.query);
  14173. }
  14174. {
  14175. detail::UrlComponents uc;
  14176. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  14177. EXPECT_EQ("example.com", uc.host);
  14178. EXPECT_EQ("8080", uc.port);
  14179. }
  14180. {
  14181. // Unix socket path — must not be parsed as host
  14182. detail::UrlComponents uc;
  14183. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  14184. EXPECT_TRUE(uc.host.empty());
  14185. }
  14186. {
  14187. detail::UrlComponents uc;
  14188. ASSERT_TRUE(detail::parse_url("", uc));
  14189. EXPECT_TRUE(uc.host.empty());
  14190. EXPECT_TRUE(uc.path.empty());
  14191. }
  14192. {
  14193. detail::UrlComponents uc;
  14194. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  14195. }
  14196. {
  14197. detail::UrlComponents uc;
  14198. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  14199. }
  14200. {
  14201. // Accepted by parse_url; callers restrict to http/https
  14202. detail::UrlComponents uc;
  14203. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  14204. EXPECT_EQ("ftp", uc.scheme);
  14205. }
  14206. {
  14207. detail::UrlComponents uc;
  14208. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  14209. }
  14210. {
  14211. detail::UrlComponents uc;
  14212. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  14213. }
  14214. }
  14215. TEST(ParseUrlTest, FragmentHandling) {
  14216. {
  14217. detail::UrlComponents uc;
  14218. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  14219. EXPECT_EQ("/path", uc.path);
  14220. EXPECT_TRUE(uc.query.empty());
  14221. }
  14222. {
  14223. detail::UrlComponents uc;
  14224. ASSERT_TRUE(detail::parse_url("#frag", uc));
  14225. EXPECT_TRUE(uc.path.empty());
  14226. EXPECT_TRUE(uc.query.empty());
  14227. }
  14228. }
  14229. TEST(ParseUrlTest, UserinfoHandling) {
  14230. // Userinfo with @ but no colon — host includes @
  14231. detail::UrlComponents uc;
  14232. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  14233. EXPECT_EQ("user@host.com", uc.host);
  14234. EXPECT_EQ("/path", uc.path);
  14235. }
  14236. TEST(ParseUrlTest, IPv6EdgeCases) {
  14237. {
  14238. detail::UrlComponents uc;
  14239. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  14240. EXPECT_TRUE(uc.scheme.empty());
  14241. EXPECT_EQ("::1", uc.host);
  14242. EXPECT_EQ("8080", uc.port);
  14243. }
  14244. {
  14245. // Zone ID '%25' is not in [a-fA-F0-9:]
  14246. detail::UrlComponents uc;
  14247. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  14248. }
  14249. }
  14250. TEST(ParseUrlTest, SchemeEdgeCases) {
  14251. {
  14252. detail::UrlComponents uc;
  14253. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  14254. }
  14255. {
  14256. detail::UrlComponents uc;
  14257. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  14258. }
  14259. {
  14260. detail::UrlComponents uc;
  14261. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  14262. }
  14263. }
  14264. TEST(ParseUrlTest, PortEdgeCases) {
  14265. {
  14266. detail::UrlComponents uc;
  14267. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  14268. EXPECT_TRUE(uc.port.empty());
  14269. EXPECT_EQ("/path", uc.path);
  14270. }
  14271. {
  14272. // parse_url accepts any port string; validation is done by parse_port
  14273. detail::UrlComponents uc;
  14274. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  14275. EXPECT_EQ("abc", uc.port);
  14276. }
  14277. }
  14278. TEST(ParseUrlTest, WebSocketPatterns) {
  14279. {
  14280. detail::UrlComponents uc;
  14281. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  14282. EXPECT_EQ("ws", uc.scheme);
  14283. EXPECT_EQ("echo.example.com", uc.host);
  14284. EXPECT_EQ("8080", uc.port);
  14285. EXPECT_EQ("/ws", uc.path);
  14286. }
  14287. {
  14288. detail::UrlComponents uc;
  14289. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  14290. EXPECT_EQ("wss", uc.scheme);
  14291. EXPECT_EQ("echo.example.com", uc.host);
  14292. EXPECT_TRUE(uc.port.empty());
  14293. EXPECT_EQ("/ws", uc.path);
  14294. }
  14295. }
  14296. TEST(ParseUrlTest, QueryOnly) {
  14297. detail::UrlComponents uc;
  14298. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  14299. EXPECT_TRUE(uc.host.empty());
  14300. EXPECT_TRUE(uc.path.empty());
  14301. EXPECT_EQ("?q=1&r=2", uc.query);
  14302. }
  14303. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  14304. detail::UrlComponents uc;
  14305. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  14306. EXPECT_TRUE(uc.scheme.empty());
  14307. EXPECT_EQ("example.com", uc.host);
  14308. EXPECT_EQ("443", uc.port);
  14309. EXPECT_EQ("/path", uc.path);
  14310. }
  14311. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  14312. // If ipv6 regex working, regex match codepath is taken.
  14313. // else port will default to 80 in Client impl
  14314. int clientImplMagicPort = 80;
  14315. int port = 4321;
  14316. // above ports must be different to avoid false negative
  14317. EXPECT_NE(clientImplMagicPort, port);
  14318. std::string ipV6TestURL = "http://[ff06::c3]";
  14319. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  14320. CLIENT_PRIVATE_KEY_FILE);
  14321. EXPECT_EQ(cli.port(), port);
  14322. }
  14323. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  14324. auto file_path = "./www/dir/index.html";
  14325. auto dir_path = "./www/dir";
  14326. detail::FileStat stat_file(file_path);
  14327. EXPECT_TRUE(stat_file.is_file());
  14328. EXPECT_FALSE(stat_file.is_dir());
  14329. detail::FileStat stat_dir(dir_path);
  14330. EXPECT_FALSE(stat_dir.is_file());
  14331. EXPECT_TRUE(stat_dir.is_dir());
  14332. }
  14333. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  14334. // IPv4 with default HTTP port (80)
  14335. EXPECT_EQ("example.com",
  14336. detail::make_host_and_port_string("example.com", 80, false));
  14337. // IPv4 with default HTTPS port (443)
  14338. EXPECT_EQ("example.com",
  14339. detail::make_host_and_port_string("example.com", 443, true));
  14340. // IPv4 with non-default HTTP port
  14341. EXPECT_EQ("example.com:8080",
  14342. detail::make_host_and_port_string("example.com", 8080, false));
  14343. // IPv4 with non-default HTTPS port
  14344. EXPECT_EQ("example.com:8443",
  14345. detail::make_host_and_port_string("example.com", 8443, true));
  14346. // IPv6 with default HTTP port (80)
  14347. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  14348. // IPv6 with default HTTPS port (443)
  14349. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  14350. // IPv6 with non-default HTTP port
  14351. EXPECT_EQ("[::1]:8080",
  14352. detail::make_host_and_port_string("::1", 8080, false));
  14353. // IPv6 with non-default HTTPS port
  14354. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  14355. // IPv6 full address with default port
  14356. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  14357. detail::make_host_and_port_string(
  14358. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  14359. // IPv6 full address with non-default port
  14360. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  14361. detail::make_host_and_port_string(
  14362. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  14363. // IPv6 localhost with non-default port
  14364. EXPECT_EQ("[::1]:3000",
  14365. detail::make_host_and_port_string("::1", 3000, false));
  14366. // IPv6 with zone ID (link-local address) with default port
  14367. EXPECT_EQ("[fe80::1%eth0]",
  14368. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  14369. // IPv6 with zone ID (link-local address) with non-default port
  14370. EXPECT_EQ("[fe80::1%eth0]:8080",
  14371. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  14372. // Edge case: Port 443 with is_ssl=false (should add port)
  14373. EXPECT_EQ("example.com:443",
  14374. detail::make_host_and_port_string("example.com", 443, false));
  14375. // Edge case: Port 80 with is_ssl=true (should add port)
  14376. EXPECT_EQ("example.com:80",
  14377. detail::make_host_and_port_string("example.com", 80, true));
  14378. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  14379. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  14380. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  14381. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  14382. // Security fix: Already bracketed IPv6 should not get double brackets
  14383. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  14384. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  14385. EXPECT_EQ("[::1]:8080",
  14386. detail::make_host_and_port_string("[::1]", 8080, false));
  14387. EXPECT_EQ("[2001:db8::1]:8080",
  14388. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  14389. EXPECT_EQ("[fe80::1%eth0]",
  14390. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  14391. EXPECT_EQ("[fe80::1%eth0]:8080",
  14392. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  14393. // Edge case: Empty host (should return as-is)
  14394. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  14395. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  14396. // This is a known limitation but shouldn't crash
  14397. EXPECT_EQ("[host:name]",
  14398. detail::make_host_and_port_string("host:name", 80, false));
  14399. // Port number edge cases (no validation, but should not crash)
  14400. EXPECT_EQ("example.com:0",
  14401. detail::make_host_and_port_string("example.com", 0, false));
  14402. EXPECT_EQ("example.com:-1",
  14403. detail::make_host_and_port_string("example.com", -1, false));
  14404. EXPECT_EQ("example.com:65535",
  14405. detail::make_host_and_port_string("example.com", 65535, false));
  14406. EXPECT_EQ("example.com:65536",
  14407. detail::make_host_and_port_string("example.com", 65536, false));
  14408. }
  14409. #ifdef CPPHTTPLIB_SSL_ENABLED
  14410. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  14411. httplib::SSLClient cli("roblox.com", 443);
  14412. cli.set_follow_location(true);
  14413. auto res = cli.Get("/");
  14414. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14415. EXPECT_EQ(StatusCode::OK_200, res->status);
  14416. }
  14417. #endif
  14418. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  14419. Server svr;
  14420. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  14421. EXPECT_EQ(res.status, 400);
  14422. });
  14423. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14424. auto se = detail::scope_exit([&] {
  14425. svr.stop();
  14426. thread.join();
  14427. ASSERT_FALSE(svr.is_running());
  14428. });
  14429. svr.wait_until_ready();
  14430. Client cli(HOST, PORT);
  14431. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  14432. }
  14433. TEST(InvalidHeaderCharsTest, is_field_name) {
  14434. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  14435. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  14436. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  14437. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  14438. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  14439. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  14440. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  14441. EXPECT_FALSE(detail::fields::is_field_name(""));
  14442. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  14443. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  14444. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  14445. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  14446. }
  14447. TEST(InvalidHeaderCharsTest, is_field_value) {
  14448. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  14449. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  14450. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  14451. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  14452. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  14453. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  14454. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  14455. EXPECT_TRUE(detail::fields::is_field_value(""));
  14456. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  14457. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  14458. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  14459. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  14460. EXPECT_TRUE(detail::fields::is_field_value("0"));
  14461. }
  14462. TEST(InvalidHeaderCharsTest, OnServer) {
  14463. Server svr;
  14464. svr.Get("/test_name", [&](const Request &req, Response &res) {
  14465. std::string header = "Not Set";
  14466. if (req.has_param("header")) { header = req.get_param_value("header"); }
  14467. res.set_header(header, "value");
  14468. res.set_content("Page Content Page Content", "text/plain");
  14469. });
  14470. svr.Get("/test_value", [&](const Request &req, Response &res) {
  14471. std::string header = "Not Set";
  14472. if (req.has_param("header")) { header = req.get_param_value("header"); }
  14473. res.set_header("X-Test", header);
  14474. res.set_content("Page Content Page Content", "text/plain");
  14475. });
  14476. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14477. auto se = detail::scope_exit([&] {
  14478. svr.stop();
  14479. thread.join();
  14480. ASSERT_FALSE(svr.is_running());
  14481. });
  14482. svr.wait_until_ready();
  14483. Client cli(HOST, PORT);
  14484. {
  14485. auto res = cli.Get(
  14486. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  14487. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14488. EXPECT_EQ("Page Content Page Content", res->body);
  14489. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  14490. }
  14491. {
  14492. auto res = cli.Get(
  14493. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  14494. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14495. EXPECT_EQ("Page Content Page Content", res->body);
  14496. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  14497. }
  14498. }
  14499. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  14500. auto handled = false;
  14501. Server svr;
  14502. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  14503. thread t = thread([&] { svr.listen(HOST, PORT); });
  14504. auto se = detail::scope_exit([&] {
  14505. svr.stop();
  14506. t.join();
  14507. ASSERT_FALSE(svr.is_running());
  14508. ASSERT_FALSE(handled);
  14509. });
  14510. svr.wait_until_ready();
  14511. auto req = "POST /test HTTP/1.1\r\n"
  14512. "Content-Length: x\r\n"
  14513. "\r\n";
  14514. std::string response;
  14515. ASSERT_TRUE(send_request(1, req, &response));
  14516. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  14517. response.substr(0, response.find("\r\n")));
  14518. }
  14519. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  14520. // case-insensitive, and a server that receives a 100-continue expectation in
  14521. // an HTTP/1.0 request MUST ignore it.
  14522. static void probe_expect(int port, const std::string &req, bool *got_100) {
  14523. std::string response;
  14524. ASSERT_TRUE(send_request(1, req, &response, port));
  14525. *got_100 = response.find("100 Continue") != std::string::npos;
  14526. }
  14527. class ExpectTokenTest : public ::testing::Test {
  14528. protected:
  14529. void SetUp() override {
  14530. svr_.Post("/p", [](const Request &, Response &res) {
  14531. res.set_content("ok", "text/plain");
  14532. });
  14533. port_ = svr_.bind_to_any_port(HOST);
  14534. thread_ = thread([&]() { svr_.listen_after_bind(); });
  14535. svr_.wait_until_ready();
  14536. }
  14537. void TearDown() override {
  14538. svr_.stop();
  14539. if (thread_.joinable()) { thread_.join(); }
  14540. }
  14541. std::string request(const char *version, const char *expect_value) const {
  14542. return std::string("POST /p ") + version +
  14543. "\r\n"
  14544. "Host: localhost\r\n"
  14545. "Content-Length: 2\r\n"
  14546. "Connection: close\r\n"
  14547. "Expect: " +
  14548. expect_value +
  14549. "\r\n"
  14550. "\r\n"
  14551. "hi";
  14552. }
  14553. Server svr_;
  14554. int port_ = 0;
  14555. thread thread_;
  14556. };
  14557. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  14558. bool got_100 = false;
  14559. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  14560. EXPECT_TRUE(got_100);
  14561. }
  14562. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  14563. bool got_100 = true;
  14564. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  14565. EXPECT_FALSE(got_100);
  14566. }
  14567. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  14568. bool got_100 = false;
  14569. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  14570. EXPECT_TRUE(got_100);
  14571. }
  14572. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  14573. bool got_100 = false;
  14574. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  14575. EXPECT_TRUE(got_100);
  14576. }
  14577. #ifndef _WIN32
  14578. TEST(Expect100ContinueTest, ServerClosesConnection) {
  14579. static constexpr char reject[] = "Unauthorized";
  14580. static constexpr char accept[] = "Upload accepted";
  14581. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  14582. Server svr;
  14583. svr.set_expect_100_continue_handler(
  14584. [](const Request & /*req*/, Response &res) {
  14585. res.status = StatusCode::Unauthorized_401;
  14586. res.set_content(reject, "text/plain");
  14587. return res.status;
  14588. });
  14589. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  14590. res.set_content(accept, "text/plain");
  14591. });
  14592. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14593. auto se = detail::scope_exit([&] {
  14594. svr.stop();
  14595. thread.join();
  14596. ASSERT_FALSE(svr.is_running());
  14597. });
  14598. svr.wait_until_ready();
  14599. {
  14600. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  14601. curl_easy_init(), &curl_easy_cleanup};
  14602. ASSERT_NE(curl, nullptr);
  14603. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  14604. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  14605. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  14606. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  14607. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  14608. &curl_slist_free_all};
  14609. ASSERT_NE(list, nullptr);
  14610. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  14611. struct read_data {
  14612. size_t read_size;
  14613. size_t total_size;
  14614. } data = {0, total_size};
  14615. using read_callback_t =
  14616. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  14617. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  14618. void *userdata) -> size_t {
  14619. read_data *d = (read_data *)userdata;
  14620. if (!userdata || d->read_size >= d->total_size) { return 0; }
  14621. std::fill_n(ptr, size * nmemb, 'A');
  14622. d->read_size += size * nmemb;
  14623. return size * nmemb;
  14624. };
  14625. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  14626. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  14627. std::vector<char> buffer;
  14628. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  14629. using write_callback_t =
  14630. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  14631. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  14632. void *userdata) -> size_t {
  14633. std::vector<char> *buf = (std::vector<char> *)userdata;
  14634. buf->reserve(buf->size() + size * nmemb + 1);
  14635. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  14636. return size * nmemb;
  14637. };
  14638. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  14639. {
  14640. const auto res = curl_easy_perform(curl.get());
  14641. ASSERT_EQ(res, CURLE_OK);
  14642. }
  14643. {
  14644. auto response_code = long{};
  14645. const auto res =
  14646. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  14647. ASSERT_EQ(res, CURLE_OK);
  14648. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  14649. }
  14650. {
  14651. auto dl = curl_off_t{};
  14652. const auto res =
  14653. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  14654. ASSERT_EQ(res, CURLE_OK);
  14655. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  14656. }
  14657. {
  14658. buffer.push_back('\0');
  14659. ASSERT_STRCASEEQ(buffer.data(), reject);
  14660. }
  14661. }
  14662. }
  14663. #endif
  14664. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  14665. // Regression test for #2458.
  14666. //
  14667. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  14668. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  14669. // ticket can make the client socket spuriously readable during the
  14670. // 100-continue wait. If the readiness is mistaken for an incoming response,
  14671. // the client withholds the body and then blocks reading a response that never
  14672. // comes, failing with `Failed to read connection`.
  14673. //
  14674. // A correct client (like curl) sends the body once no `100 Continue` arrives
  14675. // within the timeout. This raw OpenSSL server deliberately never sends
  14676. // `100 Continue`; the client must still deliver the body and receive 200.
  14677. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  14678. signal(SIGPIPE, SIG_IGN);
  14679. const auto port = PORT + 4;
  14680. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  14681. ASSERT_NE(srv, INVALID_SOCKET);
  14682. int opt = 1;
  14683. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  14684. sockaddr_in addr{};
  14685. addr.sin_family = AF_INET;
  14686. addr.sin_port = htons(static_cast<uint16_t>(port));
  14687. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  14688. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  14689. ASSERT_EQ(0, ::listen(srv, 1));
  14690. std::atomic<size_t> server_body_bytes{0};
  14691. auto server_thread = std::thread([&] {
  14692. sockaddr_in cli_addr{};
  14693. socklen_t cli_len = sizeof(cli_addr);
  14694. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  14695. if (cli == INVALID_SOCKET) { return; }
  14696. // Bound the lifetime of the server side so a buggy client (which never
  14697. // sends the body) cannot make this thread block forever on join.
  14698. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  14699. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  14700. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  14701. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  14702. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  14703. SSL *ssl = SSL_new(ctx);
  14704. SSL_set_fd(ssl, static_cast<int>(cli));
  14705. if (SSL_accept(ssl) > 0) {
  14706. // Read the request headers. Reading here also flushes the TLS 1.3
  14707. // session tickets to the client. Deliberately do NOT send
  14708. // `100 Continue`.
  14709. std::string buf;
  14710. char tmp[1024];
  14711. while (buf.find("\r\n\r\n") == std::string::npos) {
  14712. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  14713. if (n <= 0) { break; }
  14714. buf.append(tmp, static_cast<size_t>(n));
  14715. }
  14716. // A correct client sends the body now; count what arrives.
  14717. auto pos = buf.find("\r\n\r\n");
  14718. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  14719. while (body < 4096) {
  14720. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  14721. if (n <= 0) { break; }
  14722. body += static_cast<size_t>(n);
  14723. }
  14724. server_body_bytes = body;
  14725. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  14726. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  14727. SSL_shutdown(ssl);
  14728. }
  14729. SSL_free(ssl);
  14730. detail::close_socket(cli);
  14731. SSL_CTX_free(ctx);
  14732. });
  14733. auto se = detail::scope_exit([&] {
  14734. server_thread.join();
  14735. detail::close_socket(srv);
  14736. });
  14737. SSLClient cli("127.0.0.1", port);
  14738. cli.enable_server_certificate_verification(false);
  14739. cli.set_connection_timeout(5, 0);
  14740. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  14741. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  14742. std::string body(4096, 'A');
  14743. auto res = cli.Put("/api/test", body, "application/json");
  14744. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  14745. EXPECT_EQ(StatusCode::OK_200, res->status);
  14746. EXPECT_EQ(body.size(), server_body_bytes.load());
  14747. }
  14748. #endif
  14749. template <typename S, typename C>
  14750. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  14751. svr.Get("/stream", [&](const Request &, Response &res) {
  14752. auto data = new std::string("01234567890123456789");
  14753. res.set_content_provider(
  14754. data->size(), "text/plain",
  14755. [&, data](size_t offset, size_t length, DataSink &sink) {
  14756. const size_t DATA_CHUNK_SIZE = 4;
  14757. const auto &d = *data;
  14758. std::this_thread::sleep_for(std::chrono::seconds(1));
  14759. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  14760. return true;
  14761. },
  14762. [data](bool success) {
  14763. EXPECT_FALSE(success);
  14764. delete data;
  14765. });
  14766. });
  14767. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  14768. auto i = new size_t(0);
  14769. res.set_content_provider(
  14770. "text/plain",
  14771. [i](size_t, DataSink &sink) {
  14772. if (*i < 5) {
  14773. std::this_thread::sleep_for(std::chrono::seconds(1));
  14774. sink.write("abcd", 4);
  14775. (*i)++;
  14776. } else {
  14777. sink.done();
  14778. }
  14779. return true;
  14780. },
  14781. [i](bool success) {
  14782. EXPECT_FALSE(success);
  14783. delete i;
  14784. });
  14785. });
  14786. svr.Get("/chunked", [&](const Request &, Response &res) {
  14787. auto i = new size_t(0);
  14788. res.set_chunked_content_provider(
  14789. "text/plain",
  14790. [i](size_t, DataSink &sink) {
  14791. if (*i < 5) {
  14792. std::this_thread::sleep_for(std::chrono::seconds(1));
  14793. sink.os << "abcd";
  14794. (*i)++;
  14795. } else {
  14796. sink.done();
  14797. }
  14798. return true;
  14799. },
  14800. [i](bool success) {
  14801. EXPECT_FALSE(success);
  14802. delete i;
  14803. });
  14804. });
  14805. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  14806. auto se = detail::scope_exit([&] {
  14807. svr.stop();
  14808. listen_thread.join();
  14809. ASSERT_FALSE(svr.is_running());
  14810. });
  14811. svr.wait_until_ready();
  14812. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  14813. {
  14814. auto start = std::chrono::steady_clock::now();
  14815. auto res = cli.Get("/stream");
  14816. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  14817. std::chrono::steady_clock::now() - start)
  14818. .count();
  14819. ASSERT_FALSE(res);
  14820. EXPECT_EQ(Error::Read, res.error());
  14821. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  14822. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  14823. }
  14824. {
  14825. auto start = std::chrono::steady_clock::now();
  14826. auto res = cli.Get("/stream_without_length");
  14827. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  14828. std::chrono::steady_clock::now() - start)
  14829. .count();
  14830. ASSERT_FALSE(res);
  14831. EXPECT_EQ(Error::Read, res.error());
  14832. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  14833. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  14834. }
  14835. {
  14836. auto start = std::chrono::steady_clock::now();
  14837. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  14838. EXPECT_EQ("abcd", string(data, data_length));
  14839. return true;
  14840. });
  14841. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  14842. std::chrono::steady_clock::now() - start)
  14843. .count();
  14844. ASSERT_FALSE(res);
  14845. EXPECT_EQ(Error::Read, res.error());
  14846. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  14847. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  14848. }
  14849. }
  14850. TEST(MaxTimeoutTest, ContentStream) {
  14851. time_t timeout = 2000;
  14852. time_t threshold = 200;
  14853. Server svr;
  14854. Client cli("localhost", PORT);
  14855. max_timeout_test(svr, cli, timeout, threshold);
  14856. }
  14857. #ifdef CPPHTTPLIB_SSL_ENABLED
  14858. TEST(MaxTimeoutTest, ContentStreamSSL) {
  14859. time_t timeout = 2000;
  14860. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  14861. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14862. SSLClient cli("localhost", PORT);
  14863. cli.enable_server_certificate_verification(false);
  14864. max_timeout_test(svr, cli, timeout, threshold);
  14865. }
  14866. #endif
  14867. class EventDispatcher {
  14868. public:
  14869. EventDispatcher() {}
  14870. bool wait_event(DataSink *sink) {
  14871. unique_lock<mutex> lk(m_);
  14872. int id = id_;
  14873. // Wait with timeout to prevent hanging if client disconnects
  14874. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  14875. [&] { return cid_ == id; })) {
  14876. return false; // Timeout occurred
  14877. }
  14878. sink->write(message_.data(), message_.size());
  14879. return true;
  14880. }
  14881. void send_event(const string &message) {
  14882. lock_guard<mutex> lk(m_);
  14883. cid_ = id_++;
  14884. message_ = message;
  14885. cv_.notify_all();
  14886. }
  14887. private:
  14888. mutex m_;
  14889. condition_variable cv_;
  14890. atomic_int id_{0};
  14891. atomic_int cid_{-1};
  14892. string message_;
  14893. };
  14894. TEST(ClientInThreadTest, Issue2068) {
  14895. EventDispatcher ed;
  14896. Server svr;
  14897. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  14898. res.set_chunked_content_provider("text/event-stream",
  14899. [&](size_t /*offset*/, DataSink &sink) {
  14900. return ed.wait_event(&sink);
  14901. });
  14902. });
  14903. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  14904. svr.wait_until_ready();
  14905. thread event_thread([&] {
  14906. int id = 0;
  14907. while (svr.is_running()) {
  14908. this_thread::sleep_for(chrono::milliseconds(500));
  14909. std::stringstream ss;
  14910. ss << "data: " << id << "\n\n";
  14911. ed.send_event(ss.str());
  14912. id++;
  14913. }
  14914. });
  14915. auto se = detail::scope_exit([&] {
  14916. svr.stop();
  14917. listen_thread.join();
  14918. event_thread.join();
  14919. ASSERT_FALSE(svr.is_running());
  14920. });
  14921. {
  14922. auto client = detail::make_unique<Client>(HOST, PORT);
  14923. client->set_read_timeout(std::chrono::minutes(10));
  14924. std::atomic<bool> stop{false};
  14925. std::thread t([&] {
  14926. client->Get("/event1",
  14927. [&](const char *, size_t) -> bool { return !stop; });
  14928. });
  14929. std::this_thread::sleep_for(std::chrono::seconds(2));
  14930. stop = true;
  14931. client->stop();
  14932. t.join();
  14933. // Reset client after thread has finished
  14934. client.reset();
  14935. }
  14936. }
  14937. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  14938. auto handled = false;
  14939. Server svr;
  14940. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  14941. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14942. auto se = detail::scope_exit([&] {
  14943. svr.stop();
  14944. t.join();
  14945. ASSERT_FALSE(svr.is_running());
  14946. ASSERT_FALSE(handled);
  14947. });
  14948. svr.wait_until_ready();
  14949. // Two Content-Length headers with different values — must be rejected
  14950. auto req = "POST /test HTTP/1.1\r\n"
  14951. "Content-Length: 5\r\n"
  14952. "Content-Length: 10\r\n"
  14953. "\r\n"
  14954. "hello";
  14955. std::string response;
  14956. ASSERT_TRUE(send_request(1, req, &response));
  14957. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  14958. response.substr(0, response.find("\r\n")));
  14959. }
  14960. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  14961. auto handled = false;
  14962. Server svr;
  14963. svr.Post("/test", [&](const Request &, Response &res) {
  14964. handled = true;
  14965. res.set_content("ok", "text/plain");
  14966. });
  14967. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14968. auto se = detail::scope_exit([&] {
  14969. svr.stop();
  14970. t.join();
  14971. ASSERT_FALSE(svr.is_running());
  14972. ASSERT_TRUE(handled);
  14973. });
  14974. svr.wait_until_ready();
  14975. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  14976. auto req = "POST /test HTTP/1.1\r\n"
  14977. "Content-Length: 5\r\n"
  14978. "Content-Length: 5\r\n"
  14979. "\r\n"
  14980. "hello";
  14981. std::string response;
  14982. ASSERT_TRUE(send_request(1, req, &response));
  14983. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  14984. }
  14985. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  14986. Server svr;
  14987. svr.Get("/", [](const Request &req, Response &res) {
  14988. EXPECT_EQ(2U, req.trailers.size());
  14989. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  14990. // Denied
  14991. EXPECT_FALSE(req.has_trailer("Content-Length"));
  14992. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  14993. // Accepted
  14994. EXPECT_TRUE(req.has_trailer("X-Hello"));
  14995. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  14996. EXPECT_TRUE(req.has_trailer("X-World"));
  14997. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  14998. res.set_content("ok", "text/plain");
  14999. });
  15000. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15001. auto se = detail::scope_exit([&] {
  15002. svr.stop();
  15003. t.join();
  15004. ASSERT_FALSE(svr.is_running());
  15005. });
  15006. svr.wait_until_ready();
  15007. const std::string req = "GET / HTTP/1.1\r\n"
  15008. "Transfer-Encoding: chunked\r\n"
  15009. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  15010. "\r\n"
  15011. "0\r\n"
  15012. "Content-Length: 10\r\n"
  15013. "Host: internal.local\r\n"
  15014. "Content-Type: malicious/content\r\n"
  15015. "Cookie: any\r\n"
  15016. "Set-Cookie: any\r\n"
  15017. "X-Forwarded-For: attacker.com\r\n"
  15018. "X-Real-Ip: 1.1.1.1\r\n"
  15019. "X-Hello: hello\r\n"
  15020. "X-World: world\r\n"
  15021. "\r\n";
  15022. std::string res;
  15023. ASSERT_TRUE(send_request(1, req, &res));
  15024. }
  15025. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  15026. // several field lines, and the combined value is what has to be parsed. A
  15027. // Trailer field split across lines therefore declares every name it lists;
  15028. // reading only the first line silently drops the trailers the later lines
  15029. // declare. The prohibited-trailer filter still applies to every line.
  15030. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  15031. Server svr;
  15032. size_t observed_trailer_count = 0;
  15033. std::string observed_hello;
  15034. std::string observed_world;
  15035. bool observed_content_length = true;
  15036. svr.Get("/", [&](const Request &req, Response &res) {
  15037. observed_trailer_count = req.trailers.size();
  15038. observed_hello = req.get_trailer_value("X-Hello");
  15039. observed_world = req.get_trailer_value("X-World");
  15040. observed_content_length = req.has_trailer("Content-Length");
  15041. res.set_content("ok", "text/plain");
  15042. });
  15043. auto port = svr.bind_to_any_port(HOST);
  15044. thread t = thread([&]() { svr.listen_after_bind(); });
  15045. auto se = detail::scope_exit([&] {
  15046. svr.stop();
  15047. t.join();
  15048. ASSERT_FALSE(svr.is_running());
  15049. });
  15050. svr.wait_until_ready();
  15051. const std::string req = "GET / HTTP/1.1\r\n"
  15052. "Transfer-Encoding: chunked\r\n"
  15053. "Trailer: X-Hello\r\n"
  15054. "Trailer: X-World, Content-Length\r\n"
  15055. "\r\n"
  15056. "0\r\n"
  15057. "X-Hello: hello\r\n"
  15058. "X-World: world\r\n"
  15059. "Content-Length: 10\r\n"
  15060. "\r\n";
  15061. std::string res;
  15062. ASSERT_TRUE(send_request(1, req, &res, port));
  15063. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  15064. // Accepted: both field lines contribute to the declared set
  15065. EXPECT_EQ(2U, observed_trailer_count);
  15066. EXPECT_EQ(observed_hello, "hello");
  15067. EXPECT_EQ(observed_world, "world");
  15068. // Denied: a prohibited name stays prohibited on a later field line
  15069. EXPECT_FALSE(observed_content_length);
  15070. }
  15071. // A direct client that is not listed in trusted_proxies must not be able to
  15072. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  15073. // the peer address on the actual TCP connection determines whether the
  15074. // header is honored.
  15075. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  15076. Server svr;
  15077. // Deliberately does NOT include the loopback address the test client
  15078. // actually connects from, so the direct connection is not a trusted proxy.
  15079. svr.set_trusted_proxies({"203.0.113.66"});
  15080. std::string observed_remote_addr;
  15081. svr.Get("/ip", [&](const Request &req, Response &res) {
  15082. observed_remote_addr = req.remote_addr;
  15083. res.set_content("ok", "text/plain");
  15084. });
  15085. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15086. auto se = detail::scope_exit([&] {
  15087. svr.stop();
  15088. t.join();
  15089. ASSERT_FALSE(svr.is_running());
  15090. });
  15091. svr.wait_until_ready();
  15092. Client cli(HOST, PORT);
  15093. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  15094. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15095. EXPECT_EQ(StatusCode::OK_200, res->status);
  15096. // The connecting peer is not a trusted proxy, so the spoofed header must be
  15097. // ignored entirely and the real connection-level address retained.
  15098. EXPECT_TRUE(observed_remote_addr == "::1" ||
  15099. observed_remote_addr == "127.0.0.1");
  15100. }
  15101. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  15102. Server svr;
  15103. std::string observed_remote_addr;
  15104. std::string observed_xff;
  15105. svr.Get("/ip", [&](const Request &req, Response &res) {
  15106. observed_remote_addr = req.remote_addr;
  15107. observed_xff = req.get_header_value("X-Forwarded-For");
  15108. res.set_content("ok", "text/plain");
  15109. });
  15110. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15111. auto se = detail::scope_exit([&] {
  15112. svr.stop();
  15113. t.join();
  15114. ASSERT_FALSE(svr.is_running());
  15115. });
  15116. svr.wait_until_ready();
  15117. Client cli(HOST, PORT);
  15118. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  15119. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15120. EXPECT_EQ(StatusCode::OK_200, res->status);
  15121. EXPECT_EQ(observed_xff, "203.0.113.66");
  15122. EXPECT_TRUE(observed_remote_addr == "::1" ||
  15123. observed_remote_addr == "127.0.0.1");
  15124. }
  15125. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  15126. Server svr;
  15127. svr.set_trusted_proxies({"203.0.113.66"});
  15128. std::string observed_remote_addr;
  15129. std::string observed_xff;
  15130. svr.Get("/ip", [&](const Request &req, Response &res) {
  15131. observed_remote_addr = req.remote_addr;
  15132. observed_xff = req.get_header_value("X-Forwarded-For");
  15133. res.set_content("ok", "text/plain");
  15134. });
  15135. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15136. auto se = detail::scope_exit([&] {
  15137. svr.stop();
  15138. t.join();
  15139. ASSERT_FALSE(svr.is_running());
  15140. });
  15141. svr.wait_until_ready();
  15142. Client cli(HOST, PORT);
  15143. auto res = cli.Get("/ip");
  15144. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15145. EXPECT_EQ(StatusCode::OK_200, res->status);
  15146. EXPECT_EQ(observed_xff, "");
  15147. EXPECT_TRUE(observed_remote_addr == "::1" ||
  15148. observed_remote_addr == "127.0.0.1");
  15149. }
  15150. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  15151. Server svr;
  15152. // Include the loopback address the test client actually connects from, so
  15153. // the direct connection itself is recognized as the trusted proxy hop.
  15154. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  15155. std::string observed_remote_addr;
  15156. std::string observed_xff;
  15157. svr.Get("/ip", [&](const Request &req, Response &res) {
  15158. observed_remote_addr = req.remote_addr;
  15159. observed_xff = req.get_header_value("X-Forwarded-For");
  15160. res.set_content("ok", "text/plain");
  15161. });
  15162. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15163. auto se = detail::scope_exit([&] {
  15164. svr.stop();
  15165. t.join();
  15166. ASSERT_FALSE(svr.is_running());
  15167. });
  15168. svr.wait_until_ready();
  15169. Client cli(HOST, PORT);
  15170. auto res = cli.Get(
  15171. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  15172. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15173. EXPECT_EQ(StatusCode::OK_200, res->status);
  15174. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  15175. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  15176. }
  15177. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  15178. Server svr;
  15179. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  15180. std::string observed_remote_addr;
  15181. std::string observed_xff;
  15182. svr.Get("/ip", [&](const Request &req, Response &res) {
  15183. observed_remote_addr = req.remote_addr;
  15184. observed_xff = req.get_header_value("X-Forwarded-For");
  15185. res.set_content("ok", "text/plain");
  15186. });
  15187. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15188. auto se = detail::scope_exit([&] {
  15189. svr.stop();
  15190. t.join();
  15191. ASSERT_FALSE(svr.is_running());
  15192. });
  15193. svr.wait_until_ready();
  15194. Client cli(HOST, PORT);
  15195. auto res = cli.Get(
  15196. "/ip",
  15197. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  15198. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15199. EXPECT_EQ(StatusCode::OK_200, res->status);
  15200. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  15201. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  15202. }
  15203. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  15204. Server svr;
  15205. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  15206. std::string observed_remote_addr;
  15207. std::string observed_xff;
  15208. svr.Get("/ip", [&](const Request &req, Response &res) {
  15209. observed_remote_addr = req.remote_addr;
  15210. observed_xff = req.get_header_value("X-Forwarded-For");
  15211. res.set_content("ok", "text/plain");
  15212. });
  15213. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15214. auto se = detail::scope_exit([&] {
  15215. svr.stop();
  15216. t.join();
  15217. ASSERT_FALSE(svr.is_running());
  15218. });
  15219. svr.wait_until_ready();
  15220. Client cli(HOST, PORT);
  15221. auto res = cli.Get(
  15222. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  15223. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15224. EXPECT_EQ(StatusCode::OK_200, res->status);
  15225. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  15226. // by the closest hop) is used. The leftmost entry is fully client-controlled
  15227. // and must not be selected.
  15228. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  15229. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  15230. }
  15231. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  15232. Server svr;
  15233. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  15234. std::string observed_remote_addr;
  15235. svr.Get("/ip", [&](const Request &req, Response &res) {
  15236. observed_remote_addr = req.remote_addr;
  15237. res.set_content("ok", "text/plain");
  15238. });
  15239. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15240. auto se = detail::scope_exit([&] {
  15241. svr.stop();
  15242. t.join();
  15243. ASSERT_FALSE(svr.is_running());
  15244. });
  15245. svr.wait_until_ready();
  15246. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  15247. // a forged address and the trusted proxy's own address; the forged value must
  15248. // not win over the address the trusted proxy actually recorded.
  15249. Client cli(HOST, PORT);
  15250. auto res = cli.Get(
  15251. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  15252. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15253. EXPECT_EQ(StatusCode::OK_200, res->status);
  15254. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  15255. }
  15256. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  15257. Server svr;
  15258. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  15259. std::string observed_remote_addr;
  15260. std::string observed_xff;
  15261. svr.Get("/ip", [&](const Request &req, Response &res) {
  15262. observed_remote_addr = req.remote_addr;
  15263. observed_xff = req.get_header_value("X-Forwarded-For");
  15264. res.set_content("ok", "text/plain");
  15265. });
  15266. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15267. auto se = detail::scope_exit([&] {
  15268. svr.stop();
  15269. t.join();
  15270. ASSERT_FALSE(svr.is_running());
  15271. });
  15272. svr.wait_until_ready();
  15273. Client cli(HOST, PORT);
  15274. auto res = cli.Get(
  15275. "/ip",
  15276. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  15277. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15278. EXPECT_EQ(StatusCode::OK_200, res->status);
  15279. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  15280. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  15281. }
  15282. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  15283. Server svr;
  15284. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  15285. std::string observed_remote_addr;
  15286. std::string observed_xff;
  15287. svr.Get("/ip", [&](const Request &req, Response &res) {
  15288. observed_remote_addr = req.remote_addr;
  15289. observed_xff = req.get_header_value("X-Forwarded-For");
  15290. res.set_content("ok", "text/plain");
  15291. });
  15292. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15293. auto se = detail::scope_exit([&] {
  15294. svr.stop();
  15295. t.join();
  15296. ASSERT_FALSE(svr.is_running());
  15297. });
  15298. svr.wait_until_ready();
  15299. std::string raw_req =
  15300. "GET /ip HTTP/1.1\r\n"
  15301. "Host: localhost\r\n"
  15302. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  15303. "Connection: close\r\n"
  15304. "\r\n";
  15305. std::string out;
  15306. ASSERT_TRUE(send_request(5, raw_req, &out));
  15307. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  15308. // Header parser trims surrounding whitespace of the header value
  15309. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  15310. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  15311. }
  15312. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  15313. // one comma-joined value, in the order received. Proxies such as HAProxy append
  15314. // their own X-Forwarded-For as a separate field line rather than extending the
  15315. // one the client sent, so every occurrence has to be taken into account.
  15316. // Reading only the first one hands back the address the client chose.
  15317. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  15318. Server svr;
  15319. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  15320. std::string observed_remote_addr;
  15321. size_t observed_xff_count = 0;
  15322. svr.Get("/ip", [&](const Request &req, Response &res) {
  15323. observed_remote_addr = req.remote_addr;
  15324. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  15325. res.set_content("ok", "text/plain");
  15326. });
  15327. auto port = svr.bind_to_any_port(HOST);
  15328. thread t = thread([&]() { svr.listen_after_bind(); });
  15329. auto se = detail::scope_exit([&] {
  15330. svr.stop();
  15331. t.join();
  15332. ASSERT_FALSE(svr.is_running());
  15333. });
  15334. svr.wait_until_ready();
  15335. // The client supplies the first field line; the trusted proxy appends the
  15336. // address it observed as a second one.
  15337. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  15338. "Host: localhost\r\n"
  15339. "X-Forwarded-For: 1.2.3.4\r\n"
  15340. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  15341. "Connection: close\r\n"
  15342. "\r\n";
  15343. std::string out;
  15344. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  15345. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  15346. EXPECT_EQ(observed_xff_count, 2U);
  15347. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  15348. // The same chain spread over one field line per hop derives the same client
  15349. // address, i.e. the split and the comma-joined representations agree.
  15350. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  15351. "Host: localhost\r\n"
  15352. "X-Forwarded-For: 1.2.3.4\r\n"
  15353. "X-Forwarded-For: 198.51.100.23\r\n"
  15354. "X-Forwarded-For: 192.0.2.45\r\n"
  15355. "Connection: close\r\n"
  15356. "\r\n";
  15357. out.clear();
  15358. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  15359. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  15360. EXPECT_EQ(observed_xff_count, 3U);
  15361. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  15362. }
  15363. // An X-Forwarded-For header whose value parses to zero IP segments must not
  15364. // crash the server (it used to call front() on an empty vector inside
  15365. // get_client_ip). The connection-level remote address must be retained instead.
  15366. static void run_malformed_xff_test(const std::string &xff_value) {
  15367. Server svr;
  15368. svr.set_trusted_proxies({"192.0.2.45"});
  15369. std::string observed_remote_addr;
  15370. svr.Get("/ip", [&](const Request &req, Response &res) {
  15371. observed_remote_addr = req.remote_addr;
  15372. res.set_content("ok", "text/plain");
  15373. });
  15374. int port = 0;
  15375. thread t = thread([&]() {
  15376. port = svr.bind_to_any_port(HOST);
  15377. svr.listen_after_bind();
  15378. });
  15379. auto se = detail::scope_exit([&] {
  15380. svr.stop();
  15381. t.join();
  15382. ASSERT_FALSE(svr.is_running());
  15383. });
  15384. svr.wait_until_ready();
  15385. Client cli(HOST, port);
  15386. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  15387. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15388. EXPECT_EQ(StatusCode::OK_200, res->status);
  15389. EXPECT_TRUE(observed_remote_addr == "::1" ||
  15390. observed_remote_addr == "127.0.0.1");
  15391. }
  15392. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  15393. run_malformed_xff_test("");
  15394. }
  15395. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  15396. run_malformed_xff_test(",");
  15397. }
  15398. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  15399. run_malformed_xff_test(", , ,");
  15400. }
  15401. // The same rule applies to Accept: a request whose acceptable types are spread
  15402. // over several field lines must be negotiated against all of them.
  15403. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  15404. // case-insensitive connection options. Comparing the whole field value against
  15405. // one option misses a client that sends several of them, and misses every
  15406. // casing but the one written in the comparison.
  15407. //
  15408. // Sends req, reads the response, then reuses the same socket for a second
  15409. // request to find out whether the server kept the connection.
  15410. static void probe_connection_reuse(int port, const std::string &req,
  15411. bool *announced_close, bool *reusable) {
  15412. auto error = Error::Success;
  15413. auto sock = detail::create_client_socket(
  15414. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  15415. /*connection_timeout_sec=*/5, 0,
  15416. /*read_timeout_sec=*/1, 0,
  15417. /*write_timeout_sec=*/5, 0, std::string(), error);
  15418. ASSERT_NE(sock, INVALID_SOCKET);
  15419. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  15420. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  15421. "Host: localhost\r\n"
  15422. "Connection: close\r\n"
  15423. "\r\n";
  15424. std::string first_response;
  15425. std::string second_response;
  15426. detail::process_client_socket(
  15427. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  15428. [&](Stream &strm) {
  15429. if (strm.write(req.data(), req.size()) !=
  15430. static_cast<ssize_t>(req.size())) {
  15431. return false;
  15432. }
  15433. char buf[512];
  15434. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  15435. // Headers plus the two-byte body of the handler below
  15436. while (reader.getline()) {
  15437. first_response += reader.ptr();
  15438. if (first_response.find("ok") != std::string::npos) { break; }
  15439. }
  15440. if (strm.write(second.data(), second.size()) !=
  15441. static_cast<ssize_t>(second.size())) {
  15442. return true;
  15443. }
  15444. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  15445. while (reader2.getline()) {
  15446. second_response += reader2.ptr();
  15447. if (second_response.find("ok") != std::string::npos) { break; }
  15448. }
  15449. return true;
  15450. });
  15451. *announced_close =
  15452. first_response.find("Connection: close") != std::string::npos;
  15453. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  15454. }
  15455. class ConnectionTokenTest : public ::testing::Test {
  15456. protected:
  15457. void SetUp() override {
  15458. svr_.Get("/keepalive", [](const Request &, Response &res) {
  15459. res.set_content("ok", "text/plain");
  15460. });
  15461. port_ = svr_.bind_to_any_port(HOST);
  15462. thread_ = thread([&]() { svr_.listen_after_bind(); });
  15463. svr_.wait_until_ready();
  15464. }
  15465. void TearDown() override {
  15466. svr_.stop();
  15467. if (thread_.joinable()) { thread_.join(); }
  15468. }
  15469. Server svr_;
  15470. int port_ = 0;
  15471. thread thread_;
  15472. };
  15473. // "close" alongside another option still closes the connection, and the
  15474. // response says so rather than leaving the peer to discover it.
  15475. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  15476. bool announced_close = false;
  15477. bool reusable = true;
  15478. probe_connection_reuse(port_,
  15479. "GET /keepalive HTTP/1.1\r\n"
  15480. "Host: localhost\r\n"
  15481. "Connection: keep-alive, close\r\n"
  15482. "\r\n",
  15483. &announced_close, &reusable);
  15484. EXPECT_TRUE(announced_close);
  15485. EXPECT_FALSE(reusable);
  15486. }
  15487. // "close" split over two field lines is the same list, so it is honored too.
  15488. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  15489. bool announced_close = false;
  15490. bool reusable = true;
  15491. probe_connection_reuse(port_,
  15492. "GET /keepalive HTTP/1.1\r\n"
  15493. "Host: localhost\r\n"
  15494. "Connection: keep-alive\r\n"
  15495. "Connection: close\r\n"
  15496. "\r\n",
  15497. &announced_close, &reusable);
  15498. EXPECT_TRUE(announced_close);
  15499. EXPECT_FALSE(reusable);
  15500. }
  15501. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  15502. // keep-alive in the spelling everyone actually sends keeps its connection.
  15503. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  15504. bool announced_close = false;
  15505. bool reusable = false;
  15506. probe_connection_reuse(port_,
  15507. "GET /keepalive HTTP/1.0\r\n"
  15508. "Host: localhost\r\n"
  15509. "Connection: keep-alive\r\n"
  15510. "\r\n",
  15511. &announced_close, &reusable);
  15512. EXPECT_FALSE(announced_close);
  15513. EXPECT_TRUE(reusable);
  15514. }
  15515. // A token the value merely contains is not the token itself.
  15516. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  15517. bool announced_close = false;
  15518. bool reusable = false;
  15519. probe_connection_reuse(port_,
  15520. "GET /keepalive HTTP/1.1\r\n"
  15521. "Host: localhost\r\n"
  15522. "Connection: notclose\r\n"
  15523. "\r\n",
  15524. &announced_close, &reusable);
  15525. EXPECT_FALSE(announced_close);
  15526. EXPECT_TRUE(reusable);
  15527. }
  15528. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  15529. Server svr;
  15530. std::vector<std::string> observed_types;
  15531. svr.Get("/", [&](const Request &req, Response &res) {
  15532. observed_types = req.accept_content_types;
  15533. res.set_content("ok", "text/plain");
  15534. });
  15535. auto port = svr.bind_to_any_port(HOST);
  15536. thread t = thread([&]() { svr.listen_after_bind(); });
  15537. auto se = detail::scope_exit([&] {
  15538. svr.stop();
  15539. t.join();
  15540. ASSERT_FALSE(svr.is_running());
  15541. });
  15542. svr.wait_until_ready();
  15543. Client cli(HOST, port);
  15544. Headers headers;
  15545. headers.emplace("Accept", "text/plain;q=0.5");
  15546. headers.emplace("Accept", "application/json");
  15547. auto res = cli.Get("/", headers);
  15548. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15549. EXPECT_EQ(StatusCode::OK_200, res->status);
  15550. // Sorted by q-value, so the second field line's type comes first
  15551. ASSERT_EQ(2U, observed_types.size());
  15552. EXPECT_EQ("application/json", observed_types[0]);
  15553. EXPECT_EQ("text/plain", observed_types[1]);
  15554. }
  15555. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  15556. // empty field line must not contribute a bare comma to the combined value.
  15557. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  15558. Server svr;
  15559. std::vector<std::string> observed_types;
  15560. svr.Get("/", [&](const Request &req, Response &res) {
  15561. observed_types = req.accept_content_types;
  15562. res.set_content("ok", "text/plain");
  15563. });
  15564. auto port = svr.bind_to_any_port(HOST);
  15565. thread t = thread([&]() { svr.listen_after_bind(); });
  15566. auto se = detail::scope_exit([&] {
  15567. svr.stop();
  15568. t.join();
  15569. ASSERT_FALSE(svr.is_running());
  15570. });
  15571. svr.wait_until_ready();
  15572. // Empty first field line, then a real one
  15573. std::string raw_req = "GET / HTTP/1.1\r\n"
  15574. "Host: localhost\r\n"
  15575. "Accept:\r\n"
  15576. "Accept: application/json\r\n"
  15577. "Connection: close\r\n"
  15578. "\r\n";
  15579. std::string out;
  15580. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  15581. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  15582. ASSERT_EQ(1U, observed_types.size());
  15583. EXPECT_EQ("application/json", observed_types[0]);
  15584. }
  15585. // The skip in get_combined_header_value() is what keeps an empty field line
  15586. // from contributing a bare comma. Only a trailing empty field line exercises
  15587. // it: a leading one is already covered by the "combined is still empty" check,
  15588. // and parse_accept_header() now ignores the empty element either way, so the
  15589. // request-level test above can no longer tell the two apart.
  15590. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  15591. Headers headers;
  15592. headers.emplace("Accept", "text/html");
  15593. headers.emplace("Accept", "");
  15594. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  15595. headers.clear();
  15596. headers.emplace("Accept", "");
  15597. headers.emplace("Accept", "application/json");
  15598. EXPECT_EQ("application/json",
  15599. detail::get_combined_header_value(headers, "Accept"));
  15600. }
  15601. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  15602. // An encoding offered on a later Accept-Encoding field line is still offered.
  15603. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  15604. Server svr;
  15605. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15606. res.set_content(std::string(1024, 'x'), "text/plain");
  15607. });
  15608. auto port = svr.bind_to_any_port(HOST);
  15609. thread t = thread([&]() { svr.listen_after_bind(); });
  15610. auto se = detail::scope_exit([&] {
  15611. svr.stop();
  15612. t.join();
  15613. ASSERT_FALSE(svr.is_running());
  15614. });
  15615. svr.wait_until_ready();
  15616. Client cli(HOST, port);
  15617. cli.set_decompress(false);
  15618. Headers headers;
  15619. headers.emplace("Accept-Encoding", "identity");
  15620. headers.emplace("Accept-Encoding", "gzip");
  15621. auto res = cli.Get("/", headers);
  15622. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15623. EXPECT_EQ(StatusCode::OK_200, res->status);
  15624. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  15625. }
  15626. #endif
  15627. #ifndef _WIN32
  15628. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  15629. Server svr;
  15630. svr.Post("/post", [&](const Request &req, Response &res) {
  15631. res.set_content(req.body, "text/plain");
  15632. });
  15633. svr.Put("/put", [&](const Request &req, Response &res) {
  15634. res.set_content(req.body, "text/plain");
  15635. });
  15636. svr.Patch("/patch", [&](const Request &req, Response &res) {
  15637. res.set_content(req.body, "text/plain");
  15638. });
  15639. svr.Delete("/delete", [&](const Request &req, Response &res) {
  15640. res.set_content(req.body, "text/plain");
  15641. });
  15642. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15643. auto se = detail::scope_exit([&] {
  15644. svr.stop();
  15645. t.join();
  15646. ASSERT_FALSE(svr.is_running());
  15647. });
  15648. svr.wait_until_ready();
  15649. std::string resp;
  15650. // POST without Content-Length
  15651. ASSERT_TRUE(send_request(5,
  15652. "POST /post HTTP/1.1\r\n"
  15653. "Host: localhost\r\n"
  15654. "Connection: close\r\n"
  15655. "\r\n",
  15656. &resp));
  15657. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  15658. // PUT without Content-Length
  15659. resp.clear();
  15660. ASSERT_TRUE(send_request(5,
  15661. "PUT /put HTTP/1.1\r\n"
  15662. "Host: localhost\r\n"
  15663. "Connection: close\r\n"
  15664. "\r\n",
  15665. &resp));
  15666. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  15667. // PATCH without Content-Length
  15668. resp.clear();
  15669. ASSERT_TRUE(send_request(5,
  15670. "PATCH /patch HTTP/1.1\r\n"
  15671. "Host: localhost\r\n"
  15672. "Connection: close\r\n"
  15673. "\r\n",
  15674. &resp));
  15675. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  15676. // DELETE without Content-Length
  15677. resp.clear();
  15678. ASSERT_TRUE(send_request(5,
  15679. "DELETE /delete HTTP/1.1\r\n"
  15680. "Host: localhost\r\n"
  15681. "Connection: close\r\n"
  15682. "\r\n",
  15683. &resp));
  15684. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  15685. }
  15686. #endif
  15687. //==============================================================================
  15688. // open_stream() Tests
  15689. //==============================================================================
  15690. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  15691. std::string result;
  15692. char buf[8192];
  15693. ssize_t n;
  15694. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  15695. result.append(buf, static_cast<size_t>(n));
  15696. }
  15697. return result;
  15698. }
  15699. // Mock stream for unit tests
  15700. class MockStream : public Stream {
  15701. public:
  15702. std::string data;
  15703. size_t pos = 0;
  15704. ssize_t error_after = -1; // -1 = no error
  15705. explicit MockStream(const std::string &d, ssize_t err = -1)
  15706. : data(d), error_after(err) {}
  15707. bool is_readable() const override { return true; }
  15708. bool wait_readable() const override { return true; }
  15709. bool wait_writable() const override { return true; }
  15710. ssize_t read(char *ptr, size_t size) override {
  15711. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  15712. if (pos >= data.size()) return 0;
  15713. size_t limit =
  15714. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  15715. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  15716. std::memcpy(ptr, data.data() + pos, to_read);
  15717. pos += to_read;
  15718. return static_cast<ssize_t>(to_read);
  15719. }
  15720. ssize_t write(const char *, size_t) override { return -1; }
  15721. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  15722. ip = "127.0.0.1";
  15723. port = 0;
  15724. }
  15725. void get_local_ip_and_port(std::string &ip, int &port) const override {
  15726. ip = "127.0.0.1";
  15727. port = 0;
  15728. }
  15729. socket_t socket() const override { return INVALID_SOCKET; }
  15730. time_t duration() const override { return 0; }
  15731. };
  15732. TEST(StreamHandleTest, Basic) {
  15733. ClientImpl::StreamHandle handle;
  15734. EXPECT_FALSE(handle.is_valid());
  15735. handle.response = detail::make_unique<Response>();
  15736. handle.error = Error::Connection;
  15737. EXPECT_FALSE(handle.is_valid());
  15738. handle.error = Error::Success;
  15739. EXPECT_TRUE(handle.is_valid());
  15740. }
  15741. TEST(BodyReaderTest, Basic) {
  15742. MockStream stream("Hello, World!");
  15743. detail::BodyReader reader;
  15744. reader.stream = &stream;
  15745. reader.content_length = 13;
  15746. char buf[32];
  15747. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  15748. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  15749. EXPECT_TRUE(reader.eof);
  15750. }
  15751. TEST(BodyReaderTest, NoStream) {
  15752. detail::BodyReader reader;
  15753. char buf[32];
  15754. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  15755. EXPECT_EQ(Error::Connection, reader.last_error);
  15756. }
  15757. TEST(BodyReaderTest, Error) {
  15758. MockStream stream("Hello, World!", 5);
  15759. detail::BodyReader reader;
  15760. reader.stream = &stream;
  15761. reader.content_length = 13;
  15762. char buf[32];
  15763. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  15764. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  15765. EXPECT_EQ(Error::Read, reader.last_error);
  15766. }
  15767. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  15768. // Mock-based StreamHandle tests relying on private internals are removed.
  15769. class OpenStreamTest : public ::testing::Test {
  15770. protected:
  15771. void SetUp() override {
  15772. svr_.Get("/hello", [](const Request &, Response &res) {
  15773. res.set_content("Hello World!", "text/plain");
  15774. });
  15775. svr_.Get("/large", [](const Request &, Response &res) {
  15776. res.set_content(std::string(10000, 'X'), "text/plain");
  15777. });
  15778. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  15779. res.set_content("Hello World!", "image/jpeg");
  15780. res.set_header("Content-Encoding", "UTF-8");
  15781. });
  15782. svr_.Get("/chunked", [](const Request &, Response &res) {
  15783. res.set_chunked_content_provider("text/plain",
  15784. [](size_t offset, DataSink &sink) {
  15785. if (offset < 15) {
  15786. sink.write("chunk", 5);
  15787. return true;
  15788. }
  15789. sink.done();
  15790. return true;
  15791. });
  15792. });
  15793. svr_.Get("/compressible", [](const Request &, Response &res) {
  15794. res.set_chunked_content_provider("text/plain", [](size_t offset,
  15795. DataSink &sink) {
  15796. if (offset < 100 * 1024) {
  15797. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  15798. sink.write(chunk.data(), chunk.size());
  15799. return true;
  15800. }
  15801. sink.done();
  15802. return true;
  15803. });
  15804. });
  15805. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  15806. [](const Request & /*req*/, Response &res) {
  15807. auto i = new int(0);
  15808. res.set_header("Trailer", "Content-Length, X-Allowed");
  15809. res.set_chunked_content_provider(
  15810. "text/plain",
  15811. [i](size_t /*offset*/, DataSink &sink) {
  15812. switch (*i) {
  15813. case 0: sink.os << "123"; break;
  15814. case 1: sink.os << "456"; break;
  15815. case 2: sink.os << "789"; break;
  15816. case 3: {
  15817. sink.done_with_trailer(
  15818. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  15819. } break;
  15820. }
  15821. (*i)++;
  15822. return true;
  15823. },
  15824. [i](bool success) {
  15825. EXPECT_TRUE(success);
  15826. delete i;
  15827. });
  15828. });
  15829. // Echo headers endpoint for header-related tests
  15830. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  15831. std::string body;
  15832. for (const auto &h : req.headers) {
  15833. body.append(h.first);
  15834. body.push_back(':');
  15835. body.append(h.second);
  15836. body.push_back('\n');
  15837. }
  15838. res.set_content(body, "text/plain");
  15839. });
  15840. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  15841. std::string body;
  15842. for (const auto &h : req.headers) {
  15843. body.append(h.first);
  15844. body.push_back(':');
  15845. body.append(h.second);
  15846. body.push_back('\n');
  15847. }
  15848. res.set_content(body, "text/plain");
  15849. });
  15850. port_ = svr_.bind_to_any_port("127.0.0.1");
  15851. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  15852. svr_.wait_until_ready();
  15853. }
  15854. void TearDown() override {
  15855. svr_.stop();
  15856. if (thread_.joinable()) thread_.join();
  15857. }
  15858. Server svr_;
  15859. std::thread thread_;
  15860. int port_ = 0;
  15861. };
  15862. TEST_F(OpenStreamTest, Basic) {
  15863. Client cli("127.0.0.1", port_);
  15864. auto handle = cli.open_stream("GET", "/hello");
  15865. EXPECT_TRUE(handle.is_valid());
  15866. EXPECT_EQ("Hello World!", read_all(handle));
  15867. }
  15868. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  15869. Client cli("127.0.0.1", port_);
  15870. auto handle = cli.open_stream("GET", "/unknown-encoding");
  15871. ASSERT_TRUE(handle.is_valid());
  15872. EXPECT_EQ("Hello World!", read_all(handle));
  15873. }
  15874. TEST_F(OpenStreamTest, SmallBuffer) {
  15875. Client cli("127.0.0.1", port_);
  15876. auto handle = cli.open_stream("GET", "/hello");
  15877. std::string result;
  15878. char buf[4];
  15879. ssize_t n;
  15880. while ((n = handle.read(buf, sizeof(buf))) > 0)
  15881. result.append(buf, static_cast<size_t>(n));
  15882. EXPECT_EQ("Hello World!", result);
  15883. }
  15884. TEST_F(OpenStreamTest, DefaultHeaders) {
  15885. Client cli("127.0.0.1", port_);
  15886. // open_stream GET should include Host, User-Agent and Accept-Encoding
  15887. {
  15888. auto handle = cli.open_stream("GET", "/echo-headers");
  15889. ASSERT_TRUE(handle.is_valid());
  15890. auto body = read_all(handle);
  15891. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  15892. std::string::npos);
  15893. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  15894. std::string::npos);
  15895. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  15896. }
  15897. // open_stream POST with body and no explicit content_type should NOT add
  15898. // text/plain Content-Type (behavior differs from non-streaming path), but
  15899. // should include Content-Length
  15900. {
  15901. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  15902. ASSERT_TRUE(handle.is_valid());
  15903. auto body = read_all(handle);
  15904. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  15905. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  15906. }
  15907. // open_stream POST with explicit Content-Type should preserve it
  15908. {
  15909. auto handle = cli.open_stream("POST", "/echo-headers", {},
  15910. {{"Content-Type", "application/custom"}},
  15911. "{}", "application/custom");
  15912. ASSERT_TRUE(handle.is_valid());
  15913. auto body = read_all(handle);
  15914. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  15915. }
  15916. // User-specified User-Agent must not be overwritten for stream API
  15917. {
  15918. auto handle = cli.open_stream("GET", "/echo-headers", {},
  15919. {{"User-Agent", "MyAgent/1.2"}});
  15920. ASSERT_TRUE(handle.is_valid());
  15921. auto body = read_all(handle);
  15922. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  15923. }
  15924. }
  15925. TEST_F(OpenStreamTest, Large) {
  15926. Client cli("127.0.0.1", port_);
  15927. auto handle = cli.open_stream("GET", "/large");
  15928. EXPECT_EQ(10000u, read_all(handle).size());
  15929. }
  15930. TEST_F(OpenStreamTest, ConnectionError) {
  15931. Client cli("127.0.0.1", 9999);
  15932. auto handle = cli.open_stream("GET", "/hello");
  15933. EXPECT_FALSE(handle.is_valid());
  15934. }
  15935. TEST_F(OpenStreamTest, Chunked) {
  15936. Client cli("127.0.0.1", port_);
  15937. auto handle = cli.open_stream("GET", "/chunked");
  15938. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  15939. "Transfer-Encoding") == "chunked");
  15940. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  15941. }
  15942. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  15943. Client cli("127.0.0.1", port_);
  15944. auto handle =
  15945. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  15946. ASSERT_TRUE(handle.is_valid());
  15947. // Consume body to allow trailers to be received/parsed
  15948. auto body = read_all(handle);
  15949. // Explicitly parse trailers (ensure trailers are available for assertion)
  15950. handle.parse_trailers_if_needed();
  15951. EXPECT_EQ(std::string("123456789"), body);
  15952. // The response should include a Trailer header declaring both names
  15953. ASSERT_TRUE(handle.response);
  15954. EXPECT_TRUE(handle.response->has_header("Trailer"));
  15955. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  15956. handle.response->get_header_value("Trailer"));
  15957. // Prohibited trailer must not be present
  15958. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  15959. // Allowed trailer should be present
  15960. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  15961. EXPECT_EQ(std::string("yes"),
  15962. handle.response->get_trailer_value("X-Allowed"));
  15963. // Verify trailers are NOT present as regular headers
  15964. EXPECT_EQ(std::string(""),
  15965. handle.response->get_header_value("Content-Length"));
  15966. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  15967. }
  15968. static std::thread serve_single_response(std::promise<int> &port_promise,
  15969. const std::string &response) {
  15970. return std::thread([&port_promise, response] {
  15971. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15972. default_socket_options(srv);
  15973. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  15974. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  15975. sockaddr_in addr{};
  15976. addr.sin_family = AF_INET;
  15977. addr.sin_port = htons(0); // Let OS assign a free port
  15978. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15979. int opt = 1;
  15980. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  15981. #ifdef _WIN32
  15982. reinterpret_cast<const char *>(&opt),
  15983. #else
  15984. &opt,
  15985. #endif
  15986. sizeof(opt));
  15987. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  15988. ::listen(srv, 1) != 0) {
  15989. port_promise.set_value(-1);
  15990. detail::close_socket(srv);
  15991. return;
  15992. }
  15993. socklen_t addr_len = sizeof(addr);
  15994. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  15995. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  15996. sockaddr_in cli_addr{};
  15997. socklen_t cli_len = sizeof(cli_addr);
  15998. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  15999. if (cli != INVALID_SOCKET) {
  16000. // Read the complete HTTP request (until the blank line that terminates
  16001. // headers) before sending the response. If the server closes the socket
  16002. // while the client's request data is still unread in the kernel receive
  16003. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  16004. // connection on both sides: it discards the client's receive buffer
  16005. // (which already holds our response) and causes any in-progress write on
  16006. // the client to fail with ECONNRESET. Reading all request data first
  16007. // ensures close() emits a graceful FIN.
  16008. {
  16009. char rbuf[256];
  16010. std::string req;
  16011. while (req.find("\r\n\r\n") == std::string::npos) {
  16012. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  16013. if (n <= 0) { break; }
  16014. req.append(rbuf, static_cast<size_t>(n));
  16015. }
  16016. }
  16017. ::send(cli,
  16018. #ifdef _WIN32
  16019. static_cast<const char *>(response.c_str()),
  16020. static_cast<int>(response.size()),
  16021. #else
  16022. response.c_str(), response.size(),
  16023. #endif
  16024. 0);
  16025. detail::close_socket(cli);
  16026. }
  16027. detail::close_socket(srv);
  16028. });
  16029. }
  16030. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  16031. #ifndef _WIN32
  16032. signal(SIGPIPE, SIG_IGN);
  16033. #endif
  16034. std::promise<int> port_promise;
  16035. auto port_future = port_promise.get_future();
  16036. auto server_thread =
  16037. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  16038. "Content-Type: text/plain\r\n"
  16039. "Content-Length: not-a-number\r\n"
  16040. "Connection: close\r\n"
  16041. "\r\n"
  16042. "hello");
  16043. auto port = port_future.get();
  16044. ASSERT_GT(port, 0);
  16045. Client cli("127.0.0.1", port);
  16046. auto handle = cli.open_stream("GET", "/");
  16047. EXPECT_FALSE(handle.is_valid());
  16048. server_thread.join();
  16049. }
  16050. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  16051. #ifndef _WIN32
  16052. signal(SIGPIPE, SIG_IGN);
  16053. #endif
  16054. std::promise<int> port_promise;
  16055. auto port_future = port_promise.get_future();
  16056. auto server_thread = serve_single_response(
  16057. port_promise, "HTTP/1.1 200 OK\r\n"
  16058. "Content-Type: text/plain\r\n"
  16059. "Content-Length: 99999999999999999999999999\r\n"
  16060. "Connection: close\r\n"
  16061. "\r\n"
  16062. "hello");
  16063. auto port = port_future.get();
  16064. ASSERT_GT(port, 0);
  16065. // Historically std::stoull would throw std::out_of_range here and crash
  16066. // the process, then parsing silently clamped to a bogus framing length and
  16067. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  16068. // so the stream fails to open, matching the not-a-number case above. The
  16069. // process still must NOT terminate.
  16070. Client cli("127.0.0.1", port);
  16071. auto handle = cli.open_stream("GET", "/");
  16072. EXPECT_FALSE(handle.is_valid());
  16073. server_thread.join();
  16074. }
  16075. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  16076. TEST_F(OpenStreamTest, Gzip) {
  16077. Client cli("127.0.0.1", port_);
  16078. auto handle = cli.open_stream("GET", "/compressible", {},
  16079. {{"Accept-Encoding", "gzip"}});
  16080. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  16081. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  16082. }
  16083. #endif
  16084. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  16085. TEST_F(OpenStreamTest, Brotli) {
  16086. Client cli("127.0.0.1", port_);
  16087. auto handle =
  16088. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  16089. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  16090. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  16091. }
  16092. #endif
  16093. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  16094. TEST_F(OpenStreamTest, Zstd) {
  16095. Client cli("127.0.0.1", port_);
  16096. auto handle = cli.open_stream("GET", "/compressible", {},
  16097. {{"Accept-Encoding", "zstd"}});
  16098. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  16099. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  16100. }
  16101. #endif
  16102. #ifdef CPPHTTPLIB_SSL_ENABLED
  16103. class SSLOpenStreamTest : public ::testing::Test {
  16104. protected:
  16105. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  16106. void SetUp() override {
  16107. svr_.Get("/hello", [](const Request &, Response &res) {
  16108. res.set_content("Hello SSL World!", "text/plain");
  16109. });
  16110. svr_.Get("/chunked", [](const Request &, Response &res) {
  16111. res.set_chunked_content_provider("text/plain",
  16112. [](size_t offset, DataSink &sink) {
  16113. if (offset < 15) {
  16114. sink.write("chunk", 5);
  16115. return true;
  16116. }
  16117. sink.done();
  16118. return true;
  16119. });
  16120. });
  16121. svr_.Post("/echo", [](const Request &req, Response &res) {
  16122. res.set_content(req.body, req.get_header_value("Content-Type"));
  16123. });
  16124. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  16125. std::string body = req.body;
  16126. res.set_chunked_content_provider(
  16127. "text/plain", [body](size_t offset, DataSink &sink) {
  16128. if (offset < body.size()) {
  16129. sink.write(body.data() + offset, body.size() - offset);
  16130. }
  16131. sink.done();
  16132. return true;
  16133. });
  16134. });
  16135. port_ = svr_.bind_to_any_port("127.0.0.1");
  16136. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  16137. svr_.wait_until_ready();
  16138. }
  16139. void TearDown() override {
  16140. svr_.stop();
  16141. if (thread_.joinable()) thread_.join();
  16142. }
  16143. SSLServer svr_;
  16144. std::thread thread_;
  16145. int port_ = 0;
  16146. };
  16147. TEST_F(SSLOpenStreamTest, Basic) {
  16148. SSLClient cli("127.0.0.1", port_);
  16149. cli.enable_server_certificate_verification(false);
  16150. auto handle = cli.open_stream("GET", "/hello");
  16151. ASSERT_TRUE(handle.is_valid());
  16152. EXPECT_EQ("Hello SSL World!", read_all(handle));
  16153. }
  16154. TEST_F(SSLOpenStreamTest, Chunked) {
  16155. SSLClient cli("127.0.0.1", port_);
  16156. cli.enable_server_certificate_verification(false);
  16157. auto handle = cli.open_stream("GET", "/chunked");
  16158. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  16159. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  16160. "Transfer-Encoding") == "chunked");
  16161. auto body = read_all(handle);
  16162. EXPECT_EQ("chunkchunkchunk", body);
  16163. }
  16164. TEST_F(SSLOpenStreamTest, Post) {
  16165. SSLClient cli("127.0.0.1", port_);
  16166. cli.enable_server_certificate_verification(false);
  16167. auto handle =
  16168. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  16169. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  16170. EXPECT_EQ(200, handle.response->status);
  16171. auto body = read_all(handle);
  16172. EXPECT_EQ("Hello SSL POST", body);
  16173. }
  16174. TEST_F(SSLOpenStreamTest, PostChunked) {
  16175. SSLClient cli("127.0.0.1", port_);
  16176. cli.enable_server_certificate_verification(false);
  16177. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  16178. "Chunked SSL Data", "text/plain");
  16179. ASSERT_TRUE(handle.is_valid());
  16180. EXPECT_EQ(200, handle.response->status);
  16181. auto body = read_all(handle);
  16182. EXPECT_EQ("Chunked SSL Data", body);
  16183. }
  16184. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  16185. // Content-Length is terminated by the server closing the connection. When the
  16186. // SSL peer sends a close_notify after the body, the client must treat it as a
  16187. // clean EOF and return a successful response rather than an error.
  16188. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  16189. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16190. ASSERT_TRUE(svr.is_valid());
  16191. svr.set_keep_alive_max_count(1);
  16192. const std::string expected_body = "Hello from connection-close response!";
  16193. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  16194. res.set_content_provider("text/plain",
  16195. [&](size_t offset, DataSink &sink) -> bool {
  16196. if (offset < expected_body.size()) {
  16197. sink.write(expected_body.data() + offset,
  16198. expected_body.size() - offset);
  16199. }
  16200. sink.done();
  16201. return true;
  16202. });
  16203. });
  16204. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  16205. auto se = detail::scope_exit([&] {
  16206. svr.stop();
  16207. listen_thread.join();
  16208. ASSERT_FALSE(svr.is_running());
  16209. });
  16210. svr.wait_until_ready();
  16211. SSLClient cli(HOST, PORT);
  16212. cli.enable_server_certificate_verification(false);
  16213. auto res = cli.Get("/no-content-length");
  16214. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  16215. EXPECT_EQ(StatusCode::OK_200, res->status);
  16216. EXPECT_EQ(expected_body, res->body);
  16217. }
  16218. #endif // CPPHTTPLIB_SSL_ENABLED
  16219. //==============================================================================
  16220. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  16221. // results for various scenarios.
  16222. //==============================================================================
  16223. TEST(ParityTest, GetVsOpenStream) {
  16224. Server svr;
  16225. const std::string path = "/parity";
  16226. const std::string content = "Parity test content: hello world";
  16227. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  16228. res.set_content(content, "text/plain");
  16229. });
  16230. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16231. auto se = detail::scope_exit([&] {
  16232. svr.stop();
  16233. t.join();
  16234. ASSERT_FALSE(svr.is_running());
  16235. });
  16236. svr.wait_until_ready();
  16237. Client cli(HOST, PORT);
  16238. // Non-stream path
  16239. auto r1 = cli.Get(path);
  16240. ASSERT_TRUE(r1);
  16241. EXPECT_EQ(StatusCode::OK_200, r1->status);
  16242. // Stream path
  16243. auto h = cli.open_stream("GET", path);
  16244. ASSERT_TRUE(h.is_valid());
  16245. EXPECT_EQ(r1->body, read_all(h));
  16246. }
  16247. // Helper to compress data with provided compressor type T
  16248. template <typename Compressor>
  16249. static std::string compress_payload_for_parity(const std::string &in) {
  16250. std::string out;
  16251. Compressor compressor;
  16252. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  16253. [&](const char *data, size_t n) {
  16254. out.append(data, n);
  16255. return true;
  16256. });
  16257. EXPECT_TRUE(ok);
  16258. return out;
  16259. }
  16260. // Helper function for compression parity tests
  16261. template <typename Compressor>
  16262. static void test_compression_parity(const std::string &original,
  16263. const std::string &path,
  16264. const std::string &encoding) {
  16265. const std::string compressed =
  16266. compress_payload_for_parity<Compressor>(original);
  16267. Server svr;
  16268. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  16269. res.set_content(compressed, "application/octet-stream");
  16270. res.set_header("Content-Encoding", encoding);
  16271. });
  16272. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  16273. auto se = detail::scope_exit([&] {
  16274. svr.stop();
  16275. t.join();
  16276. ASSERT_FALSE(svr.is_running());
  16277. });
  16278. svr.wait_until_ready();
  16279. Client cli(HOST, PORT);
  16280. // Non-streaming
  16281. {
  16282. auto res = cli.Get(path);
  16283. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16284. EXPECT_EQ(StatusCode::OK_200, res->status);
  16285. EXPECT_EQ(original, res->body);
  16286. }
  16287. // Streaming
  16288. {
  16289. auto h = cli.open_stream("GET", path);
  16290. ASSERT_TRUE(h.is_valid());
  16291. EXPECT_EQ(original, read_all(h));
  16292. }
  16293. }
  16294. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  16295. TEST(ParityTest, Gzip) {
  16296. test_compression_parity<detail::gzip_compressor>(
  16297. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  16298. }
  16299. #endif
  16300. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  16301. TEST(ParityTest, Brotli) {
  16302. test_compression_parity<detail::brotli_compressor>(
  16303. "Hello, brotli parity test payload", "/parity-br", "br");
  16304. }
  16305. #endif
  16306. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  16307. TEST(ParityTest, Zstd) {
  16308. test_compression_parity<detail::zstd_compressor>(
  16309. "Zstandard parity test payload", "/parity-zstd", "zstd");
  16310. }
  16311. #endif
  16312. //==============================================================================
  16313. // New Stream API Tests
  16314. //==============================================================================
  16315. inline std::string read_body(httplib::stream::Result &result) {
  16316. std::string body;
  16317. while (result.next()) {
  16318. body.append(result.data(), result.size());
  16319. }
  16320. return body;
  16321. }
  16322. TEST(ClientConnectionTest, Basic) {
  16323. httplib::ClientConnection conn;
  16324. EXPECT_FALSE(conn.is_open());
  16325. conn.sock = 1;
  16326. EXPECT_TRUE(conn.is_open());
  16327. httplib::ClientConnection conn2(std::move(conn));
  16328. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  16329. conn2.sock = INVALID_SOCKET;
  16330. }
  16331. // Unified test server for all stream::* tests
  16332. class StreamApiTest : public ::testing::Test {
  16333. protected:
  16334. void SetUp() override {
  16335. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  16336. res.set_content("Hello World!", "text/plain");
  16337. });
  16338. svr_.Get("/echo-params",
  16339. [](const httplib::Request &req, httplib::Response &res) {
  16340. std::string r;
  16341. for (const auto &p : req.params) {
  16342. if (!r.empty()) r += "&";
  16343. r += p.first + "=" + p.second;
  16344. }
  16345. res.set_content(r, "text/plain");
  16346. });
  16347. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  16348. res.set_content(req.body, req.get_header_value("Content-Type"));
  16349. });
  16350. svr_.Post("/echo-headers",
  16351. [](const httplib::Request &req, httplib::Response &res) {
  16352. std::string r;
  16353. for (const auto &h : req.headers)
  16354. r += h.first + ": " + h.second + "\n";
  16355. res.set_content(r, "text/plain");
  16356. });
  16357. svr_.Post("/echo-params",
  16358. [](const httplib::Request &req, httplib::Response &res) {
  16359. std::string r = "params:";
  16360. for (const auto &p : req.params)
  16361. r += p.first + "=" + p.second + ";";
  16362. res.set_content(r + " body:" + req.body, "text/plain");
  16363. });
  16364. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  16365. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  16366. });
  16367. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  16368. res.set_content("PUT:" + req.body, "text/plain");
  16369. });
  16370. svr_.Patch("/echo",
  16371. [](const httplib::Request &req, httplib::Response &res) {
  16372. res.set_content("PATCH:" + req.body, "text/plain");
  16373. });
  16374. svr_.Delete(
  16375. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  16376. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  16377. "text/plain");
  16378. });
  16379. svr_.Get("/head-test",
  16380. [](const httplib::Request &, httplib::Response &res) {
  16381. res.set_content("body for HEAD", "text/plain");
  16382. });
  16383. svr_.Options("/options",
  16384. [](const httplib::Request &, httplib::Response &res) {
  16385. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  16386. });
  16387. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  16388. svr_.wait_until_ready();
  16389. }
  16390. void TearDown() override {
  16391. svr_.stop();
  16392. if (thread_.joinable()) thread_.join();
  16393. }
  16394. httplib::Server svr_;
  16395. std::thread thread_;
  16396. };
  16397. // stream::Get tests
  16398. TEST_F(StreamApiTest, GetBasic) {
  16399. httplib::Client cli(HOST, PORT);
  16400. auto result = httplib::stream::Get(cli, "/hello");
  16401. ASSERT_TRUE(result.is_valid());
  16402. EXPECT_EQ(200, result.status());
  16403. EXPECT_EQ("Hello World!", read_body(result));
  16404. }
  16405. TEST_F(StreamApiTest, GetWithParams) {
  16406. httplib::Client cli(HOST, PORT);
  16407. httplib::Params params{{"foo", "bar"}};
  16408. auto result = httplib::stream::Get(cli, "/echo-params", params);
  16409. ASSERT_TRUE(result.is_valid());
  16410. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  16411. }
  16412. TEST_F(StreamApiTest, GetConnectionError) {
  16413. httplib::Client cli(HOST, 9999);
  16414. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  16415. }
  16416. TEST_F(StreamApiTest, Get404) {
  16417. httplib::Client cli(HOST, PORT);
  16418. auto result = httplib::stream::Get(cli, "/nonexistent");
  16419. EXPECT_TRUE(result.is_valid());
  16420. EXPECT_EQ(404, result.status());
  16421. }
  16422. // stream::Post tests
  16423. TEST_F(StreamApiTest, PostBasic) {
  16424. httplib::Client cli(HOST, PORT);
  16425. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  16426. "application/json");
  16427. ASSERT_TRUE(result.is_valid());
  16428. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  16429. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  16430. }
  16431. TEST_F(StreamApiTest, PostWithHeaders) {
  16432. httplib::Client cli(HOST, PORT);
  16433. httplib::Headers headers{{"X-Custom", "value"}};
  16434. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  16435. "text/plain");
  16436. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  16437. }
  16438. TEST_F(StreamApiTest, PostWithParams) {
  16439. httplib::Client cli(HOST, PORT);
  16440. httplib::Params params{{"k", "v"}};
  16441. auto result =
  16442. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  16443. auto body = read_body(result);
  16444. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  16445. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  16446. }
  16447. TEST_F(StreamApiTest, PostLarge) {
  16448. httplib::Client cli(HOST, PORT);
  16449. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  16450. size_t total = 0;
  16451. while (result.next()) {
  16452. total += result.size();
  16453. }
  16454. EXPECT_EQ(100u * 1024u, total);
  16455. }
  16456. // stream::Put/Patch tests
  16457. TEST_F(StreamApiTest, PutAndPatch) {
  16458. httplib::Client cli(HOST, PORT);
  16459. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  16460. EXPECT_EQ("PUT:test", read_body(put));
  16461. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  16462. EXPECT_EQ("PATCH:test", read_body(patch));
  16463. }
  16464. // stream::Delete tests
  16465. TEST_F(StreamApiTest, Delete) {
  16466. httplib::Client cli(HOST, PORT);
  16467. auto del1 = httplib::stream::Delete(cli, "/resource");
  16468. EXPECT_EQ("Deleted", read_body(del1));
  16469. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  16470. EXPECT_EQ("Deleted:data", read_body(del2));
  16471. }
  16472. // stream::Head/Options tests
  16473. TEST_F(StreamApiTest, HeadAndOptions) {
  16474. httplib::Client cli(HOST, PORT);
  16475. auto head = httplib::stream::Head(cli, "/head-test");
  16476. EXPECT_TRUE(head.is_valid());
  16477. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  16478. auto opts = httplib::stream::Options(cli, "/options");
  16479. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  16480. }
  16481. // SSL stream::* tests
  16482. #ifdef CPPHTTPLIB_SSL_ENABLED
  16483. class SSLStreamApiTest : public ::testing::Test {
  16484. protected:
  16485. void SetUp() override {
  16486. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  16487. res.set_content("Hello SSL!", "text/plain");
  16488. });
  16489. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  16490. res.set_content(req.body, "text/plain");
  16491. });
  16492. port_ = svr_.bind_to_any_port("127.0.0.1");
  16493. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  16494. svr_.wait_until_ready();
  16495. }
  16496. void TearDown() override {
  16497. svr_.stop();
  16498. if (thread_.joinable()) thread_.join();
  16499. }
  16500. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  16501. std::thread thread_;
  16502. int port_ = 0;
  16503. };
  16504. TEST_F(SSLStreamApiTest, GetAndPost) {
  16505. httplib::SSLClient cli("127.0.0.1", port_);
  16506. cli.enable_server_certificate_verification(false);
  16507. auto get = httplib::stream::Get(cli, "/hello");
  16508. EXPECT_EQ("Hello SSL!", read_body(get));
  16509. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  16510. EXPECT_EQ("test", read_body(post));
  16511. }
  16512. #endif
  16513. // Tests for Error::Timeout and Error::ConnectionClosed error types
  16514. // These errors are set in SocketStream/SSLSocketStream and propagated through
  16515. // BodyReader
  16516. TEST(ErrorHandlingTest, StreamReadTimeout) {
  16517. // Test that read timeout during streaming is detected
  16518. // Use a large content-length response where server delays mid-stream
  16519. Server svr;
  16520. svr.Get("/slow-stream", [](const Request &, Response &res) {
  16521. // Send a large response with delay in the middle
  16522. res.set_content_provider(
  16523. 1000, // content_length
  16524. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  16525. if (offset < 100) {
  16526. // Send first 100 bytes immediately
  16527. std::string data(100, 'A');
  16528. sink.write(data.c_str(), data.size());
  16529. return true;
  16530. }
  16531. // Then delay longer than client timeout
  16532. std::this_thread::sleep_for(std::chrono::seconds(3));
  16533. std::string data(900, 'B');
  16534. sink.write(data.c_str(), data.size());
  16535. return true;
  16536. });
  16537. });
  16538. auto port = 8091;
  16539. std::thread t([&]() { svr.listen("localhost", port); });
  16540. svr.wait_until_ready();
  16541. Client cli("localhost", port);
  16542. cli.set_read_timeout(1, 0); // 1 second timeout
  16543. auto handle = cli.open_stream("GET", "/slow-stream");
  16544. ASSERT_TRUE(handle.is_valid());
  16545. char buf[256];
  16546. ssize_t total = 0;
  16547. ssize_t n;
  16548. bool got_error = false;
  16549. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  16550. total += n;
  16551. }
  16552. if (n < 0) {
  16553. got_error = true;
  16554. // Should be timeout or read error
  16555. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  16556. handle.get_read_error() == Error::Read)
  16557. << "Actual error: " << to_string(handle.get_read_error());
  16558. }
  16559. // Either we got an error, or we got less data than expected
  16560. EXPECT_TRUE(got_error || total < 1000)
  16561. << "Expected timeout but got all " << total << " bytes";
  16562. svr.stop();
  16563. t.join();
  16564. }
  16565. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  16566. // Test connection closed detection via BodyReader
  16567. Server svr;
  16568. std::atomic<bool> close_now{false};
  16569. svr.Get("/will-close", [&](const Request &, Response &res) {
  16570. res.set_content_provider(
  16571. 10000, // Large content_length that we won't fully send
  16572. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  16573. if (offset < 100) {
  16574. std::string data(100, 'X');
  16575. sink.write(data.c_str(), data.size());
  16576. return true;
  16577. }
  16578. // Wait for signal then abort
  16579. while (!close_now) {
  16580. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16581. }
  16582. return false; // Abort - server will close connection
  16583. });
  16584. });
  16585. auto port = 8092;
  16586. std::thread t([&]() { svr.listen("localhost", port); });
  16587. svr.wait_until_ready();
  16588. Client cli("localhost", port);
  16589. auto handle = cli.open_stream("GET", "/will-close");
  16590. ASSERT_TRUE(handle.is_valid());
  16591. char buf[256];
  16592. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  16593. EXPECT_GT(n, 0) << "First read should succeed";
  16594. // Signal server to close
  16595. close_now = true;
  16596. // Keep reading until error or EOF
  16597. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  16598. // Keep reading
  16599. }
  16600. // Should get an error since content_length wasn't satisfied
  16601. if (n < 0) {
  16602. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  16603. handle.get_read_error() == Error::Read)
  16604. << "Actual error: " << to_string(handle.get_read_error());
  16605. }
  16606. svr.stop();
  16607. t.join();
  16608. }
  16609. #ifdef CPPHTTPLIB_SSL_ENABLED
  16610. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  16611. // Test that read timeout during SSL streaming is detected
  16612. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16613. svr.Get("/slow-stream", [](const Request &, Response &res) {
  16614. res.set_content_provider(
  16615. 1000, "text/plain",
  16616. [](size_t offset, size_t /*length*/, DataSink &sink) {
  16617. if (offset < 100) {
  16618. std::string data(100, 'A');
  16619. sink.write(data.c_str(), data.size());
  16620. return true;
  16621. }
  16622. std::this_thread::sleep_for(std::chrono::seconds(3));
  16623. std::string data(900, 'B');
  16624. sink.write(data.c_str(), data.size());
  16625. return true;
  16626. });
  16627. });
  16628. auto port = 8093;
  16629. std::thread t([&]() { svr.listen("localhost", port); });
  16630. svr.wait_until_ready();
  16631. SSLClient cli("localhost", port);
  16632. cli.enable_server_certificate_verification(false);
  16633. cli.set_read_timeout(1, 0); // 1 second timeout
  16634. auto handle = cli.open_stream("GET", "/slow-stream");
  16635. ASSERT_TRUE(handle.is_valid());
  16636. char buf[256];
  16637. ssize_t total = 0;
  16638. ssize_t n;
  16639. bool got_error = false;
  16640. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  16641. total += n;
  16642. }
  16643. if (n < 0) {
  16644. got_error = true;
  16645. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  16646. handle.get_read_error() == Error::Read)
  16647. << "Actual error: " << to_string(handle.get_read_error());
  16648. }
  16649. EXPECT_TRUE(got_error || total < 1000)
  16650. << "Expected timeout but got all " << total << " bytes";
  16651. svr.stop();
  16652. t.join();
  16653. }
  16654. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  16655. // Test SSL connection closed detection
  16656. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16657. std::atomic<bool> close_now{false};
  16658. svr.Get("/will-close", [&](const Request &, Response &res) {
  16659. res.set_content_provider(
  16660. 10000, "text/plain",
  16661. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  16662. if (offset < 100) {
  16663. std::string data(100, 'X');
  16664. sink.write(data.c_str(), data.size());
  16665. return true;
  16666. }
  16667. while (!close_now) {
  16668. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16669. }
  16670. return false;
  16671. });
  16672. });
  16673. auto port = 8094;
  16674. std::thread t([&]() { svr.listen("localhost", port); });
  16675. svr.wait_until_ready();
  16676. SSLClient cli("localhost", port);
  16677. cli.enable_server_certificate_verification(false);
  16678. auto handle = cli.open_stream("GET", "/will-close");
  16679. ASSERT_TRUE(handle.is_valid());
  16680. char buf[256];
  16681. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  16682. EXPECT_GT(n, 0);
  16683. // Signal server to close
  16684. close_now = true;
  16685. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  16686. // Keep reading
  16687. }
  16688. if (n < 0) {
  16689. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  16690. handle.get_read_error() == Error::Read)
  16691. << "Actual error: " << to_string(handle.get_read_error());
  16692. }
  16693. svr.stop();
  16694. t.join();
  16695. }
  16696. #endif
  16697. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  16698. using namespace httplib;
  16699. // Create a test file
  16700. const char *fname = "etag_testfile.txt";
  16701. const char *content = "etag-content";
  16702. {
  16703. std::ofstream ofs(fname);
  16704. ofs << content;
  16705. ASSERT_TRUE(ofs.good());
  16706. }
  16707. Server svr;
  16708. svr.set_mount_point("/static", ".");
  16709. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  16710. svr.wait_until_ready();
  16711. Client cli(HOST, PORT);
  16712. // First request: should get 200 with ETag header
  16713. auto res1 = cli.Get("/static/etag_testfile.txt");
  16714. ASSERT_TRUE(res1);
  16715. ASSERT_EQ(200, res1->status);
  16716. ASSERT_TRUE(res1->has_header("ETag"));
  16717. std::string etag = res1->get_header_value("ETag");
  16718. EXPECT_FALSE(etag.empty());
  16719. // Verify ETag format: W/"hex-hex"
  16720. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  16721. EXPECT_EQ('W', etag[0]);
  16722. EXPECT_EQ('/', etag[1]);
  16723. EXPECT_EQ('"', etag[2]);
  16724. EXPECT_EQ('"', etag.back());
  16725. // Exact match: expect 304 Not Modified
  16726. Headers h2 = {{"If-None-Match", etag}};
  16727. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  16728. ASSERT_TRUE(res2);
  16729. EXPECT_EQ(304, res2->status);
  16730. // Wildcard match: expect 304 Not Modified
  16731. Headers h3 = {{"If-None-Match", "*"}};
  16732. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  16733. ASSERT_TRUE(res3);
  16734. EXPECT_EQ(304, res3->status);
  16735. // Non-matching ETag: expect 200
  16736. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  16737. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  16738. ASSERT_TRUE(res4);
  16739. EXPECT_EQ(200, res4->status);
  16740. // Multiple ETags with one matching: expect 304
  16741. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  16742. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  16743. ASSERT_TRUE(res5);
  16744. EXPECT_EQ(304, res5->status);
  16745. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  16746. // that equivalent to the single comma-separated list above, so the match on
  16747. // the second line must still be found.
  16748. Headers h6;
  16749. h6.emplace("If-None-Match", "W/\"other\"");
  16750. h6.emplace("If-None-Match", etag);
  16751. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  16752. ASSERT_TRUE(res6);
  16753. EXPECT_EQ(304, res6->status);
  16754. svr.stop();
  16755. t.join();
  16756. std::remove(fname);
  16757. }
  16758. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  16759. using namespace httplib;
  16760. Server svr;
  16761. svr.set_mount_point("/static", ".");
  16762. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16763. svr.wait_until_ready();
  16764. Client cli(HOST, PORT);
  16765. // Send If-None-Match: * to a non-existent file
  16766. Headers h = {{"If-None-Match", "*"}};
  16767. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  16768. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16769. EXPECT_EQ(404, res->status);
  16770. svr.stop();
  16771. t.join();
  16772. }
  16773. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  16774. using namespace httplib;
  16775. // Create a test file
  16776. const char *fname = "etag_boundary_testfile.txt";
  16777. const char *content = "boundary-test";
  16778. {
  16779. std::ofstream ofs(fname);
  16780. ofs << content;
  16781. ASSERT_TRUE(ofs.good());
  16782. }
  16783. Server svr;
  16784. svr.set_mount_point("/static", ".");
  16785. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  16786. svr.wait_until_ready();
  16787. Client cli(HOST, PORT);
  16788. // Get the actual ETag
  16789. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  16790. ASSERT_TRUE(res1);
  16791. ASSERT_EQ(200, res1->status);
  16792. ASSERT_TRUE(res1->has_header("ETag"));
  16793. std::string etag = res1->get_header_value("ETag");
  16794. // Test 1: Very long ETag value (longer than actual ETag)
  16795. // Should NOT match and return 200 (not trigger out-of-bounds read)
  16796. Headers h1 = {{"If-None-Match", "W/"
  16797. "\"very-long-etag-value-that-is-much-longer-"
  16798. "than-the-actual-etag-value\""}};
  16799. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  16800. ASSERT_TRUE(res2);
  16801. EXPECT_EQ(200, res2->status); // Should not match
  16802. // Test 2: Long string followed by wildcard
  16803. // Should match on "*" and return 304 (without out-of-bounds read on the long
  16804. // string)
  16805. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  16806. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  16807. ASSERT_TRUE(res3);
  16808. EXPECT_EQ(304, res3->status); // Should match on "*"
  16809. // Test 3: Wildcard followed by long string
  16810. // Should match on "*" immediately and return 304
  16811. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  16812. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  16813. ASSERT_TRUE(res4);
  16814. EXPECT_EQ(304, res4->status); // Should match on "*"
  16815. // Test 4: Multiple long non-matching values
  16816. // Should NOT match and return 200 (test that all comparisons are safe)
  16817. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  16818. "W/\"second-long-non-matching-value\", "
  16819. "W/\"third-long-non-matching-value\""}};
  16820. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  16821. ASSERT_TRUE(res5);
  16822. EXPECT_EQ(200, res5->status); // Should not match
  16823. // Test 5: Single character that is not "*" (edge case)
  16824. Headers h5 = {{"If-None-Match", "X"}};
  16825. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  16826. ASSERT_TRUE(res6);
  16827. EXPECT_EQ(200, res6->status); // Should not match
  16828. svr.stop();
  16829. t.join();
  16830. std::remove(fname);
  16831. }
  16832. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  16833. using namespace httplib;
  16834. // Create a test file
  16835. const char *fname = "ims_testfile.txt";
  16836. const char *content = "if-modified-since-test";
  16837. {
  16838. std::ofstream ofs(fname);
  16839. ofs << content;
  16840. ASSERT_TRUE(ofs.good());
  16841. }
  16842. Server svr;
  16843. svr.set_mount_point("/static", ".");
  16844. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16845. svr.wait_until_ready();
  16846. Client cli(HOST, PORT);
  16847. // First request: should get 200 with Last-Modified header
  16848. auto res1 = cli.Get("/static/ims_testfile.txt");
  16849. ASSERT_TRUE(res1);
  16850. ASSERT_EQ(200, res1->status);
  16851. ASSERT_TRUE(res1->has_header("Last-Modified"));
  16852. std::string last_modified = res1->get_header_value("Last-Modified");
  16853. EXPECT_FALSE(last_modified.empty());
  16854. // If-Modified-Since with same time: expect 304
  16855. Headers h2 = {{"If-Modified-Since", last_modified}};
  16856. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  16857. ASSERT_TRUE(res2);
  16858. EXPECT_EQ(304, res2->status);
  16859. // If-Modified-Since with future time: expect 304
  16860. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  16861. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  16862. ASSERT_TRUE(res3);
  16863. EXPECT_EQ(304, res3->status);
  16864. // If-Modified-Since with past time: expect 200
  16865. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  16866. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  16867. ASSERT_TRUE(res4);
  16868. EXPECT_EQ(200, res4->status);
  16869. // If-None-Match takes precedence over If-Modified-Since
  16870. // (send matching ETag with old If-Modified-Since -> should still be 304)
  16871. ASSERT_TRUE(res1->has_header("ETag"));
  16872. std::string etag = res1->get_header_value("ETag");
  16873. Headers h5 = {{"If-None-Match", etag},
  16874. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  16875. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  16876. ASSERT_TRUE(res5);
  16877. EXPECT_EQ(304, res5->status);
  16878. svr.stop();
  16879. t.join();
  16880. std::remove(fname);
  16881. }
  16882. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  16883. using namespace httplib;
  16884. Server svr;
  16885. // Endpoint that returns compressible content
  16886. svr.Get("/compressible", [](const Request &, Response &res) {
  16887. // Return a large enough body to trigger compression
  16888. std::string body(1000, 'a');
  16889. res.set_content(body, "text/plain");
  16890. });
  16891. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16892. svr.wait_until_ready();
  16893. Client cli(HOST, PORT);
  16894. // Request with gzip support: should get Vary header when compressed
  16895. cli.set_compress(true);
  16896. auto res1 = cli.Get("/compressible");
  16897. ASSERT_TRUE(res1);
  16898. EXPECT_EQ(200, res1->status);
  16899. // If Content-Encoding is set, Vary should also be set
  16900. if (res1->has_header("Content-Encoding")) {
  16901. EXPECT_TRUE(res1->has_header("Vary"));
  16902. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  16903. }
  16904. // Request without Accept-Encoding header: should not have compression
  16905. Headers h_no_compress;
  16906. auto res2 = cli.Get("/compressible", h_no_compress);
  16907. ASSERT_TRUE(res2);
  16908. EXPECT_EQ(200, res2->status);
  16909. // Verify Vary header is present when compression is applied
  16910. // (the exact behavior depends on server configuration)
  16911. svr.stop();
  16912. t.join();
  16913. }
  16914. TEST(ETagTest, IfRangeWithETag) {
  16915. using namespace httplib;
  16916. // Create a test file with known content
  16917. const char *fname = "if_range_testfile.txt";
  16918. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  16919. {
  16920. std::ofstream ofs(fname);
  16921. ofs << content;
  16922. ASSERT_TRUE(ofs.good());
  16923. }
  16924. Server svr;
  16925. svr.set_mount_point("/static", ".");
  16926. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16927. svr.wait_until_ready();
  16928. Client cli(HOST, PORT);
  16929. // First request: get ETag
  16930. auto res1 = cli.Get("/static/if_range_testfile.txt");
  16931. ASSERT_TRUE(res1);
  16932. ASSERT_EQ(200, res1->status);
  16933. ASSERT_TRUE(res1->has_header("ETag"));
  16934. std::string etag = res1->get_header_value("ETag");
  16935. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  16936. // Since our server generates weak ETags (W/"..."), If-Range with our
  16937. // ETag should NOT result in partial content - it should return full content.
  16938. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  16939. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  16940. ASSERT_TRUE(res2);
  16941. // Weak ETag in If-Range -> full content (200), not partial (206)
  16942. EXPECT_EQ(200, res2->status);
  16943. EXPECT_EQ(content, res2->body);
  16944. EXPECT_FALSE(res2->has_header("Content-Range"));
  16945. // Range request with non-matching If-Range (ETag): should get 200 (full
  16946. // content)
  16947. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  16948. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  16949. ASSERT_TRUE(res3);
  16950. EXPECT_EQ(200, res3->status);
  16951. EXPECT_EQ(content, res3->body);
  16952. EXPECT_FALSE(res3->has_header("Content-Range"));
  16953. // Range request with strong ETag (hypothetical - our server doesn't generate
  16954. // strong ETags, but if client sends a strong ETag that doesn't match, it
  16955. // should return full content)
  16956. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  16957. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  16958. ASSERT_TRUE(res4);
  16959. EXPECT_EQ(200, res4->status);
  16960. EXPECT_EQ(content, res4->body);
  16961. EXPECT_FALSE(res4->has_header("Content-Range"));
  16962. svr.stop();
  16963. t.join();
  16964. std::remove(fname);
  16965. }
  16966. TEST(ETagTest, IfRangeWithDate) {
  16967. using namespace httplib;
  16968. // Create a test file
  16969. const char *fname = "if_range_date_testfile.txt";
  16970. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  16971. {
  16972. std::ofstream ofs(fname);
  16973. ofs << content;
  16974. ASSERT_TRUE(ofs.good());
  16975. }
  16976. Server svr;
  16977. svr.set_mount_point("/static", ".");
  16978. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16979. svr.wait_until_ready();
  16980. Client cli(HOST, PORT);
  16981. // First request: get Last-Modified
  16982. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  16983. ASSERT_TRUE(res1);
  16984. ASSERT_EQ(200, res1->status);
  16985. ASSERT_TRUE(res1->has_header("Last-Modified"));
  16986. std::string last_modified = res1->get_header_value("Last-Modified");
  16987. // Range request with matching If-Range (date): should get 206
  16988. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  16989. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  16990. ASSERT_TRUE(res2);
  16991. EXPECT_EQ(206, res2->status);
  16992. EXPECT_EQ("FGHIJ", res2->body);
  16993. // Range request with old If-Range date: should get 200 (full content)
  16994. Headers h3 = {{"Range", "bytes=5-9"},
  16995. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  16996. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  16997. ASSERT_TRUE(res3);
  16998. EXPECT_EQ(200, res3->status);
  16999. EXPECT_EQ(content, res3->body);
  17000. // Range request with future If-Range date: should get 206
  17001. Headers h4 = {{"Range", "bytes=0-4"},
  17002. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  17003. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  17004. ASSERT_TRUE(res4);
  17005. EXPECT_EQ(206, res4->status);
  17006. EXPECT_EQ("ABCDE", res4->body);
  17007. svr.stop();
  17008. t.join();
  17009. std::remove(fname);
  17010. }
  17011. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  17012. using namespace httplib;
  17013. const char *fname = "etag_malformed.txt";
  17014. const char *content = "malformed-etag";
  17015. {
  17016. std::ofstream ofs(fname);
  17017. ofs << content;
  17018. ASSERT_TRUE(ofs.good());
  17019. }
  17020. Server svr;
  17021. svr.set_mount_point("/static", ".");
  17022. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17023. svr.wait_until_ready();
  17024. Client cli(HOST, PORT);
  17025. // baseline: should get 200 and an ETag
  17026. auto res1 = cli.Get("/static/etag_malformed.txt");
  17027. ASSERT_TRUE(res1);
  17028. ASSERT_EQ(200, res1->status);
  17029. ASSERT_TRUE(res1->has_header("ETag"));
  17030. // Malformed ETag value (missing quotes) should be treated as non-matching
  17031. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  17032. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  17033. ASSERT_TRUE(res_bad);
  17034. EXPECT_EQ(200, res_bad->status);
  17035. // Whitespace-only header value should be considered invalid / non-matching
  17036. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  17037. "Host: localhost\r\n"
  17038. "If-None-Match: \r\n"
  17039. "Connection: close\r\n"
  17040. "\r\n";
  17041. std::string out;
  17042. ASSERT_TRUE(send_request(5, raw_req, &out));
  17043. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17044. svr.stop();
  17045. t.join();
  17046. std::remove(fname);
  17047. }
  17048. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  17049. using namespace httplib;
  17050. const char *fname = "ims_invalid_format.txt";
  17051. const char *content = "ims-bad-format";
  17052. {
  17053. std::ofstream ofs(fname);
  17054. ofs << content;
  17055. ASSERT_TRUE(ofs.good());
  17056. }
  17057. Server svr;
  17058. svr.set_mount_point("/static", ".");
  17059. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17060. svr.wait_until_ready();
  17061. Client cli(HOST, PORT);
  17062. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  17063. ASSERT_TRUE(res1);
  17064. ASSERT_EQ(200, res1->status);
  17065. ASSERT_TRUE(res1->has_header("Last-Modified"));
  17066. // If-Modified-Since with invalid format should not result in 304
  17067. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  17068. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  17069. ASSERT_TRUE(res_bad);
  17070. EXPECT_EQ(200, res_bad->status);
  17071. // If-Range with invalid date format should be treated as mismatch -> full
  17072. // content (200)
  17073. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  17074. {"If-Range", "invalid-date"}};
  17075. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  17076. ASSERT_TRUE(res_ifrange);
  17077. EXPECT_EQ(200, res_ifrange->status);
  17078. svr.stop();
  17079. t.join();
  17080. std::remove(fname);
  17081. }
  17082. TEST(ETagTest, IfRangeWithMalformedETag) {
  17083. using namespace httplib;
  17084. const char *fname = "ifrange_malformed.txt";
  17085. const std::string content = "0123456789";
  17086. {
  17087. std::ofstream ofs(fname);
  17088. ofs << content;
  17089. ASSERT_TRUE(ofs.good());
  17090. }
  17091. Server svr;
  17092. svr.set_mount_point("/static", ".");
  17093. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17094. svr.wait_until_ready();
  17095. Client cli(HOST, PORT);
  17096. // First request: get ETag
  17097. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  17098. ASSERT_TRUE(res1);
  17099. ASSERT_EQ(200, res1->status);
  17100. ASSERT_TRUE(res1->has_header("ETag"));
  17101. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  17102. // full content (200)
  17103. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  17104. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  17105. ASSERT_TRUE(res2);
  17106. EXPECT_EQ(200, res2->status);
  17107. EXPECT_EQ(content, res2->body);
  17108. svr.stop();
  17109. t.join();
  17110. std::remove(fname);
  17111. }
  17112. TEST(ETagTest, ExtremeLargeDateValues) {
  17113. using namespace httplib;
  17114. const char *fname = "ims_extreme_date.txt";
  17115. const char *content = "ims-extreme-date";
  17116. {
  17117. std::ofstream ofs(fname);
  17118. ofs << content;
  17119. ASSERT_TRUE(ofs.good());
  17120. }
  17121. Server svr;
  17122. svr.set_mount_point("/static", ".");
  17123. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17124. svr.wait_until_ready();
  17125. Client cli(HOST, PORT);
  17126. auto res1 = cli.Get(std::string("/static/") + fname);
  17127. ASSERT_TRUE(res1);
  17128. ASSERT_EQ(200, res1->status);
  17129. ASSERT_TRUE(res1->has_header("Last-Modified"));
  17130. // Extremely large year that may overflow date parsing routines.
  17131. Headers h_large_date = {
  17132. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  17133. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  17134. ASSERT_TRUE(res_bad);
  17135. // Expect server to treat this as invalid/mismatch and return full content
  17136. EXPECT_EQ(200, res_bad->status);
  17137. // If-Range with extremely large date should be treated as mismatch -> full
  17138. // content (200)
  17139. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  17140. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  17141. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  17142. ASSERT_TRUE(res_ifrange);
  17143. EXPECT_EQ(200, res_ifrange->status);
  17144. svr.stop();
  17145. t.join();
  17146. std::remove(fname);
  17147. }
  17148. TEST(ETagTest, NegativeFileModificationTime) {
  17149. using namespace httplib;
  17150. const char *fname = "ims_negative_mtime.txt";
  17151. const std::string content = "negative-mtime";
  17152. {
  17153. std::ofstream ofs(fname);
  17154. ofs << content;
  17155. ASSERT_TRUE(ofs.good());
  17156. }
  17157. // Try to set file mtime to a negative value. This may fail on some
  17158. // platforms/filesystems; if it fails, the test will still verify server
  17159. // behaves safely by performing a regular conditional request.
  17160. #if defined(__APPLE__) || defined(__linux__)
  17161. bool set_negative = false;
  17162. do {
  17163. struct timeval times[2];
  17164. // access time: now
  17165. times[0].tv_sec = time(nullptr);
  17166. times[0].tv_usec = 0;
  17167. // modification time: negative (e.g., -1)
  17168. times[1].tv_sec = -1;
  17169. times[1].tv_usec = 0;
  17170. if (utimes(fname, times) == 0) { set_negative = true; }
  17171. } while (0);
  17172. #else
  17173. bool set_negative = false;
  17174. #endif
  17175. Server svr;
  17176. svr.set_mount_point("/static", ".");
  17177. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17178. svr.wait_until_ready();
  17179. Client cli(HOST, PORT);
  17180. auto res1 = cli.Get(std::string("/static/") + fname);
  17181. ASSERT_TRUE(res1);
  17182. ASSERT_EQ(200, res1->status);
  17183. bool has_last_modified = res1->has_header("Last-Modified");
  17184. std::string last_modified;
  17185. if (has_last_modified) {
  17186. last_modified = res1->get_header_value("Last-Modified");
  17187. }
  17188. if (set_negative) {
  17189. // If we successfully set a negative mtime, ensure server returns a
  17190. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  17191. // with an old date and ensure server handles it without crash.
  17192. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  17193. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  17194. ASSERT_TRUE(res2);
  17195. // Behavior may vary; at minimum ensure server responds (200 or 304).
  17196. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  17197. } else {
  17198. // Could not set negative mtime on this platform; fall back to verifying
  17199. // that normal invalid/malformed dates are treated safely (non-304).
  17200. Headers h_bad_date = {
  17201. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  17202. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  17203. ASSERT_TRUE(res_bad);
  17204. EXPECT_EQ(200, res_bad->status);
  17205. }
  17206. svr.stop();
  17207. t.join();
  17208. std::remove(fname);
  17209. }
  17210. //==============================================================================
  17211. // SSE Parsing Tests
  17212. //==============================================================================
  17213. class SSEParsingTest : public ::testing::Test {
  17214. protected:
  17215. // Test helper that mimics SSE parsing behavior
  17216. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  17217. int &retry_ms) {
  17218. // Blank line signals end of event
  17219. if (line.empty() || line == "\r") { return true; }
  17220. // Lines starting with ':' are comments (ignored)
  17221. if (!line.empty() && line[0] == ':') { return false; }
  17222. // Find the colon separator
  17223. auto colon_pos = line.find(':');
  17224. if (colon_pos == std::string::npos) {
  17225. // Line with no colon is treated as field name with empty value
  17226. return false;
  17227. }
  17228. std::string field = line.substr(0, colon_pos);
  17229. std::string value;
  17230. // Value starts after colon, skip optional single space
  17231. if (colon_pos + 1 < line.size()) {
  17232. size_t value_start = colon_pos + 1;
  17233. if (line[value_start] == ' ') { value_start++; }
  17234. value = line.substr(value_start);
  17235. // Remove trailing \r if present
  17236. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  17237. }
  17238. // Handle known fields
  17239. if (field == "event") {
  17240. msg.event = value;
  17241. } else if (field == "data") {
  17242. // Multiple data lines are concatenated with newlines
  17243. if (!msg.data.empty()) { msg.data += "\n"; }
  17244. msg.data += value;
  17245. } else if (field == "id") {
  17246. // Empty id is valid (clears the last event ID)
  17247. msg.id = value;
  17248. } else if (field == "retry") {
  17249. // Parse retry interval in milliseconds
  17250. {
  17251. int v = 0;
  17252. auto res =
  17253. detail::from_chars(value.data(), value.data() + value.size(), v);
  17254. if (res.ec == std::errc{}) { retry_ms = v; }
  17255. }
  17256. }
  17257. // Unknown fields are ignored per SSE spec
  17258. return false;
  17259. }
  17260. };
  17261. // Test: Single-line data
  17262. TEST_F(SSEParsingTest, SingleLineData) {
  17263. sse::SSEMessage msg;
  17264. int retry_ms = 3000;
  17265. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  17266. EXPECT_EQ(msg.data, "hello");
  17267. EXPECT_EQ(msg.event, "message");
  17268. // Blank line ends event
  17269. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  17270. }
  17271. // Test: Multi-line data
  17272. TEST_F(SSEParsingTest, MultiLineData) {
  17273. sse::SSEMessage msg;
  17274. int retry_ms = 3000;
  17275. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  17276. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  17277. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  17278. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  17279. }
  17280. // Test: Custom event types
  17281. TEST_F(SSEParsingTest, CustomEventType) {
  17282. sse::SSEMessage msg;
  17283. int retry_ms = 3000;
  17284. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  17285. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  17286. EXPECT_EQ(msg.event, "update");
  17287. EXPECT_EQ(msg.data, "payload");
  17288. }
  17289. // Test: Event ID handling
  17290. TEST_F(SSEParsingTest, EventIdHandling) {
  17291. sse::SSEMessage msg;
  17292. int retry_ms = 3000;
  17293. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  17294. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  17295. EXPECT_EQ(msg.id, "12345");
  17296. }
  17297. // Test: Empty event ID (clears last event ID)
  17298. TEST_F(SSEParsingTest, EmptyEventId) {
  17299. sse::SSEMessage msg;
  17300. msg.id = "previous";
  17301. int retry_ms = 3000;
  17302. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  17303. EXPECT_EQ(msg.id, "");
  17304. }
  17305. // Test: Retry field parsing
  17306. TEST_F(SSEParsingTest, RetryFieldParsing) {
  17307. sse::SSEMessage msg;
  17308. int retry_ms = 3000;
  17309. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  17310. EXPECT_EQ(retry_ms, 5000);
  17311. }
  17312. // Test: Invalid retry value
  17313. TEST_F(SSEParsingTest, InvalidRetryValue) {
  17314. sse::SSEMessage msg;
  17315. int retry_ms = 3000;
  17316. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  17317. EXPECT_EQ(retry_ms, 3000); // Unchanged
  17318. }
  17319. // Test: Comments (lines starting with :)
  17320. TEST_F(SSEParsingTest, CommentsIgnored) {
  17321. sse::SSEMessage msg;
  17322. int retry_ms = 3000;
  17323. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  17324. EXPECT_EQ(msg.data, "");
  17325. EXPECT_EQ(msg.event, "message");
  17326. }
  17327. // Test: Colon in value
  17328. TEST_F(SSEParsingTest, ColonInValue) {
  17329. sse::SSEMessage msg;
  17330. int retry_ms = 3000;
  17331. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  17332. EXPECT_EQ(msg.data, "hello:world:test");
  17333. }
  17334. // Test: Line with no colon (field name only)
  17335. TEST_F(SSEParsingTest, FieldNameOnly) {
  17336. sse::SSEMessage msg;
  17337. int retry_ms = 3000;
  17338. // According to SSE spec, this is treated as field name with empty value
  17339. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  17340. // Since we don't recognize "data" without colon, data should be empty
  17341. EXPECT_EQ(msg.data, "");
  17342. }
  17343. // Test: Trailing \r handling
  17344. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  17345. sse::SSEMessage msg;
  17346. int retry_ms = 3000;
  17347. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  17348. EXPECT_EQ(msg.data, "hello");
  17349. }
  17350. // Test: Unknown fields ignored
  17351. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  17352. sse::SSEMessage msg;
  17353. int retry_ms = 3000;
  17354. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  17355. EXPECT_EQ(msg.data, "");
  17356. EXPECT_EQ(msg.event, "message");
  17357. }
  17358. // Test: Space after colon is optional
  17359. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  17360. sse::SSEMessage msg1, msg2;
  17361. int retry_ms = 3000;
  17362. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  17363. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  17364. EXPECT_EQ(msg1.data, "hello");
  17365. EXPECT_EQ(msg2.data, "hello");
  17366. }
  17367. // Test: SSEMessage clear
  17368. TEST_F(SSEParsingTest, MessageClear) {
  17369. sse::SSEMessage msg;
  17370. msg.event = "custom";
  17371. msg.data = "some data";
  17372. msg.id = "123";
  17373. msg.clear();
  17374. EXPECT_EQ(msg.event, "message");
  17375. EXPECT_EQ(msg.data, "");
  17376. EXPECT_EQ(msg.id, "");
  17377. }
  17378. // Test: Complete event parsing
  17379. TEST_F(SSEParsingTest, CompleteEventParsing) {
  17380. sse::SSEMessage msg;
  17381. int retry_ms = 3000;
  17382. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  17383. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  17384. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  17385. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  17386. // Blank line ends event
  17387. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  17388. EXPECT_EQ(msg.event, "notification");
  17389. EXPECT_EQ(msg.id, "evt-42");
  17390. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  17391. EXPECT_EQ(retry_ms, 1000);
  17392. }
  17393. //==============================================================================
  17394. // Integration Tests with Server
  17395. //==============================================================================
  17396. class SSEIntegrationTest : public ::testing::Test {
  17397. protected:
  17398. void SetUp() override {
  17399. stop_server_.store(false);
  17400. events_.clear();
  17401. server_ = httplib::detail::make_unique<Server>();
  17402. setup_server();
  17403. start_server();
  17404. }
  17405. void TearDown() override {
  17406. stop_server_.store(true);
  17407. event_cv_.notify_all();
  17408. server_->stop();
  17409. if (server_thread_.joinable()) { server_thread_.join(); }
  17410. }
  17411. void setup_server() {
  17412. // Simple SSE endpoint
  17413. server_->Get("/events", [this](const Request &req, Response &res) {
  17414. auto last_id = req.get_header_value("Last-Event-ID");
  17415. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  17416. res.set_chunked_content_provider(
  17417. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  17418. std::unique_lock<std::mutex> lock(event_mutex_);
  17419. if (event_cv_.wait_for(
  17420. lock, std::chrono::milliseconds(200), [this] {
  17421. return !events_.empty() || stop_server_.load();
  17422. })) {
  17423. if (stop_server_.load()) { return false; }
  17424. if (!events_.empty()) {
  17425. std::string event = events_.front();
  17426. events_.erase(events_.begin());
  17427. sink.write(event.data(), event.size());
  17428. return true;
  17429. }
  17430. }
  17431. return !stop_server_.load();
  17432. });
  17433. });
  17434. // Endpoint that returns error
  17435. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  17436. res.status = 500;
  17437. res.set_content("Internal Server Error", "text/plain");
  17438. });
  17439. // Endpoint for custom event types
  17440. server_->Get("/custom-events", [](const Request &, Response &res) {
  17441. res.set_chunked_content_provider(
  17442. "text/event-stream", [](size_t offset, DataSink &sink) {
  17443. if (offset == 0) {
  17444. std::string event = "event: update\ndata: updated\n\n"
  17445. "event: delete\ndata: deleted\n\n";
  17446. sink.write(event.data(), event.size());
  17447. }
  17448. return false; // End stream after sending
  17449. });
  17450. });
  17451. }
  17452. void start_server() {
  17453. port_ = server_->bind_to_any_port(HOST);
  17454. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  17455. // Wait for server to start
  17456. while (!server_->is_running()) {
  17457. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  17458. }
  17459. }
  17460. int get_port() const { return port_; }
  17461. void send_event(const std::string &event) {
  17462. std::lock_guard<std::mutex> lock(event_mutex_);
  17463. events_.push_back(event);
  17464. event_cv_.notify_all();
  17465. }
  17466. std::unique_ptr<Server> server_;
  17467. std::thread server_thread_;
  17468. std::mutex event_mutex_;
  17469. std::condition_variable event_cv_;
  17470. std::vector<std::string> events_;
  17471. std::atomic<bool> stop_server_{false};
  17472. std::string last_received_event_id_;
  17473. int port_ = 0;
  17474. };
  17475. // Test: Successful connection and on_open callback
  17476. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  17477. // Add a simple endpoint that sends one event and closes
  17478. server_->Get("/simple-event", [](const Request &, Response &res) {
  17479. res.set_chunked_content_provider(
  17480. "text/event-stream", [](size_t offset, DataSink &sink) {
  17481. if (offset == 0) {
  17482. std::string event = "data: hello\n\n";
  17483. sink.write(event.data(), event.size());
  17484. }
  17485. return false; // Close stream after sending
  17486. });
  17487. });
  17488. Client client("localhost", get_port());
  17489. sse::SSEClient sse(client, "/simple-event");
  17490. std::atomic<bool> open_called{false};
  17491. std::atomic<bool> message_received{false};
  17492. sse.on_open([&open_called]() { open_called.store(true); });
  17493. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  17494. if (msg.data == "hello") { message_received.store(true); }
  17495. });
  17496. sse.set_reconnect_interval(100);
  17497. sse.set_max_reconnect_attempts(1);
  17498. // Start async
  17499. sse.start_async();
  17500. // Wait for message to be processed
  17501. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  17502. sse.stop();
  17503. EXPECT_TRUE(open_called.load());
  17504. EXPECT_TRUE(message_received.load());
  17505. }
  17506. // Test: on_message callback
  17507. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  17508. // Endpoint that sends multiple events then closes
  17509. server_->Get("/multi-event", [](const Request &, Response &res) {
  17510. res.set_chunked_content_provider(
  17511. "text/event-stream", [](size_t offset, DataSink &sink) {
  17512. if (offset == 0) {
  17513. std::string events = "data: message1\n\ndata: message2\n\n";
  17514. sink.write(events.data(), events.size());
  17515. }
  17516. return false;
  17517. });
  17518. });
  17519. Client client("localhost", get_port());
  17520. sse::SSEClient sse(client, "/multi-event");
  17521. std::vector<std::string> received_messages;
  17522. std::mutex messages_mutex;
  17523. sse.on_message([&](const sse::SSEMessage &msg) {
  17524. std::lock_guard<std::mutex> lock(messages_mutex);
  17525. received_messages.push_back(msg.data);
  17526. });
  17527. sse.set_reconnect_interval(100);
  17528. sse.set_max_reconnect_attempts(1);
  17529. sse.start_async();
  17530. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  17531. sse.stop();
  17532. std::lock_guard<std::mutex> lock(messages_mutex);
  17533. EXPECT_GE(received_messages.size(), 2u);
  17534. if (received_messages.size() >= 2) {
  17535. EXPECT_EQ(received_messages[0], "message1");
  17536. EXPECT_EQ(received_messages[1], "message2");
  17537. }
  17538. }
  17539. // Test: on_event for specific types
  17540. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  17541. Client client("localhost", get_port());
  17542. sse::SSEClient sse(client, "/custom-events");
  17543. std::atomic<bool> update_received{false};
  17544. std::atomic<bool> delete_received{false};
  17545. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  17546. if (msg.data == "updated") { update_received.store(true); }
  17547. });
  17548. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  17549. if (msg.data == "deleted") { delete_received.store(true); }
  17550. });
  17551. sse.set_max_reconnect_attempts(1);
  17552. sse.start_async();
  17553. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  17554. sse.stop();
  17555. EXPECT_TRUE(update_received.load());
  17556. EXPECT_TRUE(delete_received.load());
  17557. }
  17558. // Test: on_error callback on connection failure
  17559. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  17560. // Connect to a non-existent port
  17561. Client client("localhost", 59999);
  17562. sse::SSEClient sse(client, "/events");
  17563. std::atomic<bool> error_called{false};
  17564. Error received_error = Error::Success;
  17565. sse.on_error([&](Error err) {
  17566. error_called.store(true);
  17567. received_error = err;
  17568. });
  17569. sse.set_reconnect_interval(50);
  17570. sse.set_max_reconnect_attempts(1);
  17571. sse.start_async();
  17572. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  17573. sse.stop();
  17574. EXPECT_TRUE(error_called.load());
  17575. EXPECT_NE(received_error, Error::Success);
  17576. }
  17577. // Test: Last-Event-ID header sent on reconnect
  17578. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  17579. // Endpoint that sends event with ID
  17580. server_->Get("/event-with-id", [](const Request &, Response &res) {
  17581. res.set_chunked_content_provider(
  17582. "text/event-stream", [](size_t offset, DataSink &sink) {
  17583. if (offset == 0) {
  17584. std::string event = "id: evt-123\ndata: test\n\n";
  17585. sink.write(event.data(), event.size());
  17586. }
  17587. return false;
  17588. });
  17589. });
  17590. Client client("localhost", get_port());
  17591. sse::SSEClient sse(client, "/event-with-id");
  17592. std::atomic<bool> id_received{false};
  17593. sse.on_message([&](const sse::SSEMessage &msg) {
  17594. if (!msg.id.empty()) { id_received.store(true); }
  17595. });
  17596. sse.set_reconnect_interval(100);
  17597. sse.set_max_reconnect_attempts(1);
  17598. sse.start_async();
  17599. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  17600. sse.stop();
  17601. EXPECT_TRUE(id_received.load());
  17602. EXPECT_EQ(sse.last_event_id(), "evt-123");
  17603. }
  17604. // Test: Manual stop
  17605. TEST_F(SSEIntegrationTest, ManualStop) {
  17606. // Endpoint that sends one event and stays open briefly
  17607. std::atomic<bool> handler_running{true};
  17608. server_->Get("/stay-open", [&handler_running](const Request &,
  17609. Response &res) {
  17610. res.set_chunked_content_provider(
  17611. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  17612. if (offset == 0) {
  17613. std::string event = "data: connected\n\n";
  17614. sink.write(event.data(), event.size());
  17615. }
  17616. // Keep connection open while handler_running is true
  17617. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  17618. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  17619. }
  17620. return false;
  17621. });
  17622. });
  17623. Client client("localhost", get_port());
  17624. sse::SSEClient sse(client, "/stay-open");
  17625. std::atomic<bool> connected{false};
  17626. sse.on_open([&connected]() { connected.store(true); });
  17627. sse.set_reconnect_interval(100);
  17628. sse.set_max_reconnect_attempts(1);
  17629. sse.start_async();
  17630. // Wait for connection to establish
  17631. for (int i = 0; i < 20 && !connected.load(); ++i) {
  17632. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  17633. }
  17634. EXPECT_TRUE(connected.load());
  17635. EXPECT_TRUE(sse.is_connected());
  17636. // Signal handler to stop
  17637. handler_running.store(false);
  17638. // Stop SSE client
  17639. sse.stop();
  17640. EXPECT_FALSE(sse.is_connected());
  17641. }
  17642. // Test: SSEClient with custom headers
  17643. TEST_F(SSEIntegrationTest, CustomHeaders) {
  17644. // Setup a server endpoint that checks for custom header
  17645. std::atomic<bool> header_received{false};
  17646. server_->Get("/header-check", [&](const Request &req, Response &res) {
  17647. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  17648. header_received.store(true);
  17649. }
  17650. res.set_chunked_content_provider("text/event-stream",
  17651. [](size_t, DataSink &) { return false; });
  17652. });
  17653. Client client("localhost", get_port());
  17654. Headers headers = {{"X-Custom-Header", "custom-value"}};
  17655. sse::SSEClient sse(client, "/header-check", headers);
  17656. sse.set_max_reconnect_attempts(1);
  17657. sse.start_async();
  17658. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  17659. sse.stop();
  17660. EXPECT_TRUE(header_received.load());
  17661. }
  17662. // Test: Reconnect interval configuration
  17663. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  17664. Client client("localhost", get_port());
  17665. sse::SSEClient sse(client, "/events");
  17666. auto &result = sse.set_reconnect_interval(500);
  17667. // Builder pattern should return reference to self
  17668. EXPECT_EQ(&result, &sse);
  17669. }
  17670. // Test: Max reconnect attempts
  17671. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  17672. // Connect to non-existent port to force reconnects
  17673. Client client("localhost", 59998);
  17674. sse::SSEClient sse(client, "/events");
  17675. std::atomic<int> error_count{0};
  17676. sse.on_error([&](Error) { error_count.fetch_add(1); });
  17677. sse.set_reconnect_interval(50);
  17678. sse.set_max_reconnect_attempts(2);
  17679. auto start = std::chrono::steady_clock::now();
  17680. sse.start(); // Blocking call
  17681. auto end = std::chrono::steady_clock::now();
  17682. // Should have stopped after 2 failed attempts
  17683. EXPECT_GE(error_count.load(), 2);
  17684. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  17685. auto duration =
  17686. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  17687. #ifdef _WIN32
  17688. // Windows is much slower for socket connection failures
  17689. EXPECT_LT(duration.count(), 7000);
  17690. #else
  17691. EXPECT_LT(duration.count(), 1000);
  17692. #endif
  17693. }
  17694. // Test: Multi-line data in integration
  17695. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  17696. // Endpoint with multi-line data
  17697. server_->Get("/multiline-data", [](const Request &, Response &res) {
  17698. res.set_chunked_content_provider(
  17699. "text/event-stream", [](size_t offset, DataSink &sink) {
  17700. if (offset == 0) {
  17701. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  17702. sink.write(event.data(), event.size());
  17703. }
  17704. return false;
  17705. });
  17706. });
  17707. Client client("localhost", get_port());
  17708. sse::SSEClient sse(client, "/multiline-data");
  17709. std::string received_data;
  17710. std::mutex data_mutex;
  17711. sse.on_message([&](const sse::SSEMessage &msg) {
  17712. std::lock_guard<std::mutex> lock(data_mutex);
  17713. received_data = msg.data;
  17714. });
  17715. sse.set_reconnect_interval(100);
  17716. sse.set_max_reconnect_attempts(1);
  17717. sse.start_async();
  17718. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  17719. sse.stop();
  17720. std::lock_guard<std::mutex> lock(data_mutex);
  17721. EXPECT_EQ(received_data, "line1\nline2\nline3");
  17722. }
  17723. // Test: Auto-reconnect after server disconnection
  17724. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  17725. std::atomic<int> connection_count{0};
  17726. std::atomic<int> message_count{0};
  17727. // Endpoint that sends one event and closes, forcing reconnect
  17728. server_->Get("/reconnect-test",
  17729. [&connection_count](const Request &, Response &res) {
  17730. connection_count.fetch_add(1);
  17731. res.set_chunked_content_provider(
  17732. "text/event-stream", [](size_t offset, DataSink &sink) {
  17733. if (offset == 0) {
  17734. std::string event = "data: hello\n\n";
  17735. sink.write(event.data(), event.size());
  17736. }
  17737. return false; // Close connection after sending
  17738. });
  17739. });
  17740. Client client("localhost", get_port());
  17741. sse::SSEClient sse(client, "/reconnect-test");
  17742. sse.on_message([&message_count](const sse::SSEMessage &) {
  17743. message_count.fetch_add(1);
  17744. });
  17745. sse.set_reconnect_interval(100);
  17746. sse.set_max_reconnect_attempts(3);
  17747. sse.start_async();
  17748. // Wait long enough for multiple reconnects
  17749. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  17750. sse.stop();
  17751. // Should have connected multiple times (initial + reconnects)
  17752. EXPECT_GE(connection_count.load(), 2);
  17753. // Should have received messages from multiple connections
  17754. EXPECT_GE(message_count.load(), 2);
  17755. }
  17756. // Test: Last-Event-ID sent on reconnect
  17757. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  17758. std::atomic<int> connection_count{0};
  17759. std::vector<std::string> received_last_event_ids;
  17760. std::mutex id_mutex;
  17761. // Endpoint that checks Last-Event-ID header and sends event with ID
  17762. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  17763. int conn = connection_count.fetch_add(1);
  17764. // Capture the Last-Event-ID header from each connection
  17765. {
  17766. std::lock_guard<std::mutex> lock(id_mutex);
  17767. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  17768. }
  17769. res.set_chunked_content_provider(
  17770. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  17771. if (offset == 0) {
  17772. std::string event =
  17773. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  17774. sink.write(event.data(), event.size());
  17775. }
  17776. return false;
  17777. });
  17778. });
  17779. Client client("localhost", get_port());
  17780. sse::SSEClient sse(client, "/reconnect-with-id");
  17781. sse.set_reconnect_interval(100);
  17782. sse.set_max_reconnect_attempts(3);
  17783. sse.start_async();
  17784. // Wait for at least 2 connections
  17785. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  17786. sse.stop();
  17787. // Verify behavior
  17788. std::lock_guard<std::mutex> lock(id_mutex);
  17789. EXPECT_GE(received_last_event_ids.size(), 2u);
  17790. // First connection should have no Last-Event-ID
  17791. if (!received_last_event_ids.empty()) {
  17792. EXPECT_EQ(received_last_event_ids[0], "");
  17793. }
  17794. // Second connection should have Last-Event-ID from first connection
  17795. if (received_last_event_ids.size() >= 2) {
  17796. EXPECT_EQ(received_last_event_ids[1], "event-0");
  17797. }
  17798. }
  17799. // Test: set_headers updates headers used on reconnect
  17800. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  17801. std::vector<std::string> received_tokens;
  17802. std::mutex token_mutex;
  17803. // Endpoint that captures Authorization header
  17804. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  17805. {
  17806. std::lock_guard<std::mutex> lock(token_mutex);
  17807. received_tokens.push_back(req.get_header_value("Authorization"));
  17808. }
  17809. res.set_chunked_content_provider(
  17810. "text/event-stream", [](size_t offset, DataSink &sink) {
  17811. if (offset == 0) {
  17812. std::string event = "data: hello\n\n";
  17813. sink.write(event.data(), event.size());
  17814. }
  17815. return false; // Close connection to trigger reconnect
  17816. });
  17817. });
  17818. Client client("localhost", get_port());
  17819. Headers headers = {{"Authorization", "Bearer old-token"}};
  17820. sse::SSEClient sse(client, "/auth-check", headers);
  17821. // Update headers on each successful connection
  17822. sse.on_open(
  17823. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  17824. sse.set_reconnect_interval(100);
  17825. sse.set_max_reconnect_attempts(3);
  17826. sse.start_async();
  17827. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  17828. sse.stop();
  17829. std::lock_guard<std::mutex> lock(token_mutex);
  17830. ASSERT_GE(received_tokens.size(), 2u);
  17831. // First connection uses original header
  17832. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  17833. // Second connection uses updated header from set_headers
  17834. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  17835. }
  17836. // Test: 401 allows reconnection (so on_error can refresh headers)
  17837. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  17838. std::atomic<int> connection_count{0};
  17839. // Endpoint: returns 401 on first attempt, 200 on second
  17840. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  17841. int conn = connection_count.fetch_add(1);
  17842. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  17843. res.status = StatusCode::Unauthorized_401;
  17844. res.set_content("Unauthorized", "text/plain");
  17845. return;
  17846. }
  17847. res.set_chunked_content_provider(
  17848. "text/event-stream", [](size_t offset, DataSink &sink) {
  17849. if (offset == 0) {
  17850. std::string event = "data: authenticated\n\n";
  17851. sink.write(event.data(), event.size());
  17852. }
  17853. return false;
  17854. });
  17855. });
  17856. Client client("localhost", get_port());
  17857. Headers headers = {{"Authorization", "Bearer expired"}};
  17858. sse::SSEClient sse(client, "/auth-retry", headers);
  17859. std::atomic<bool> message_received{false};
  17860. // Refresh token on error
  17861. sse.on_error(
  17862. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  17863. sse.on_message([&](const sse::SSEMessage &msg) {
  17864. if (msg.data == "authenticated") { message_received.store(true); }
  17865. });
  17866. sse.set_reconnect_interval(100);
  17867. sse.set_max_reconnect_attempts(3);
  17868. sse.start_async();
  17869. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  17870. sse.stop();
  17871. // Should have reconnected after 401 and succeeded with new token
  17872. EXPECT_GE(connection_count.load(), 2);
  17873. EXPECT_TRUE(message_received.load());
  17874. }
  17875. TEST(Issue2318Test, EmptyHostString) {
  17876. {
  17877. httplib::Client cli_empty("", PORT);
  17878. auto res = cli_empty.Get("/");
  17879. ASSERT_FALSE(res);
  17880. EXPECT_EQ(httplib::Error::Connection, res.error());
  17881. }
  17882. {
  17883. httplib::Client cli(" ", PORT);
  17884. auto res = cli.Get("/");
  17885. ASSERT_FALSE(res);
  17886. EXPECT_EQ(httplib::Error::Connection, res.error());
  17887. }
  17888. }
  17889. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  17890. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  17891. Server svr;
  17892. // Set a small payload limit (1KB)
  17893. svr.set_payload_max_length(1024);
  17894. svr.Post("/test", [&](const Request &req, Response &res) {
  17895. res.set_content("Body size: " + std::to_string(req.body.size()),
  17896. "text/plain");
  17897. });
  17898. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17899. auto se = detail::scope_exit([&] {
  17900. svr.stop();
  17901. listen_thread.join();
  17902. });
  17903. svr.wait_until_ready();
  17904. // Create data that compresses well but exceeds limit when decompressed
  17905. // 8KB of repeated null bytes compresses to a very small size
  17906. std::string original_data(8 * 1024, '\0');
  17907. // Compress the data using gzip
  17908. std::string compressed_data;
  17909. detail::gzip_compressor compressor;
  17910. compressor.compress(original_data.data(), original_data.size(), true,
  17911. [&](const char *data, size_t size) {
  17912. compressed_data.append(data, size);
  17913. return true;
  17914. });
  17915. // Verify compression worked (compressed should be much smaller)
  17916. ASSERT_LT(compressed_data.size(), original_data.size());
  17917. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  17918. // Send compressed data with Content-Encoding: gzip
  17919. Client cli(HOST, PORT);
  17920. Headers headers = {{"Content-Encoding", "gzip"}};
  17921. auto res =
  17922. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  17923. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  17924. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17925. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  17926. }
  17927. #endif
  17928. // ============================================================================
  17929. // OpenSSL-Specific Tests
  17930. // ============================================================================
  17931. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  17932. X509 *readCertificate(const std::string &strFileName) {
  17933. std::ifstream inStream(strFileName);
  17934. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  17935. std::istreambuf_iterator<char>());
  17936. if (strCertPEM.empty()) return (nullptr);
  17937. BIO *pbCert = BIO_new(BIO_s_mem());
  17938. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  17939. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  17940. BIO_free(pbCert);
  17941. return (pCert);
  17942. }
  17943. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  17944. std::ifstream inStream(strFileName);
  17945. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  17946. std::istreambuf_iterator<char>());
  17947. if (strPrivateKeyPEM.empty()) return (nullptr);
  17948. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  17949. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  17950. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  17951. BIO_free(pbPrivKey);
  17952. return (pPrivateKey);
  17953. }
  17954. TEST(BindServerTest, UpdateCerts) {
  17955. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  17956. int port = svr.bind_to_any_port("0.0.0.0");
  17957. ASSERT_TRUE(svr.is_valid());
  17958. ASSERT_TRUE(port > 0);
  17959. X509 *cert = readCertificate(SERVER_CERT_FILE);
  17960. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  17961. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  17962. ASSERT_TRUE(cert != nullptr);
  17963. ASSERT_TRUE(ca_cert != nullptr);
  17964. ASSERT_TRUE(key != nullptr);
  17965. X509_STORE *cert_store = X509_STORE_new();
  17966. X509_STORE_add_cert(cert_store, ca_cert);
  17967. // svr.update_certs(cert, key, cert_store); // deprecated
  17968. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  17969. CLIENT_CA_CERT_FILE);
  17970. ASSERT_TRUE(svr.is_valid());
  17971. svr.stop();
  17972. X509_STORE_free(cert_store);
  17973. X509_free(cert);
  17974. X509_free(ca_cert);
  17975. EVP_PKEY_free(key);
  17976. }
  17977. // Test that update_certs() updates client CA list correctly
  17978. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  17979. // Start with file-based constructor
  17980. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17981. ASSERT_TRUE(svr.is_valid());
  17982. // Initially no client CA list should be set
  17983. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  17984. ASSERT_TRUE(ssl_ctx != nullptr);
  17985. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  17986. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  17987. EXPECT_EQ(0, count_before);
  17988. // Now update with client CA (PEM string)
  17989. std::string cert_pem, key_pem, ca_pem;
  17990. read_file(SERVER_CERT_FILE, cert_pem);
  17991. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  17992. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  17993. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  17994. ASSERT_TRUE(svr.is_valid());
  17995. // Now client CA list should be set
  17996. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  17997. ASSERT_TRUE(ca_list_after != nullptr);
  17998. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  17999. }
  18000. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  18001. // Test that the file-path SSLServer constructor properly sets the client CA
  18002. // list that is sent to clients during the TLS handshake (CertificateRequest)
  18003. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  18004. ASSERT_TRUE(svr.is_valid());
  18005. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  18006. ASSERT_TRUE(ssl_ctx != nullptr);
  18007. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  18008. ASSERT_TRUE(ca_list != nullptr);
  18009. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  18010. }
  18011. #endif
  18012. // ============================================================================
  18013. // MbedTLS-Specific Tests
  18014. // ============================================================================
  18015. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  18016. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  18017. using namespace httplib::tls;
  18018. // Track if callback was invoked
  18019. bool callback_invoked = false;
  18020. // The callback receives void* ctx which is actually MbedTlsContext*
  18021. // We can access the mbedtls_ssl_config via the context
  18022. auto setup_callback = [&callback_invoked](void *ctx) {
  18023. callback_invoked = true;
  18024. // Cast to MbedTlsContext* to access the ssl config
  18025. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  18026. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  18027. // Use static variables to hold certificate data (simplified for test)
  18028. static mbedtls_x509_crt own_cert;
  18029. static mbedtls_pk_context own_key;
  18030. static mbedtls_x509_crt ca_chain;
  18031. static bool initialized = false;
  18032. if (!initialized) {
  18033. mbedtls_x509_crt_init(&own_cert);
  18034. mbedtls_pk_init(&own_key);
  18035. mbedtls_x509_crt_init(&ca_chain);
  18036. // Load server certificate
  18037. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  18038. return false;
  18039. }
  18040. // Load server private key.
  18041. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  18042. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  18043. #if MBEDTLS_VERSION_MAJOR == 3
  18044. ,
  18045. mbedtls_ctr_drbg_random, nullptr
  18046. #endif
  18047. ) != 0) {
  18048. return false;
  18049. }
  18050. // Load CA chain for client verification
  18051. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  18052. return false;
  18053. }
  18054. initialized = true;
  18055. }
  18056. // Configure the SSL config
  18057. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  18058. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  18059. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  18060. // Set minimum TLS version using mbedTLS native API
  18061. #if MBEDTLS_VERSION_MAJOR >= 3
  18062. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  18063. #else
  18064. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  18065. MBEDTLS_SSL_MINOR_VERSION_3);
  18066. #endif
  18067. return true;
  18068. };
  18069. SSLServer svr(setup_callback);
  18070. ASSERT_TRUE(svr.is_valid());
  18071. ASSERT_TRUE(callback_invoked);
  18072. svr.Get("/test", [&](const Request &req, Response &res) {
  18073. res.set_content("test", "text/plain");
  18074. auto cert = req.peer_cert();
  18075. ASSERT_TRUE(static_cast<bool>(cert));
  18076. auto common_name = cert.subject_cn();
  18077. EXPECT_EQ("Common Name", common_name);
  18078. });
  18079. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  18080. auto se = detail::scope_exit([&] {
  18081. svr.stop();
  18082. t.join();
  18083. ASSERT_FALSE(svr.is_running());
  18084. });
  18085. svr.wait_until_ready();
  18086. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  18087. cli.enable_server_certificate_verification(false);
  18088. cli.set_connection_timeout(30);
  18089. auto res = cli.Get("/test");
  18090. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18091. ASSERT_EQ(StatusCode::OK_200, res->status);
  18092. }
  18093. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  18094. // context (owning mbedtls_ssl_config) before shutting down a still-open
  18095. // keep-alive SSL session, which reads through that config in
  18096. // mbedtls_ssl_close_notify.
  18097. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  18098. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18099. ASSERT_TRUE(svr.is_valid());
  18100. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  18101. res.set_content("test", "text/plain");
  18102. });
  18103. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  18104. auto se = detail::scope_exit([&] {
  18105. svr.stop();
  18106. t.join();
  18107. ASSERT_FALSE(svr.is_running());
  18108. });
  18109. svr.wait_until_ready();
  18110. {
  18111. SSLClient cli(HOST, PORT);
  18112. cli.enable_server_certificate_verification(false);
  18113. cli.set_keep_alive(true);
  18114. auto res = cli.Get("/test");
  18115. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18116. ASSERT_EQ(StatusCode::OK_200, res->status);
  18117. // cli is destructed here with the keep-alive SSL session still open.
  18118. }
  18119. }
  18120. #endif
  18121. // WebSocket Tests
  18122. TEST(WebSocketTest, RSVBitsMustBeZero) {
  18123. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  18124. // defining the meaning of these bits has been negotiated.
  18125. auto make_frame = [](uint8_t first_byte) {
  18126. std::string frame;
  18127. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  18128. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  18129. frame += "Hello";
  18130. return frame;
  18131. };
  18132. // RSV1 set (0x40)
  18133. {
  18134. detail::BufferStream strm;
  18135. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  18136. ws::Opcode opcode;
  18137. std::string payload;
  18138. bool fin;
  18139. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  18140. false, 1024));
  18141. }
  18142. // RSV2 set (0x20)
  18143. {
  18144. detail::BufferStream strm;
  18145. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  18146. ws::Opcode opcode;
  18147. std::string payload;
  18148. bool fin;
  18149. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  18150. false, 1024));
  18151. }
  18152. // RSV3 set (0x10)
  18153. {
  18154. detail::BufferStream strm;
  18155. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  18156. ws::Opcode opcode;
  18157. std::string payload;
  18158. bool fin;
  18159. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  18160. false, 1024));
  18161. }
  18162. // No RSV bits set - should succeed
  18163. {
  18164. detail::BufferStream strm;
  18165. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  18166. ws::Opcode opcode;
  18167. std::string payload;
  18168. bool fin;
  18169. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  18170. false, 1024));
  18171. EXPECT_EQ(ws::Opcode::Text, opcode);
  18172. EXPECT_EQ("Hello", payload);
  18173. EXPECT_TRUE(fin);
  18174. }
  18175. }
  18176. TEST(WebSocketTest, ControlFrameValidation) {
  18177. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  18178. // payload length <= 125.
  18179. // Ping with FIN=0 - must be rejected
  18180. {
  18181. detail::BufferStream strm;
  18182. std::string frame;
  18183. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  18184. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  18185. strm.write(frame.data(), frame.size());
  18186. ws::Opcode opcode;
  18187. std::string payload;
  18188. bool fin;
  18189. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  18190. false, 1024));
  18191. }
  18192. // Close with FIN=0 - must be rejected
  18193. {
  18194. detail::BufferStream strm;
  18195. std::string frame;
  18196. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  18197. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  18198. strm.write(frame.data(), frame.size());
  18199. ws::Opcode opcode;
  18200. std::string payload;
  18201. bool fin;
  18202. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  18203. false, 1024));
  18204. }
  18205. // Ping with payload_len=126 (extended length) - must be rejected
  18206. {
  18207. detail::BufferStream strm;
  18208. std::string frame;
  18209. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  18210. frame += static_cast<char>(126); // payload_len=126 (>125)
  18211. frame += static_cast<char>(0x00); // extended length high byte
  18212. frame += static_cast<char>(126); // extended length low byte
  18213. frame += std::string(126, 'x');
  18214. strm.write(frame.data(), frame.size());
  18215. ws::Opcode opcode;
  18216. std::string payload;
  18217. bool fin;
  18218. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  18219. false, 1024));
  18220. }
  18221. // Ping with FIN=1 and payload_len=125 - should succeed
  18222. {
  18223. detail::BufferStream strm;
  18224. std::string frame;
  18225. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  18226. frame += static_cast<char>(125); // payload_len=125
  18227. frame += std::string(125, 'x');
  18228. strm.write(frame.data(), frame.size());
  18229. ws::Opcode opcode;
  18230. std::string payload;
  18231. bool fin;
  18232. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  18233. false, 1024));
  18234. EXPECT_EQ(ws::Opcode::Ping, opcode);
  18235. EXPECT_EQ(125u, payload.size());
  18236. EXPECT_TRUE(fin);
  18237. }
  18238. }
  18239. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  18240. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  18241. // length MUST be 0.
  18242. // MSB set - must be rejected
  18243. {
  18244. detail::BufferStream strm;
  18245. std::string frame;
  18246. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  18247. frame += static_cast<char>(127); // 64-bit extended length
  18248. frame += static_cast<char>(0x80); // MSB set (invalid)
  18249. frame += std::string(7, '\0'); // remaining 7 bytes of length
  18250. strm.write(frame.data(), frame.size());
  18251. ws::Opcode opcode;
  18252. std::string payload;
  18253. bool fin;
  18254. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  18255. false, 1024));
  18256. }
  18257. // MSB clear - should pass length parsing (will be rejected by max_len,
  18258. // but that's a different check; use a small length to verify)
  18259. {
  18260. detail::BufferStream strm;
  18261. std::string frame;
  18262. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  18263. frame += static_cast<char>(127); // 64-bit extended length
  18264. frame += std::string(7, '\0'); // high bytes = 0
  18265. frame += static_cast<char>(0x03); // length = 3
  18266. frame += "abc";
  18267. strm.write(frame.data(), frame.size());
  18268. ws::Opcode opcode;
  18269. std::string payload;
  18270. bool fin;
  18271. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  18272. false, 1024));
  18273. EXPECT_EQ(ws::Opcode::Text, opcode);
  18274. EXPECT_EQ("abc", payload);
  18275. }
  18276. }
  18277. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  18278. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  18279. // Valid UTF-8
  18280. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  18281. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  18282. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  18283. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  18284. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  18285. // Invalid UTF-8
  18286. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  18287. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  18288. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  18289. EXPECT_FALSE(
  18290. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  18291. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  18292. }
  18293. TEST(WebSocketTest, ConnectAndDisconnect) {
  18294. Server svr;
  18295. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  18296. std::string msg;
  18297. while (ws.read(msg)) {}
  18298. });
  18299. auto port = svr.bind_to_any_port(HOST);
  18300. std::thread t([&]() { svr.listen_after_bind(); });
  18301. svr.wait_until_ready();
  18302. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  18303. auto res = client.connect();
  18304. ASSERT_TRUE(res);
  18305. EXPECT_EQ(Error::Success, res.error());
  18306. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  18307. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  18308. EXPECT_TRUE(client.is_open());
  18309. client.close();
  18310. EXPECT_FALSE(client.is_open());
  18311. svr.stop();
  18312. t.join();
  18313. }
  18314. TEST(WebSocketTest, ValidURL) {
  18315. ws::WebSocketClient ws1("ws://localhost:8080/path");
  18316. EXPECT_TRUE(ws1.is_valid());
  18317. ws::WebSocketClient ws2("ws://example.com/path");
  18318. EXPECT_TRUE(ws2.is_valid());
  18319. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  18320. EXPECT_TRUE(ws3.is_valid());
  18321. #ifdef CPPHTTPLIB_SSL_ENABLED
  18322. ws::WebSocketClient wss1("wss://example.com/path");
  18323. EXPECT_TRUE(wss1.is_valid());
  18324. ws::WebSocketClient wss2("wss://example.com:443/path");
  18325. EXPECT_TRUE(wss2.is_valid());
  18326. #endif
  18327. }
  18328. TEST(WebSocketTest, InvalidURL) {
  18329. // No scheme
  18330. ws::WebSocketClient ws1("localhost:8080/path");
  18331. EXPECT_FALSE(ws1.is_valid());
  18332. // No path
  18333. ws::WebSocketClient ws2("ws://localhost:8080");
  18334. EXPECT_FALSE(ws2.is_valid());
  18335. // Empty string
  18336. ws::WebSocketClient ws3("");
  18337. EXPECT_FALSE(ws3.is_valid());
  18338. // Missing host
  18339. ws::WebSocketClient ws4("ws://:8080/path");
  18340. EXPECT_FALSE(ws4.is_valid());
  18341. // Port number overflow — should not crash
  18342. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  18343. EXPECT_FALSE(ws5.is_valid());
  18344. // Port out of range
  18345. ws::WebSocketClient ws6("ws://localhost:99999/path");
  18346. EXPECT_FALSE(ws6.is_valid());
  18347. }
  18348. TEST(WebSocketTest, UnsupportedScheme) {
  18349. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  18350. ws::WebSocketClient ws1("http://localhost:8080/path");
  18351. EXPECT_FALSE(ws1.is_valid());
  18352. ws::WebSocketClient ws2("https://localhost:8080/path");
  18353. EXPECT_FALSE(ws2.is_valid());
  18354. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  18355. EXPECT_FALSE(ws3.is_valid());
  18356. #else
  18357. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  18358. std::invalid_argument);
  18359. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  18360. std::invalid_argument);
  18361. #endif
  18362. }
  18363. TEST(WebSocketTest, ConnectWhenInvalid) {
  18364. ws::WebSocketClient ws("not a valid url");
  18365. EXPECT_FALSE(ws.is_valid());
  18366. auto res = ws.connect();
  18367. EXPECT_FALSE(res);
  18368. EXPECT_EQ(Error::Connection, res.error());
  18369. EXPECT_EQ(-1, res.status());
  18370. }
  18371. TEST(WebSocketTest, ConnectRefusedReportsError) {
  18372. // Grab a port that is free, then close it again so nothing listens there
  18373. Server svr;
  18374. auto port = svr.bind_to_any_port(HOST);
  18375. svr.stop();
  18376. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  18377. auto res = client.connect();
  18378. ASSERT_FALSE(res);
  18379. EXPECT_EQ(Error::Connection, res.error());
  18380. EXPECT_EQ(-1, res.status());
  18381. }
  18382. TEST(WebSocketTest, DefaultPort) {
  18383. ws::WebSocketClient ws1("ws://example.com/path");
  18384. EXPECT_TRUE(ws1.is_valid());
  18385. // ws:// defaults to port 80 (verified by successful parse)
  18386. #ifdef CPPHTTPLIB_SSL_ENABLED
  18387. ws::WebSocketClient ws2("wss://example.com/path");
  18388. EXPECT_TRUE(ws2.is_valid());
  18389. // wss:// defaults to port 443 (verified by successful parse)
  18390. #endif
  18391. }
  18392. TEST(WebSocketTest, IPv6LiteralAddress) {
  18393. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  18394. EXPECT_TRUE(ws1.is_valid());
  18395. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  18396. EXPECT_TRUE(ws2.is_valid());
  18397. }
  18398. TEST(WebSocketTest, ComplexPath) {
  18399. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  18400. EXPECT_TRUE(ws1.is_valid());
  18401. ws::WebSocketClient ws2("ws://localhost:8080/");
  18402. EXPECT_TRUE(ws2.is_valid());
  18403. }
  18404. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  18405. Server svr;
  18406. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  18407. std::string msg;
  18408. while (ws.read(msg)) {}
  18409. });
  18410. auto port = svr.bind_to_any_port(HOST);
  18411. std::thread t([&]() { svr.listen_after_bind(); });
  18412. svr.wait_until_ready();
  18413. auto another_host = "example.com";
  18414. auto wrong_ip = "192.0.2.1";
  18415. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  18416. client.set_hostname_addr_map({{another_host, wrong_ip}});
  18417. ASSERT_TRUE(client.connect());
  18418. EXPECT_TRUE(client.is_open());
  18419. client.close();
  18420. svr.stop();
  18421. t.join();
  18422. }
  18423. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  18424. Server svr;
  18425. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  18426. std::string msg;
  18427. while (ws.read(msg)) {}
  18428. });
  18429. auto port = svr.bind_to_any_port(HOST);
  18430. std::thread t([&]() { svr.listen_after_bind(); });
  18431. svr.wait_until_ready();
  18432. auto wrong_ip = "192.0.2.1";
  18433. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  18434. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  18435. client.set_connection_timeout(1);
  18436. client.set_read_timeout(1);
  18437. client.set_write_timeout(1);
  18438. EXPECT_FALSE(client.connect());
  18439. EXPECT_FALSE(client.is_open());
  18440. svr.stop();
  18441. t.join();
  18442. }
  18443. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  18444. // A mapped value that is not an IP literal must be resolved. HOST resolves
  18445. // from the hosts file, so this test needs no external DNS. "target.invalid"
  18446. // (RFC 6761) is only a map key and the Host header value.
  18447. auto host = "target.invalid";
  18448. Server svr;
  18449. std::string received_host;
  18450. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  18451. received_host = req.get_header_value("Host");
  18452. std::string msg;
  18453. while (ws.read(msg)) {}
  18454. });
  18455. auto port = svr.bind_to_any_port(HOST);
  18456. std::thread t([&]() { svr.listen_after_bind(); });
  18457. // ASSERT_* below returns from the test body, which would leave t joinable
  18458. // and make ~thread call std::terminate.
  18459. auto se = detail::scope_exit([&] {
  18460. svr.stop();
  18461. if (t.joinable()) { t.join(); }
  18462. });
  18463. svr.wait_until_ready();
  18464. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  18465. std::to_string(port) + "/ws");
  18466. client.set_hostname_addr_map({{host, HOST}});
  18467. ASSERT_TRUE(client.connect());
  18468. EXPECT_TRUE(client.is_open());
  18469. client.close();
  18470. svr.stop();
  18471. t.join();
  18472. // The mapping only redirects the connection; the identity stays host_.
  18473. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  18474. }
  18475. class WebSocketIntegrationTest : public ::testing::Test {
  18476. protected:
  18477. void SetUp() override {
  18478. server_ = httplib::detail::make_unique<Server>();
  18479. setup_server();
  18480. start_server();
  18481. }
  18482. void TearDown() override {
  18483. server_->stop();
  18484. if (server_thread_.joinable()) { server_thread_.join(); }
  18485. }
  18486. void setup_server() {
  18487. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  18488. std::string msg;
  18489. ws::ReadResult ret;
  18490. while ((ret = ws.read(msg))) {
  18491. if (ret == ws::Binary) {
  18492. ws.send(msg.data(), msg.size());
  18493. } else {
  18494. ws.send(msg);
  18495. }
  18496. }
  18497. });
  18498. server_->WebSocket("/ws-echo-string",
  18499. [](const Request &, ws::WebSocket &ws) {
  18500. std::string msg;
  18501. while (ws.read(msg)) {
  18502. ws.send("echo: " + msg);
  18503. }
  18504. });
  18505. server_->WebSocket(
  18506. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  18507. // Echo back request metadata
  18508. ws.send("path:" + req.path);
  18509. ws.send("header:" + req.get_header_value("X-Test-Header"));
  18510. std::string msg;
  18511. while (ws.read(msg)) {}
  18512. });
  18513. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  18514. std::string msg;
  18515. ws.read(msg); // wait for a message
  18516. ws.close();
  18517. });
  18518. server_->WebSocket("/ws-close-status",
  18519. [](const Request &, ws::WebSocket &ws) {
  18520. std::string msg;
  18521. ws.read(msg); // wait for a message
  18522. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  18523. });
  18524. server_->WebSocket(
  18525. "/ws-subprotocol",
  18526. [](const Request &, ws::WebSocket &ws) {
  18527. std::string msg;
  18528. while (ws.read(msg)) {
  18529. ws.send(msg);
  18530. }
  18531. },
  18532. [](const std::vector<std::string> &protocols) -> std::string {
  18533. for (const auto &p : protocols) {
  18534. if (p == "graphql-ws") { return p; }
  18535. }
  18536. return "";
  18537. });
  18538. }
  18539. void start_server() {
  18540. port_ = server_->bind_to_any_port(HOST);
  18541. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  18542. server_->wait_until_ready();
  18543. }
  18544. std::unique_ptr<Server> server_;
  18545. std::thread server_thread_;
  18546. int port_ = 0;
  18547. };
  18548. TEST_F(WebSocketIntegrationTest, TextEcho) {
  18549. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18550. "/ws-echo");
  18551. ASSERT_TRUE(client.connect());
  18552. ASSERT_TRUE(client.is_open());
  18553. ASSERT_TRUE(client.send("Hello WebSocket"));
  18554. std::string msg;
  18555. EXPECT_EQ(ws::Text, client.read(msg));
  18556. EXPECT_EQ("Hello WebSocket", msg);
  18557. client.close();
  18558. }
  18559. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  18560. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18561. "/ws-echo");
  18562. ASSERT_TRUE(client.connect());
  18563. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  18564. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  18565. std::string msg;
  18566. EXPECT_EQ(ws::Binary, client.read(msg));
  18567. EXPECT_EQ(binary_data, msg);
  18568. client.close();
  18569. }
  18570. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  18571. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18572. "/ws-echo");
  18573. ASSERT_TRUE(client.connect());
  18574. for (int i = 0; i < 10; i++) {
  18575. auto text = "message " + std::to_string(i);
  18576. ASSERT_TRUE(client.send(text));
  18577. std::string msg;
  18578. ASSERT_TRUE(client.read(msg));
  18579. EXPECT_EQ(text, msg);
  18580. }
  18581. client.close();
  18582. }
  18583. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  18584. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18585. "/ws-close");
  18586. ASSERT_TRUE(client.connect());
  18587. // Send a message to trigger the server to close
  18588. ASSERT_TRUE(client.send("trigger close"));
  18589. // The server will close, so read should return false
  18590. std::string msg;
  18591. EXPECT_FALSE(client.read(msg));
  18592. EXPECT_FALSE(client.is_open());
  18593. }
  18594. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  18595. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18596. "/ws-echo");
  18597. ASSERT_TRUE(client.connect());
  18598. // 128KB message
  18599. std::string large_data(128 * 1024, 'X');
  18600. ASSERT_TRUE(client.send(large_data));
  18601. std::string msg;
  18602. ASSERT_TRUE(client.read(msg));
  18603. EXPECT_EQ(large_data, msg);
  18604. client.close();
  18605. }
  18606. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  18607. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18608. "/ws-echo");
  18609. ASSERT_TRUE(client.connect());
  18610. const int num_threads = 4;
  18611. std::vector<std::thread> threads;
  18612. std::atomic<int> send_count{0};
  18613. for (int t = 0; t < num_threads; t++) {
  18614. threads.emplace_back([&client, &send_count, t]() {
  18615. for (int i = 0; i < 5; i++) {
  18616. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  18617. if (client.send(text)) { send_count++; }
  18618. }
  18619. });
  18620. }
  18621. for (auto &th : threads) {
  18622. th.join();
  18623. }
  18624. int received = 0;
  18625. std::string msg;
  18626. while (received < send_count.load()) {
  18627. if (!client.read(msg)) { break; }
  18628. received++;
  18629. }
  18630. EXPECT_EQ(send_count.load(), received);
  18631. client.close();
  18632. }
  18633. TEST_F(WebSocketIntegrationTest, ReadString) {
  18634. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18635. "/ws-echo-string");
  18636. ASSERT_TRUE(client.connect());
  18637. ASSERT_TRUE(client.send("hello"));
  18638. std::string msg;
  18639. ASSERT_TRUE(client.read(msg));
  18640. EXPECT_EQ("echo: hello", msg);
  18641. ASSERT_TRUE(client.send("world"));
  18642. ASSERT_TRUE(client.read(msg));
  18643. EXPECT_EQ("echo: world", msg);
  18644. client.close();
  18645. }
  18646. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  18647. Headers headers = {{"X-Test-Header", "test-value"}};
  18648. ws::WebSocketClient client(
  18649. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  18650. ASSERT_TRUE(client.connect());
  18651. std::string msg;
  18652. ASSERT_TRUE(client.read(msg));
  18653. EXPECT_EQ("path:/ws-request-info", msg);
  18654. ASSERT_TRUE(client.read(msg));
  18655. EXPECT_EQ("header:test-value", msg);
  18656. client.close();
  18657. }
  18658. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  18659. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18660. "/ws-echo");
  18661. client.set_read_timeout(1, 0); // 1 second
  18662. ASSERT_TRUE(client.connect());
  18663. // Don't send anything — server echo handler waits for a message,
  18664. // so read() should time out and return false.
  18665. std::string msg;
  18666. EXPECT_FALSE(client.read(msg));
  18667. }
  18668. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  18669. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18670. "/ws-echo");
  18671. client.set_read_timeout(5, 0);
  18672. ASSERT_TRUE(client.connect());
  18673. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  18674. // The server should reject it and close the connection.
  18675. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  18676. client.send(oversized);
  18677. // The server's read() should have failed due to payload limit,
  18678. // so our read() should return false (connection closed).
  18679. std::string msg;
  18680. EXPECT_FALSE(client.read(msg));
  18681. }
  18682. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  18683. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18684. "/ws-echo");
  18685. client.set_read_timeout(10, 0);
  18686. ASSERT_TRUE(client.connect());
  18687. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  18688. // This should succeed.
  18689. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  18690. ASSERT_TRUE(client.send(at_limit));
  18691. std::string msg;
  18692. ASSERT_TRUE(client.read(msg));
  18693. EXPECT_EQ(at_limit.size(), msg.size());
  18694. client.close();
  18695. }
  18696. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  18697. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18698. "/nonexistent");
  18699. auto res = client.connect();
  18700. EXPECT_FALSE(res);
  18701. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  18702. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  18703. EXPECT_FALSE(client.is_open());
  18704. }
  18705. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  18706. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18707. "/ws-echo");
  18708. ASSERT_TRUE(client.connect());
  18709. ASSERT_TRUE(client.send(""));
  18710. std::string msg;
  18711. EXPECT_EQ(ws::Text, client.read(msg));
  18712. EXPECT_EQ("", msg);
  18713. client.close();
  18714. }
  18715. TEST_F(WebSocketIntegrationTest, Reconnect) {
  18716. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18717. "/ws-echo");
  18718. // First connection
  18719. ASSERT_TRUE(client.connect());
  18720. ASSERT_TRUE(client.send("first"));
  18721. std::string msg;
  18722. ASSERT_TRUE(client.read(msg));
  18723. EXPECT_EQ("first", msg);
  18724. client.close();
  18725. EXPECT_FALSE(client.is_open());
  18726. // Reconnect using the same client object
  18727. ASSERT_TRUE(client.connect());
  18728. ASSERT_TRUE(client.is_open());
  18729. ASSERT_TRUE(client.send("second"));
  18730. ASSERT_TRUE(client.read(msg));
  18731. EXPECT_EQ("second", msg);
  18732. client.close();
  18733. }
  18734. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  18735. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18736. "/ws-close-status");
  18737. ASSERT_TRUE(client.connect());
  18738. // Trigger the server to close with GoingAway status
  18739. ASSERT_TRUE(client.send("trigger"));
  18740. // read() should return false after receiving the close frame
  18741. std::string msg;
  18742. EXPECT_FALSE(client.read(msg));
  18743. EXPECT_FALSE(client.is_open());
  18744. }
  18745. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  18746. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18747. "/ws-echo");
  18748. ASSERT_TRUE(client.connect());
  18749. client.close(ws::CloseStatus::GoingAway, "client leaving");
  18750. EXPECT_FALSE(client.is_open());
  18751. }
  18752. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  18753. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  18754. ws::WebSocketClient client(
  18755. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  18756. ASSERT_TRUE(client.connect());
  18757. // Server should have selected graphql-ws
  18758. EXPECT_EQ("graphql-ws", client.subprotocol());
  18759. client.close();
  18760. }
  18761. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  18762. Headers headers;
  18763. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  18764. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  18765. ws::WebSocketClient client(
  18766. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  18767. ASSERT_TRUE(client.connect());
  18768. // The offer on the second field line counts too, so graphql-ws is selected
  18769. EXPECT_EQ("graphql-ws", client.subprotocol());
  18770. client.close();
  18771. }
  18772. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  18773. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  18774. ws::WebSocketClient client(
  18775. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  18776. ASSERT_TRUE(client.connect());
  18777. // Server should not have selected any subprotocol
  18778. EXPECT_TRUE(client.subprotocol().empty());
  18779. client.close();
  18780. }
  18781. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  18782. // Connect without requesting any subprotocol
  18783. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18784. "/ws-subprotocol");
  18785. ASSERT_TRUE(client.connect());
  18786. EXPECT_TRUE(client.subprotocol().empty());
  18787. client.close();
  18788. }
  18789. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  18790. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18791. "/ws-echo");
  18792. client.set_tcp_nodelay(true);
  18793. client.set_connection_timeout(3, 0);
  18794. bool socket_options_called = false;
  18795. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  18796. ASSERT_TRUE(client.connect());
  18797. ASSERT_TRUE(client.is_open());
  18798. EXPECT_TRUE(socket_options_called);
  18799. ASSERT_TRUE(client.send("hello"));
  18800. std::string msg;
  18801. auto result = client.read(msg);
  18802. EXPECT_EQ(result, ws::ReadResult::Text);
  18803. EXPECT_EQ(msg, "hello");
  18804. client.close();
  18805. }
  18806. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  18807. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18808. "/ws-echo");
  18809. client.set_connection_timeout(std::chrono::seconds(3));
  18810. client.set_write_timeout(std::chrono::seconds(3));
  18811. // A sub-second remainder exercises the seconds/microseconds split.
  18812. client.set_read_timeout(std::chrono::milliseconds(1500));
  18813. ASSERT_TRUE(client.connect());
  18814. auto start = std::chrono::steady_clock::now();
  18815. std::string msg;
  18816. EXPECT_EQ(client.read(msg), ws::ReadResult::Fail);
  18817. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18818. std::chrono::steady_clock::now() - start)
  18819. .count();
  18820. // Above 1s so that dropping the microseconds half of the split fails here,
  18821. // and well under the 300s default so that ignoring the setter fails too.
  18822. EXPECT_GE(elapsed, 1400);
  18823. EXPECT_LT(elapsed, 30000);
  18824. }
  18825. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  18826. Server svr;
  18827. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  18828. if (!req.has_header("Authorization")) {
  18829. res.status = StatusCode::Unauthorized_401;
  18830. res.set_content("Unauthorized", "text/plain");
  18831. return Server::HandlerResponse::Handled;
  18832. }
  18833. return Server::HandlerResponse::Unhandled;
  18834. });
  18835. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  18836. std::string msg;
  18837. while (ws.read(msg)) {
  18838. ws.send(msg);
  18839. }
  18840. });
  18841. auto port = svr.bind_to_any_port("localhost");
  18842. std::thread t([&]() { svr.listen_after_bind(); });
  18843. svr.wait_until_ready();
  18844. // Without Authorization header - should be rejected before upgrade
  18845. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  18846. EXPECT_FALSE(client1.connect());
  18847. // With Authorization header - should succeed
  18848. Headers headers = {{"Authorization", "Bearer token123"}};
  18849. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  18850. headers);
  18851. ASSERT_TRUE(client2.connect());
  18852. ASSERT_TRUE(client2.send("hello"));
  18853. std::string msg;
  18854. ASSERT_TRUE(client2.read(msg));
  18855. EXPECT_EQ("hello", msg);
  18856. client2.close();
  18857. svr.stop();
  18858. t.join();
  18859. }
  18860. TEST(WebSocketTest, QueryStringInHandshake) {
  18861. Server svr;
  18862. std::mutex mtx;
  18863. std::string received_target;
  18864. std::string received_token;
  18865. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  18866. {
  18867. std::lock_guard<std::mutex> lock(mtx);
  18868. received_target = req.target;
  18869. if (req.has_param("token")) {
  18870. received_token = req.get_param_value("token");
  18871. }
  18872. }
  18873. std::string msg;
  18874. while (ws.read(msg)) {
  18875. ws.send(msg);
  18876. }
  18877. });
  18878. auto port = svr.bind_to_any_port("localhost");
  18879. std::thread t([&]() { svr.listen_after_bind(); });
  18880. svr.wait_until_ready();
  18881. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  18882. "/ws?token=ABC&session=123");
  18883. ASSERT_TRUE(client.connect());
  18884. // Round-trip ensures the handler has run and captured the request.
  18885. ASSERT_TRUE(client.send("hello"));
  18886. std::string msg;
  18887. ASSERT_TRUE(client.read(msg));
  18888. EXPECT_EQ("hello", msg);
  18889. client.close();
  18890. {
  18891. std::lock_guard<std::mutex> lock(mtx);
  18892. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  18893. EXPECT_EQ("ABC", received_token);
  18894. }
  18895. svr.stop();
  18896. t.join();
  18897. }
  18898. // Run a handshake against a throwaway server and hand the request the server
  18899. // received back to the caller, so tests can assert on the headers the client
  18900. // actually put on the wire.
  18901. static void capture_websocket_handshake_request(
  18902. const Headers &client_headers,
  18903. std::function<void(const Request &, int port)> verify) {
  18904. Server svr;
  18905. std::mutex mtx;
  18906. Request received;
  18907. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  18908. {
  18909. std::lock_guard<std::mutex> lock(mtx);
  18910. received = req;
  18911. }
  18912. std::string msg;
  18913. while (ws.read(msg)) {
  18914. ws.send(msg);
  18915. }
  18916. });
  18917. auto port = svr.bind_to_any_port("localhost");
  18918. std::thread t([&]() { svr.listen_after_bind(); });
  18919. auto se = detail::scope_exit([&] {
  18920. svr.stop();
  18921. t.join();
  18922. });
  18923. svr.wait_until_ready();
  18924. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  18925. client_headers);
  18926. ASSERT_TRUE(client.connect());
  18927. ASSERT_TRUE(client.send("hello"));
  18928. std::string msg;
  18929. ASSERT_TRUE(client.read(msg));
  18930. client.close();
  18931. {
  18932. std::lock_guard<std::mutex> lock(mtx);
  18933. verify(received, port);
  18934. }
  18935. }
  18936. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  18937. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  18938. // Non-default port must be present in the Host header. Default ports
  18939. // (80/443) are omitted; that logic is covered by
  18940. // MakeHostAndPortStringTest.
  18941. EXPECT_EQ("localhost:" + std::to_string(port),
  18942. req.get_header_value("Host"));
  18943. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  18944. req.get_header_value("User-Agent"));
  18945. EXPECT_FALSE(req.has_header("Accept"));
  18946. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  18947. EXPECT_FALSE(req.has_header("Content-Length"));
  18948. });
  18949. }
  18950. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  18951. capture_websocket_handshake_request(
  18952. {{"Host", "example.com"},
  18953. {"User-Agent", "custom-agent"},
  18954. {"X-Custom", "value"}},
  18955. [](const Request &req, int) {
  18956. EXPECT_EQ("example.com", req.get_header_value("Host"));
  18957. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  18958. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  18959. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  18960. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  18961. });
  18962. }
  18963. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  18964. capture_websocket_handshake_request(
  18965. {{"Upgrade", "bogus"},
  18966. {"Connection", "close"},
  18967. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  18968. {"Sec-WebSocket-Version", "8"}},
  18969. [](const Request &req, int) {
  18970. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  18971. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  18972. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  18973. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  18974. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  18975. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  18976. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  18977. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  18978. req.get_header_value("Sec-WebSocket-Key"));
  18979. });
  18980. }
  18981. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  18982. // A header the client refuses to send must abort the handshake before any
  18983. // part of it reaches the wire; a lone request line would otherwise sit in
  18984. // the peer's buffer as a truncated request.
  18985. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18986. ASSERT_NE(INVALID_SOCKET, srv);
  18987. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  18988. sockaddr_in addr{};
  18989. addr.sin_family = AF_INET;
  18990. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  18991. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18992. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  18993. ASSERT_EQ(0, ::listen(srv, 1));
  18994. sockaddr_in bound{};
  18995. socklen_t bound_len = sizeof(bound);
  18996. ASSERT_EQ(
  18997. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  18998. auto port = ntohs(bound.sin_port);
  18999. ssize_t received = -1;
  19000. std::thread t([&] {
  19001. // Bound every blocking call so a regression fails the test with a bad
  19002. // value instead of hanging the suite.
  19003. fd_set rfds;
  19004. FD_ZERO(&rfds);
  19005. FD_SET(srv, &rfds);
  19006. timeval tv{5, 0};
  19007. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  19008. 0) {
  19009. return;
  19010. }
  19011. sockaddr_in cli_addr{};
  19012. socklen_t cli_len = sizeof(cli_addr);
  19013. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  19014. if (cli == INVALID_SOCKET) { return; }
  19015. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  19016. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  19017. char buf[4096];
  19018. received = ::recv(cli, buf, sizeof(buf), 0);
  19019. });
  19020. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  19021. // connect() has already shut the socket down by the time it returns false,
  19022. // so the peer sees EOF without waiting for the client to be destroyed.
  19023. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  19024. {{"X-Bad", "a\r\nInjected: 1"}});
  19025. EXPECT_FALSE(client.connect());
  19026. t.join();
  19027. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  19028. EXPECT_EQ(0, received);
  19029. }
  19030. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  19031. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  19032. // contains "upgrade" as a substring is a different token and must not
  19033. // start a WebSocket handshake.
  19034. auto make_request = [](const std::vector<std::string> &connection_values) {
  19035. Request req;
  19036. req.method = "GET";
  19037. req.headers.emplace("Upgrade", "websocket");
  19038. for (const auto &value : connection_values) {
  19039. req.headers.emplace("Connection", value);
  19040. }
  19041. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  19042. req.headers.emplace("Sec-WebSocket-Version", "13");
  19043. return req;
  19044. };
  19045. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  19046. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  19047. EXPECT_TRUE(
  19048. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  19049. EXPECT_TRUE(
  19050. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  19051. EXPECT_TRUE(
  19052. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  19053. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  19054. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  19055. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  19056. EXPECT_FALSE(
  19057. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  19058. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  19059. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  19060. }
  19061. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  19062. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  19063. // asks recipients to match each protocol-name case-insensitively, and RFC
  19064. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  19065. // client naming websocket alongside another protocol, or on a second field
  19066. // line, is offering websocket; a value that merely contains "websocket" as a
  19067. // substring is a different protocol name and is not.
  19068. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  19069. Request req;
  19070. req.method = "GET";
  19071. for (const auto &value : upgrade_values) {
  19072. req.headers.emplace("Upgrade", value);
  19073. }
  19074. req.headers.emplace("Connection", "Upgrade");
  19075. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  19076. req.headers.emplace("Sec-WebSocket-Version", "13");
  19077. return req;
  19078. };
  19079. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  19080. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  19081. EXPECT_TRUE(
  19082. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  19083. EXPECT_TRUE(
  19084. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  19085. EXPECT_TRUE(
  19086. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  19087. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  19088. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  19089. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  19090. EXPECT_FALSE(
  19091. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  19092. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  19093. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  19094. }
  19095. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  19096. Server svr;
  19097. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  19098. auto port = svr.bind_to_any_port("localhost");
  19099. std::thread t([&]() { svr.listen_after_bind(); });
  19100. auto se = detail::scope_exit([&] {
  19101. svr.stop();
  19102. t.join();
  19103. });
  19104. svr.wait_until_ready();
  19105. Headers headers = {{"Upgrade", "websocket"},
  19106. {"Connection", "notupgrade"},
  19107. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  19108. {"Sec-WebSocket-Version", "13"}};
  19109. Client cli("localhost", port);
  19110. auto res = cli.Get("/ws", headers);
  19111. // The route exists only as a WebSocket route, so a request that fails the
  19112. // handshake check falls through to ordinary routing.
  19113. ASSERT_TRUE(res);
  19114. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  19115. }
  19116. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  19117. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  19118. // Connection value is the only thing left for the client to reject.
  19119. Server svr;
  19120. svr.Get("/ws", [](const Request &req, Response &res) {
  19121. res.status = StatusCode::SwitchingProtocol_101;
  19122. res.set_header("Upgrade", "websocket");
  19123. res.set_header("Connection", "notupgrade");
  19124. res.set_header("Sec-WebSocket-Accept",
  19125. detail::websocket_accept_key(
  19126. req.get_header_value("Sec-WebSocket-Key")));
  19127. });
  19128. auto port = svr.bind_to_any_port("localhost");
  19129. std::thread t([&]() { svr.listen_after_bind(); });
  19130. auto se = detail::scope_exit([&] {
  19131. svr.stop();
  19132. t.join();
  19133. });
  19134. svr.wait_until_ready();
  19135. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  19136. auto res = client.connect();
  19137. EXPECT_FALSE(res);
  19138. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  19139. EXPECT_FALSE(client.is_open());
  19140. }
  19141. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  19142. // The socket path doubles as the URL host, so it must not contain '/'.
  19143. const char *shard = getenv("GTEST_SHARD_INDEX");
  19144. const std::string sock_path =
  19145. shard ? std::string("httplib-ws-") + shard + ".sock"
  19146. : std::string("httplib-ws.sock");
  19147. std::remove(sock_path.c_str());
  19148. Server svr;
  19149. std::mutex mtx;
  19150. std::string received_host;
  19151. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  19152. {
  19153. std::lock_guard<std::mutex> lock(mtx);
  19154. received_host = req.get_header_value("Host");
  19155. }
  19156. std::string msg;
  19157. while (ws.read(msg)) {
  19158. ws.send(msg);
  19159. }
  19160. });
  19161. svr.set_address_family(AF_UNIX);
  19162. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  19163. auto se = detail::scope_exit([&] {
  19164. svr.stop();
  19165. t.join();
  19166. std::remove(sock_path.c_str());
  19167. });
  19168. svr.wait_until_ready();
  19169. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  19170. client.set_address_family(AF_UNIX);
  19171. ASSERT_TRUE(client.connect());
  19172. ASSERT_TRUE(client.send("hello"));
  19173. std::string msg;
  19174. ASSERT_TRUE(client.read(msg));
  19175. client.close();
  19176. {
  19177. std::lock_guard<std::mutex> lock(mtx);
  19178. // There is no host:port for a Unix socket, so the same "localhost"
  19179. // placeholder the HTTP client uses is expected.
  19180. EXPECT_EQ("localhost", received_host);
  19181. }
  19182. }
  19183. // Two threads must never parse WebSocket frames from the same stream.
  19184. // close() used to read the peer's Close reply with its own frame read, so it
  19185. // raced a reader thread that was in the middle of a payload: the payload loop
  19186. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  19187. // so bytes taken by close() were replaced with bytes from further along the
  19188. // stream. The message kept its length and silently changed content.
  19189. //
  19190. // The raw peer below sends a frame header plus part of the payload, waits for
  19191. // the handler to call close(), and only then sends the rest. Whichever thread
  19192. // would win the race for those bytes, the message must arrive intact, because
  19193. // close() must not touch the stream while read() owns it.
  19194. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  19195. #ifndef _WIN32
  19196. signal(SIGPIPE, SIG_IGN);
  19197. #endif
  19198. const size_t payload_len = 120; // fits the 7-bit length field
  19199. const size_t prefix_len = 8;
  19200. const int attempts = 8;
  19201. std::string expected(payload_len, '\0');
  19202. for (size_t i = 0; i < payload_len; i++) {
  19203. expected[i] = static_cast<char>('a' + i % 26);
  19204. }
  19205. std::atomic<bool> peer_stalled{false};
  19206. std::atomic<bool> handler_done{false};
  19207. std::mutex received_mutex;
  19208. std::vector<std::string> received;
  19209. // Bound every wait, so a regression fails the test instead of hanging the
  19210. // suite.
  19211. auto wait_for = [](const std::atomic<bool> &flag) {
  19212. for (int i = 0; i < 500 && !flag; i++) {
  19213. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  19214. }
  19215. };
  19216. Server svr;
  19217. svr.set_websocket_ping_interval(0);
  19218. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  19219. std::thread reader([&]() {
  19220. std::string msg;
  19221. while (ws.read(msg)) {
  19222. std::lock_guard<std::mutex> guard(received_mutex);
  19223. received.push_back(msg);
  19224. }
  19225. });
  19226. // Wait until the peer stalls mid-payload, so the reader thread is parked
  19227. // inside read_websocket_frame() when close() runs.
  19228. wait_for(peer_stalled);
  19229. ws.close();
  19230. reader.join();
  19231. handler_done = true;
  19232. });
  19233. auto port = svr.bind_to_any_port("127.0.0.1");
  19234. std::thread t([&]() { svr.listen_after_bind(); });
  19235. auto se = detail::scope_exit([&] {
  19236. svr.stop();
  19237. t.join();
  19238. });
  19239. svr.wait_until_ready();
  19240. auto send_bytes = [](socket_t s, const std::string &data) {
  19241. #ifdef _WIN32
  19242. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  19243. #else
  19244. auto n = ::send(s, data.data(), data.size(), 0);
  19245. #endif
  19246. return n == static_cast<decltype(n)>(data.size());
  19247. };
  19248. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  19249. // Every length used here fits the 7-bit length field.
  19250. auto masked_header = [](uint8_t first_byte, size_t len) {
  19251. std::string h;
  19252. h += static_cast<char>(first_byte);
  19253. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  19254. h.append(4, '\0'); // mask key
  19255. return h;
  19256. };
  19257. for (int attempt = 0; attempt < attempts; attempt++) {
  19258. peer_stalled = false;
  19259. handler_done = false;
  19260. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  19261. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  19262. auto se_sock = detail::scope_exit([&] {
  19263. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  19264. });
  19265. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  19266. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  19267. sockaddr_in addr{};
  19268. addr.sin_family = AF_INET;
  19269. addr.sin_port = htons(static_cast<uint16_t>(port));
  19270. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  19271. ASSERT_EQ(
  19272. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  19273. << "attempt " << attempt;
  19274. ASSERT_TRUE(send_bytes(sock,
  19275. "GET /ws HTTP/1.1\r\n"
  19276. "Host: 127.0.0.1\r\n"
  19277. "Upgrade: websocket\r\n"
  19278. "Connection: Upgrade\r\n"
  19279. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  19280. "Sec-WebSocket-Version: 13\r\n"
  19281. "\r\n"))
  19282. << "attempt " << attempt;
  19283. std::string response;
  19284. while (response.find("\r\n\r\n") == std::string::npos) {
  19285. char buf[512];
  19286. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  19287. if (n <= 0) { break; }
  19288. response.append(buf, static_cast<size_t>(n));
  19289. }
  19290. ASSERT_NE(std::string::npos, response.find(" 101 "))
  19291. << "attempt " << attempt;
  19292. // Send the header of a Binary message but only the first prefix_len bytes
  19293. // of its payload, leaving the reader thread stalled inside the payload.
  19294. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  19295. expected.substr(0, prefix_len)))
  19296. << "attempt " << attempt;
  19297. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  19298. peer_stalled = true;
  19299. // Let close() send its Close frame and park in its own read before the
  19300. // rest of the payload arrives, so both threads are waiting for it.
  19301. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  19302. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  19303. close_frame += static_cast<char>(0x03); // status 1000
  19304. close_frame += static_cast<char>(0xE8);
  19305. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  19306. << "attempt " << attempt;
  19307. // Closing the peer releases the reader thread even on the buggy path,
  19308. // where it waits for bytes another thread already consumed.
  19309. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  19310. detail::close_socket(sock);
  19311. sock = INVALID_SOCKET;
  19312. wait_for(handler_done);
  19313. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  19314. }
  19315. std::lock_guard<std::mutex> guard(received_mutex);
  19316. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  19317. << "a message in flight when close() ran was dropped";
  19318. for (size_t i = 0; i < received.size(); i++) {
  19319. EXPECT_EQ(expected, received[i]) << "message " << i;
  19320. }
  19321. }
  19322. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  19323. class WebSocketSSLIntegrationTest : public ::testing::Test {
  19324. protected:
  19325. void SetUp() override {
  19326. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  19327. SERVER_PRIVATE_KEY_FILE);
  19328. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  19329. std::string msg;
  19330. ws::ReadResult ret;
  19331. while ((ret = ws.read(msg))) {
  19332. if (ret == ws::Binary) {
  19333. ws.send(msg.data(), msg.size());
  19334. } else {
  19335. ws.send(msg);
  19336. }
  19337. }
  19338. });
  19339. port_ = server_->bind_to_any_port(HOST);
  19340. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  19341. server_->wait_until_ready();
  19342. }
  19343. void TearDown() override {
  19344. server_->stop();
  19345. if (server_thread_.joinable()) { server_thread_.join(); }
  19346. }
  19347. std::unique_ptr<SSLServer> server_;
  19348. std::thread server_thread_;
  19349. int port_ = 0;
  19350. };
  19351. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  19352. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  19353. "/ws-echo");
  19354. client.enable_server_certificate_verification(false);
  19355. ASSERT_TRUE(client.connect());
  19356. ASSERT_TRUE(client.is_open());
  19357. ASSERT_TRUE(client.send("Hello WSS"));
  19358. std::string msg;
  19359. EXPECT_EQ(ws::Text, client.read(msg));
  19360. EXPECT_EQ("Hello WSS", msg);
  19361. client.close();
  19362. }
  19363. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  19364. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  19365. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  19366. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  19367. // client (without calling close() first) is the only path that runs
  19368. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  19369. // bug exactly.
  19370. //
  19371. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  19372. // when linked against an instrumented libssl; run under Valgrind to catch it
  19373. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  19374. // suite (the freed session otherwise stalls on the close handshake) — this test
  19375. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  19376. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  19377. {
  19378. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  19379. "/ws-echo");
  19380. client.enable_server_certificate_verification(false);
  19381. client.set_read_timeout(2, 0);
  19382. client.set_write_timeout(2, 0);
  19383. ASSERT_TRUE(client.connect());
  19384. ASSERT_TRUE(client.is_open());
  19385. ASSERT_TRUE(client.send("still open"));
  19386. // Intentionally do NOT call client.close(): leaving scope runs
  19387. // shutdown_and_close() with the WebSocket still open, which must send the
  19388. // close frame while the TLS session is still alive.
  19389. }
  19390. }
  19391. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  19392. // shutdown_and_close() at the start of connect(), reproducing the same
  19393. // use-after-free within the test body rather than at scope exit. The second
  19394. // connect must succeed and echo, proving the close handshake ran over a live
  19395. // session. See the note above about memory-tool requirements.
  19396. TEST_F(WebSocketSSLIntegrationTest,
  19397. ReconnectWhileOpenSendsCloseOverLiveSession) {
  19398. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  19399. "/ws-echo");
  19400. client.enable_server_certificate_verification(false);
  19401. client.set_read_timeout(2, 0);
  19402. client.set_write_timeout(2, 0);
  19403. ASSERT_TRUE(client.connect());
  19404. ASSERT_TRUE(client.is_open());
  19405. ASSERT_TRUE(client.send("still open"));
  19406. // Reconnect without closing first: connect() calls shutdown_and_close() on
  19407. // the still-open connection, which must not touch a freed TLS session.
  19408. ASSERT_TRUE(client.connect());
  19409. ASSERT_TRUE(client.is_open());
  19410. ASSERT_TRUE(client.send("after reconnect"));
  19411. std::string msg;
  19412. EXPECT_EQ(ws::Text, client.read(msg));
  19413. EXPECT_EQ("after reconnect", msg);
  19414. client.close();
  19415. }
  19416. #endif
  19417. #ifdef CPPHTTPLIB_SSL_ENABLED
  19418. class WebSocketSSLCATest : public ::testing::Test {
  19419. protected:
  19420. void SetUp() override {
  19421. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  19422. SERVER_PRIVATE_KEY_FILE);
  19423. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  19424. std::string msg;
  19425. while (ws.read(msg)) {
  19426. ws.send(msg);
  19427. }
  19428. });
  19429. port_ = server_->bind_to_any_port("127.0.0.1");
  19430. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  19431. server_->wait_until_ready();
  19432. }
  19433. void TearDown() override {
  19434. server_->stop();
  19435. if (server_thread_.joinable()) { server_thread_.join(); }
  19436. }
  19437. std::string url() const {
  19438. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  19439. }
  19440. std::unique_ptr<SSLServer> server_;
  19441. std::thread server_thread_;
  19442. int port_ = 0;
  19443. };
  19444. // A custom CA loaded as PEM verifies the server with full certificate
  19445. // verification enabled
  19446. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  19447. ws::WebSocketClient client(url());
  19448. std::string cert;
  19449. read_file(SERVER_CERT2_FILE, cert);
  19450. client.load_ca_cert_store(cert.c_str(), cert.size());
  19451. ASSERT_TRUE(client.connect());
  19452. ASSERT_TRUE(client.send("hello"));
  19453. std::string msg;
  19454. EXPECT_EQ(ws::Text, client.read(msg));
  19455. EXPECT_EQ("hello", msg);
  19456. client.close();
  19457. }
  19458. // A custom CA that does not cover the server must fail verification (the
  19459. // custom CA is exclusive; system certs are not loaded alongside it)
  19460. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  19461. ws::WebSocketClient client(url());
  19462. std::string cert;
  19463. read_file(CLIENT_CA_CERT_FILE, cert);
  19464. client.load_ca_cert_store(cert.c_str(), cert.size());
  19465. auto res = client.connect();
  19466. ASSERT_FALSE(res);
  19467. EXPECT_EQ(Error::SSLServerVerification, res.error());
  19468. EXPECT_EQ(-1, res.status());
  19469. EXPECT_NE(0u, res.ssl_backend_error());
  19470. }
  19471. // The same CA as a file path rather than PEM in memory
  19472. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  19473. ws::WebSocketClient client(url());
  19474. client.set_ca_cert_path(SERVER_CERT2_FILE);
  19475. ASSERT_TRUE(client.connect());
  19476. ASSERT_TRUE(client.send("hello"));
  19477. std::string msg;
  19478. EXPECT_EQ(ws::Text, client.read(msg));
  19479. EXPECT_EQ("hello", msg);
  19480. client.close();
  19481. }
  19482. // ...and a CA file that does not cover the server still fails, so it is the
  19483. // path above that decides the outcome
  19484. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  19485. ws::WebSocketClient client(url());
  19486. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  19487. ASSERT_FALSE(client.connect());
  19488. }
  19489. // Regression test: reconnecting with a native custom CA store used to reuse
  19490. // a store handle the previous TLS context had already freed (use-after-free
  19491. // under the OpenSSL backend). The context now lives as long as the client.
  19492. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  19493. ws::WebSocketClient client(url());
  19494. std::string cert;
  19495. read_file(SERVER_CERT2_FILE, cert);
  19496. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  19497. ASSERT_TRUE(client.connect());
  19498. client.close();
  19499. ASSERT_TRUE(client.connect());
  19500. ASSERT_TRUE(client.send("again"));
  19501. std::string msg;
  19502. EXPECT_EQ(ws::Text, client.read(msg));
  19503. EXPECT_EQ("again", msg);
  19504. client.close();
  19505. }
  19506. // Regression test: a certificate with a trusted chain but no identity match
  19507. // for the server IP must be rejected. The Mbed TLS backend used to skip
  19508. // verification entirely for IP hosts, so this connection succeeded there.
  19509. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  19510. // chain verification while the identity check must still fail.
  19511. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  19512. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19513. ASSERT_TRUE(svr.is_valid());
  19514. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  19515. std::string msg;
  19516. while (ws.read(msg)) {
  19517. ws.send(msg);
  19518. }
  19519. });
  19520. auto port = svr.bind_to_any_port("127.0.0.1");
  19521. auto t = std::thread([&]() { svr.listen_after_bind(); });
  19522. auto se = detail::scope_exit([&] {
  19523. svr.stop();
  19524. t.join();
  19525. });
  19526. svr.wait_until_ready();
  19527. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  19528. "/echo");
  19529. std::string cert;
  19530. read_file(SERVER_CERT_FILE, cert);
  19531. client.load_ca_cert_store(cert.c_str(), cert.size());
  19532. ASSERT_FALSE(client.connect());
  19533. }
  19534. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  19535. // SNI, so nothing binds the host name to the TLS session. These bind the
  19536. // server to "localhost" instead, the only shape that exercises the SNI and
  19537. // hostname-verification path with certificate verification left enabled.
  19538. class WebSocketSSLDnsHostTest : public ::testing::Test {
  19539. protected:
  19540. void Start(const char *cert_file) {
  19541. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  19542. SERVER_PRIVATE_KEY_FILE);
  19543. ASSERT_TRUE(server_->is_valid());
  19544. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  19545. std::string msg;
  19546. while (ws.read(msg)) {
  19547. ws.send(msg);
  19548. }
  19549. });
  19550. port_ = server_->bind_to_any_port("localhost");
  19551. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  19552. server_->wait_until_ready();
  19553. }
  19554. void TearDown() override {
  19555. if (server_) { server_->stop(); }
  19556. if (server_thread_.joinable()) { server_thread_.join(); }
  19557. }
  19558. std::string url() const {
  19559. return "wss://localhost:" + std::to_string(port_) + "/echo";
  19560. }
  19561. std::unique_ptr<SSLServer> server_;
  19562. std::thread server_thread_;
  19563. int port_ = 0;
  19564. };
  19565. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  19566. // out and the connection is usable
  19567. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  19568. Start(SERVER_CERT2_FILE);
  19569. ws::WebSocketClient client(url());
  19570. client.set_ca_cert_path(SERVER_CERT2_FILE);
  19571. ASSERT_TRUE(client.connect());
  19572. ASSERT_TRUE(client.send("hello"));
  19573. std::string msg;
  19574. EXPECT_EQ(ws::Text, client.read(msg));
  19575. EXPECT_EQ("hello", msg);
  19576. client.close();
  19577. }
  19578. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  19579. // while the identity check must still reject "localhost"
  19580. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  19581. Start(SERVER_CERT_FILE);
  19582. ws::WebSocketClient client(url());
  19583. client.set_ca_cert_path(SERVER_CERT_FILE);
  19584. auto res = client.connect();
  19585. ASSERT_FALSE(res);
  19586. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  19587. EXPECT_EQ(-1, res.status());
  19588. }
  19589. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  19590. // disabled: the chain is still checked, only the identity check is skipped
  19591. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  19592. Start(SERVER_CERT_FILE);
  19593. ws::WebSocketClient client(url());
  19594. client.set_ca_cert_path(SERVER_CERT_FILE);
  19595. client.enable_server_hostname_verification(false);
  19596. ASSERT_TRUE(client.connect());
  19597. ASSERT_TRUE(client.send("hello"));
  19598. std::string msg;
  19599. EXPECT_EQ(ws::Text, client.read(msg));
  19600. EXPECT_EQ("hello", msg);
  19601. client.close();
  19602. }
  19603. // A CA that did not sign the server certificate fails the chain, even though
  19604. // the name would match
  19605. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  19606. Start(SERVER_CERT2_FILE);
  19607. ws::WebSocketClient client(url());
  19608. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  19609. ASSERT_FALSE(client.connect());
  19610. }
  19611. // With verification disabled, neither the chain nor the name is checked
  19612. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  19613. Start(SERVER_CERT_FILE);
  19614. ws::WebSocketClient client(url());
  19615. client.enable_server_certificate_verification(false);
  19616. ASSERT_TRUE(client.connect());
  19617. ASSERT_TRUE(client.send("hello"));
  19618. std::string msg;
  19619. EXPECT_EQ(ws::Text, client.read(msg));
  19620. EXPECT_EQ("hello", msg);
  19621. client.close();
  19622. }
  19623. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  19624. protected:
  19625. void SetUp() override {
  19626. server_ = httplib::detail::make_unique<SSLServer>(
  19627. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  19628. ASSERT_TRUE(server_->is_valid());
  19629. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  19630. std::string msg;
  19631. while (ws.read(msg)) {
  19632. ws.send(msg);
  19633. }
  19634. });
  19635. port_ = server_->bind_to_any_port("localhost");
  19636. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  19637. server_->wait_until_ready();
  19638. }
  19639. void TearDown() override {
  19640. server_->stop();
  19641. if (server_thread_.joinable()) { server_thread_.join(); }
  19642. }
  19643. std::string url() const {
  19644. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  19645. }
  19646. void ConnectWithClientCert(const std::string &client_cert_file,
  19647. const std::string &client_private_key_file,
  19648. const char *private_key_password) {
  19649. std::string cert_pem, key_pem;
  19650. read_file(client_cert_file, cert_pem);
  19651. read_file(client_private_key_file, key_pem);
  19652. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  19653. key_pem.c_str(), key_pem.size(),
  19654. private_key_password};
  19655. ws::WebSocketClient client(url(), pem);
  19656. ASSERT_TRUE(client.is_valid());
  19657. client.enable_server_certificate_verification(false);
  19658. ASSERT_TRUE(client.connect());
  19659. ASSERT_TRUE(client.send("hello"));
  19660. std::string msg;
  19661. EXPECT_EQ(ws::Text, client.read(msg));
  19662. EXPECT_EQ("hello", msg);
  19663. client.close();
  19664. }
  19665. std::unique_ptr<SSLServer> server_;
  19666. std::thread server_thread_;
  19667. int port_ = 0;
  19668. };
  19669. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  19670. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  19671. }
  19672. // Control for the tests above: the fixture's server really does require a
  19673. // client certificate, so it is the PEM the constructor installed that decides
  19674. // the outcome.
  19675. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  19676. ws::WebSocketClient client(url());
  19677. ASSERT_TRUE(client.is_valid());
  19678. client.enable_server_certificate_verification(false);
  19679. EXPECT_FALSE(client.connect());
  19680. }
  19681. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  19682. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  19683. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  19684. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  19685. }
  19686. #endif
  19687. #if !defined(_WIN32)
  19688. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  19689. auto secret_dir = std::string("./symlink_test_secret");
  19690. auto served_dir = std::string("./symlink_test_served");
  19691. auto secret_file = secret_dir + "/secret.txt";
  19692. auto symlink_path = served_dir + "/escape";
  19693. // Setup: create directories and files
  19694. mkdir(secret_dir.c_str(), 0755);
  19695. mkdir(served_dir.c_str(), 0755);
  19696. {
  19697. std::ofstream ofs(secret_file);
  19698. ofs << "SECRET_DATA";
  19699. }
  19700. // Create symlink using absolute path so it resolves correctly
  19701. #ifdef PATH_MAX
  19702. char abs_secret[PATH_MAX];
  19703. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  19704. #else
  19705. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  19706. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  19707. ASSERT_NE(nullptr, abs_secret);
  19708. #endif
  19709. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  19710. auto se = detail::scope_exit([&] {
  19711. unlink(symlink_path.c_str());
  19712. unlink(secret_file.c_str());
  19713. rmdir(served_dir.c_str());
  19714. rmdir(secret_dir.c_str());
  19715. });
  19716. Server svr;
  19717. svr.set_mount_point("/", served_dir);
  19718. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  19719. auto se2 = detail::scope_exit([&] {
  19720. svr.stop();
  19721. listen_thread.join();
  19722. });
  19723. svr.wait_until_ready();
  19724. Client cli("localhost", PORT);
  19725. // Symlink pointing outside base dir should be blocked
  19726. auto res = cli.Get("/escape/secret.txt");
  19727. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19728. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  19729. }
  19730. #endif
  19731. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  19732. // A GET request with Content-Length to a static file handler must have its
  19733. // body drained before the keep-alive connection is reused. Otherwise the
  19734. // unread body bytes are interpreted as the next HTTP request.
  19735. //
  19736. // The body is sent AFTER receiving the first response (as in the original
  19737. // PoC) so that the stream_line_reader cannot buffer it together with the
  19738. // headers of the first request.
  19739. Server svr;
  19740. svr.set_mount_point("/", "./www");
  19741. std::atomic<int> smuggled_count(0);
  19742. svr.Get("/smuggled", [&](const Request &, Response &res) {
  19743. smuggled_count++;
  19744. res.set_content("oops", "text/plain");
  19745. });
  19746. auto port = svr.bind_to_any_port("localhost");
  19747. thread t = thread([&] { svr.listen_after_bind(); });
  19748. auto se = detail::scope_exit([&] {
  19749. svr.stop();
  19750. t.join();
  19751. });
  19752. svr.wait_until_ready();
  19753. auto error = Error::Success;
  19754. auto sock = detail::create_client_socket(
  19755. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  19756. /*connection_timeout_sec=*/2, 0,
  19757. /*read_timeout_sec=*/2, 0,
  19758. /*write_timeout_sec=*/2, 0, std::string(), error);
  19759. ASSERT_NE(INVALID_SOCKET, sock);
  19760. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  19761. // The "smuggled" request will be sent as the body of the outer GET
  19762. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  19763. "Host: localhost\r\n"
  19764. "Connection: close\r\n"
  19765. "\r\n";
  19766. // Step 1: Send only the outer request headers (no body yet)
  19767. std::string outer_headers = "GET /file HTTP/1.1\r\n"
  19768. "Host: localhost\r\n"
  19769. "Content-Length: " +
  19770. std::to_string(smuggled.size()) +
  19771. "\r\n"
  19772. "\r\n";
  19773. auto sent = send(sock, outer_headers.data(), outer_headers.size(), 0);
  19774. ASSERT_EQ(static_cast<ssize_t>(outer_headers.size()), sent);
  19775. // Step 2: Read the first response (server serves file without reading body)
  19776. std::string first_response;
  19777. char buf[4096];
  19778. for (;;) {
  19779. auto n = recv(sock, buf, sizeof(buf), 0);
  19780. if (n <= 0) break;
  19781. first_response.append(buf, static_cast<size_t>(n));
  19782. // Stop once we have a complete response (headers + body)
  19783. auto hdr_end = first_response.find("\r\n\r\n");
  19784. if (hdr_end != std::string::npos) {
  19785. // Check for Content-Length to know when the body is complete
  19786. auto cl_pos = first_response.find("Content-Length:");
  19787. if (cl_pos != std::string::npos) {
  19788. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  19789. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  19790. auto cl = std::stoul(
  19791. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  19792. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  19793. } else {
  19794. break; // No Content-Length, assume headers-only response
  19795. }
  19796. }
  19797. }
  19798. ASSERT_TRUE(first_response.find("HTTP/1.1 200") != std::string::npos);
  19799. // Step 3: Now send the body, which looks like a new HTTP request.
  19800. // On a vulnerable server the keep-alive loop reads this as a second request.
  19801. sent = send(sock, smuggled.data(), smuggled.size(), 0);
  19802. ASSERT_EQ(static_cast<ssize_t>(smuggled.size()), sent);
  19803. // Step 4: Try to read a second response (should NOT exist after fix)
  19804. std::string second_response;
  19805. for (;;) {
  19806. auto n = recv(sock, buf, sizeof(buf), 0);
  19807. if (n <= 0) break;
  19808. second_response.append(buf, static_cast<size_t>(n));
  19809. }
  19810. // The smuggled request must NOT have been processed
  19811. EXPECT_EQ(0, smuggled_count.load());
  19812. }
  19813. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  19814. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  19815. // must be rejected with 400 Bad Request.
  19816. Server svr;
  19817. svr.Post("/test", [&](const Request &, Response &res) {
  19818. res.set_content("ok", "text/plain");
  19819. });
  19820. thread t = thread([&] { svr.listen(HOST, PORT); });
  19821. auto se = detail::scope_exit([&] {
  19822. svr.stop();
  19823. t.join();
  19824. ASSERT_FALSE(svr.is_running());
  19825. });
  19826. svr.wait_until_ready();
  19827. // Exact "chunked"
  19828. {
  19829. auto req = "POST /test HTTP/1.1\r\n"
  19830. "Host: localhost\r\n"
  19831. "Content-Length: 5\r\n"
  19832. "Transfer-Encoding: chunked\r\n"
  19833. "Connection: close\r\n"
  19834. "\r\n"
  19835. "hello";
  19836. std::string response;
  19837. ASSERT_TRUE(send_request(1, req, &response));
  19838. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  19839. response.substr(0, response.find("\r\n")));
  19840. }
  19841. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  19842. {
  19843. auto req = "POST /test HTTP/1.1\r\n"
  19844. "Host: localhost\r\n"
  19845. "Content-Length: 5\r\n"
  19846. "Transfer-Encoding: gzip, chunked\r\n"
  19847. "Connection: close\r\n"
  19848. "\r\n"
  19849. "hello";
  19850. std::string response;
  19851. ASSERT_TRUE(send_request(1, req, &response));
  19852. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  19853. response.substr(0, response.find("\r\n")));
  19854. }
  19855. }
  19856. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  19857. Server svr;
  19858. svr.Post("/test", [&](const Request &, Response &res) {
  19859. res.set_content("ok", "text/plain");
  19860. });
  19861. thread t = thread([&] { svr.listen(HOST, PORT); });
  19862. auto se = detail::scope_exit([&] {
  19863. svr.stop();
  19864. t.join();
  19865. ASSERT_FALSE(svr.is_running());
  19866. });
  19867. svr.wait_until_ready();
  19868. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  19869. // length cannot be determined, so the server must answer 400 and close
  19870. // rather than treat the request as bodyless and leave the body in the
  19871. // socket for the next request to pick up.
  19872. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  19873. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  19874. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  19875. std::string response;
  19876. ASSERT_TRUE(send_request(1, req, &response));
  19877. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  19878. response.substr(0, response.find("\r\n")))
  19879. << transfer_encoding;
  19880. }
  19881. // RFC 9110 5.3: the codings may also be split across several
  19882. // Transfer-Encoding lines, which combine in the order they were received.
  19883. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  19884. // just like the single-line "chunked, gzip" above.
  19885. {
  19886. auto req = "POST /test HTTP/1.1\r\n"
  19887. "Host: localhost\r\n"
  19888. "Transfer-Encoding: chunked\r\n"
  19889. "Transfer-Encoding: gzip\r\n"
  19890. "\r\n"
  19891. "0\r\n\r\n";
  19892. std::string response;
  19893. ASSERT_TRUE(send_request(1, req, &response));
  19894. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  19895. response.substr(0, response.find("\r\n")));
  19896. }
  19897. // A sequence ending in chunked stays valid.
  19898. auto req = "POST /test HTTP/1.1\r\n"
  19899. "Host: localhost\r\n"
  19900. "Transfer-Encoding: gzip, chunked\r\n"
  19901. "Connection: close\r\n"
  19902. "\r\n"
  19903. "0\r\n\r\n";
  19904. std::string response;
  19905. ASSERT_TRUE(send_request(1, req, &response));
  19906. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  19907. // ...including when it is spread over several lines.
  19908. auto split_req = "POST /test HTTP/1.1\r\n"
  19909. "Host: localhost\r\n"
  19910. "Transfer-Encoding: gzip\r\n"
  19911. "Transfer-Encoding: chunked\r\n"
  19912. "Connection: close\r\n"
  19913. "\r\n"
  19914. "0\r\n\r\n";
  19915. std::string split_response;
  19916. ASSERT_TRUE(send_request(1, split_req, &split_response));
  19917. EXPECT_EQ("HTTP/1.1 200 OK",
  19918. split_response.substr(0, split_response.find("\r\n")));
  19919. }
  19920. // Regression for issue #2450: a DELETE without Content-Length on a
  19921. // keep-alive connection must not let the post-response drain consume the
  19922. // next request's bytes.
  19923. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  19924. Server svr;
  19925. std::atomic<int> delete_count(0);
  19926. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  19927. delete_count++;
  19928. res.status = StatusCode::NoContent_204;
  19929. });
  19930. auto port = svr.bind_to_any_port(HOST);
  19931. thread t = thread([&] { svr.listen_after_bind(); });
  19932. auto se = detail::scope_exit([&] {
  19933. svr.stop();
  19934. t.join();
  19935. });
  19936. svr.wait_until_ready();
  19937. auto error = Error::Success;
  19938. auto sock = detail::create_client_socket(
  19939. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  19940. /*connection_timeout_sec=*/2, 0,
  19941. /*read_timeout_sec=*/2, 0,
  19942. /*write_timeout_sec=*/2, 0, std::string(), error);
  19943. ASSERT_NE(INVALID_SOCKET, sock);
  19944. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  19945. auto send_request_and_read_response = [&](const std::string &req,
  19946. std::string &out) -> bool {
  19947. auto sent = send(sock, req.data(), req.size(), 0);
  19948. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  19949. char buf[4096];
  19950. for (;;) {
  19951. auto n = recv(sock, buf, sizeof(buf), 0);
  19952. if (n <= 0) { return !out.empty(); }
  19953. out.append(buf, static_cast<size_t>(n));
  19954. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  19955. }
  19956. };
  19957. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  19958. "Host: localhost\r\n"
  19959. "\r\n";
  19960. std::string resp1;
  19961. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  19962. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  19963. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  19964. "Host: localhost\r\n"
  19965. "Connection: close\r\n"
  19966. "\r\n";
  19967. std::string resp2;
  19968. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  19969. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  19970. EXPECT_EQ(2, delete_count.load());
  19971. }
  19972. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  19973. Server svr;
  19974. svr.Post("/ingest", [&](const Request &, Response &res,
  19975. const ContentReader &content_reader) {
  19976. auto consumed = content_reader([](const char *, size_t) { return false; });
  19977. EXPECT_FALSE(consumed);
  19978. res.status = StatusCode::Conflict_409;
  19979. res.set_header("Connection", "close");
  19980. });
  19981. auto port = svr.bind_to_any_port(HOST);
  19982. thread t = thread([&] { svr.listen_after_bind(); });
  19983. auto se = detail::scope_exit([&] {
  19984. svr.stop();
  19985. t.join();
  19986. });
  19987. svr.wait_until_ready();
  19988. auto error = Error::Success;
  19989. auto sock = detail::create_client_socket(
  19990. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  19991. /*connection_timeout_sec=*/2, 0,
  19992. /*read_timeout_sec=*/1, 0,
  19993. /*write_timeout_sec=*/2, 0, std::string(), error);
  19994. ASSERT_NE(INVALID_SOCKET, sock);
  19995. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  19996. std::string request = "POST /ingest HTTP/1.1\r\n"
  19997. "Host: localhost\r\n"
  19998. "Transfer-Encoding: chunked\r\n"
  19999. "\r\n"
  20000. "4\r\n"
  20001. "data\r\n";
  20002. auto sent = send(sock, request.data(), request.size(), 0);
  20003. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  20004. std::string response;
  20005. ssize_t received = 0;
  20006. do {
  20007. char buf[4096];
  20008. received = recv(sock, buf, sizeof(buf), 0);
  20009. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  20010. } while (received > 0);
  20011. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  20012. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  20013. EXPECT_EQ(0, received);
  20014. }
  20015. namespace no_proxy_test {
  20016. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  20017. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  20018. // calling listen().
  20019. class ScopedServer {
  20020. public:
  20021. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  20022. ~ScopedServer() {
  20023. svr_.stop();
  20024. if (th_.joinable()) { th_.join(); }
  20025. }
  20026. Server &svr() { return svr_; }
  20027. int port() const { return port_; }
  20028. void listen() {
  20029. th_ = std::thread([this] { svr_.listen_after_bind(); });
  20030. svr_.wait_until_ready();
  20031. }
  20032. private:
  20033. Server svr_;
  20034. std::thread th_;
  20035. int port_ = 0;
  20036. };
  20037. class ProxyAndTargetServers {
  20038. public:
  20039. ProxyAndTargetServers() {
  20040. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  20041. proxy_hits_++;
  20042. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  20043. res.set_content("via-proxy", "text/plain");
  20044. });
  20045. target_.Get(".*", [this](const Request &req, Response &res) {
  20046. target_hits_++;
  20047. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  20048. res.set_content("direct", "text/plain");
  20049. });
  20050. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  20051. target_port_ = target_.bind_to_any_port("127.0.0.1");
  20052. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  20053. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  20054. proxy_mock_.wait_until_ready();
  20055. target_.wait_until_ready();
  20056. }
  20057. ~ProxyAndTargetServers() {
  20058. proxy_mock_.stop();
  20059. target_.stop();
  20060. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  20061. if (target_thread_.joinable()) { target_thread_.join(); }
  20062. }
  20063. Server &proxy_mock() { return proxy_mock_; }
  20064. Server &target() { return target_; }
  20065. int proxy_port() const { return proxy_port_; }
  20066. int target_port() const { return target_port_; }
  20067. int proxy_hits() const { return proxy_hits_.load(); }
  20068. int target_hits() const { return target_hits_.load(); }
  20069. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  20070. void reset_counters() {
  20071. proxy_hits_ = 0;
  20072. target_hits_ = 0;
  20073. last_had_proxy_authz_ = false;
  20074. }
  20075. private:
  20076. Server proxy_mock_;
  20077. Server target_;
  20078. std::thread proxy_thread_;
  20079. std::thread target_thread_;
  20080. int proxy_port_ = 0;
  20081. int target_port_ = 0;
  20082. std::atomic<int> proxy_hits_{0};
  20083. std::atomic<int> target_hits_{0};
  20084. std::atomic<bool> last_had_proxy_authz_{false};
  20085. };
  20086. inline std::unique_ptr<Client> make_client(const std::string &host,
  20087. ProxyAndTargetServers &s) {
  20088. auto cli = detail::make_unique<Client>(host, s.target_port());
  20089. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  20090. cli->set_proxy("127.0.0.1", s.proxy_port());
  20091. return cli;
  20092. }
  20093. } // namespace no_proxy_test
  20094. using no_proxy_test::make_client;
  20095. using no_proxy_test::ProxyAndTargetServers;
  20096. TEST(NoProxyTest, ExactHostnameBypasses) {
  20097. ProxyAndTargetServers s;
  20098. auto cli = make_client("example.com", s);
  20099. cli->set_no_proxy({"example.com"});
  20100. auto res = cli->Get("/");
  20101. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20102. EXPECT_EQ(0, s.proxy_hits());
  20103. EXPECT_EQ(1, s.target_hits());
  20104. }
  20105. TEST(NoProxyTest, SubdomainBypasses) {
  20106. ProxyAndTargetServers s;
  20107. auto cli = make_client("foo.example.com", s);
  20108. cli->set_no_proxy({"example.com"});
  20109. auto res = cli->Get("/");
  20110. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20111. EXPECT_EQ(0, s.proxy_hits());
  20112. EXPECT_EQ(1, s.target_hits());
  20113. }
  20114. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  20115. // Regression guard: "evilexample.com" must not be considered a subdomain
  20116. // of "example.com". Without the dot-boundary rule, a naive endsWith
  20117. // check would let traffic bypass the proxy and leak credentials direct
  20118. // to the attacker host.
  20119. ProxyAndTargetServers s;
  20120. auto cli = make_client("evilexample.com", s);
  20121. cli->set_no_proxy({"example.com"});
  20122. auto res = cli->Get("/");
  20123. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20124. EXPECT_GE(s.proxy_hits(), 1);
  20125. EXPECT_EQ(0, s.target_hits());
  20126. }
  20127. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  20128. ProxyAndTargetServers s;
  20129. auto cli = make_client("example.com.evil.com", s);
  20130. cli->set_no_proxy({"example.com"});
  20131. auto res = cli->Get("/");
  20132. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20133. EXPECT_GE(s.proxy_hits(), 1);
  20134. EXPECT_EQ(0, s.target_hits());
  20135. }
  20136. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  20137. ProxyAndTargetServers s;
  20138. auto cli = make_client("example.com", s);
  20139. cli->set_no_proxy({".example.com"});
  20140. auto res = cli->Get("/");
  20141. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20142. EXPECT_EQ(0, s.proxy_hits());
  20143. EXPECT_EQ(1, s.target_hits());
  20144. }
  20145. TEST(NoProxyTest, CaseInsensitiveHostname) {
  20146. ProxyAndTargetServers s;
  20147. auto cli = make_client("Example.COM", s);
  20148. cli->set_no_proxy({"EXAMPLE.com"});
  20149. auto res = cli->Get("/");
  20150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20151. EXPECT_EQ(0, s.proxy_hits());
  20152. EXPECT_EQ(1, s.target_hits());
  20153. }
  20154. TEST(NoProxyTest, TrailingDotIsNormalized) {
  20155. ProxyAndTargetServers s;
  20156. auto cli = make_client("example.com.", s);
  20157. cli->set_no_proxy({"example.com"});
  20158. auto res = cli->Get("/");
  20159. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20160. EXPECT_EQ(0, s.proxy_hits());
  20161. EXPECT_EQ(1, s.target_hits());
  20162. }
  20163. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  20164. // Trailing dots must be normalized on BOTH sides — host and entry.
  20165. // An implementation that only strips the host-side trailing dot would
  20166. // fail to match host "example.com" against entry "example.com." because
  20167. // a literal substring search would compare 11 chars against 12.
  20168. ProxyAndTargetServers s;
  20169. auto cli = make_client("example.com", s);
  20170. cli->set_no_proxy({"example.com."});
  20171. auto res = cli->Get("/");
  20172. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20173. EXPECT_EQ(0, s.proxy_hits());
  20174. EXPECT_EQ(1, s.target_hits());
  20175. }
  20176. TEST(NoProxyTest, WildcardBypassesEverything) {
  20177. ProxyAndTargetServers s;
  20178. auto cli = make_client("anything.invalid.test", s);
  20179. cli->set_no_proxy({"*"});
  20180. auto res = cli->Get("/");
  20181. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20182. EXPECT_EQ(0, s.proxy_hits());
  20183. EXPECT_EQ(1, s.target_hits());
  20184. }
  20185. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  20186. ProxyAndTargetServers s;
  20187. Client cli("127.0.0.1", s.target_port());
  20188. cli.set_proxy("127.0.0.1", s.proxy_port());
  20189. cli.set_no_proxy({"127.0.0.1"});
  20190. auto res = cli.Get("/");
  20191. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20192. EXPECT_EQ(0, s.proxy_hits());
  20193. EXPECT_EQ(1, s.target_hits());
  20194. }
  20195. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  20196. ProxyAndTargetServers s;
  20197. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  20198. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  20199. cli.set_proxy("127.0.0.1", s.proxy_port());
  20200. cli.set_no_proxy({"::1"});
  20201. auto res = cli.Get("/");
  20202. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20203. EXPECT_EQ(0, s.proxy_hits());
  20204. EXPECT_EQ(1, s.target_hits());
  20205. }
  20206. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  20207. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  20208. // must still be recognized as IPv6 for CIDR matching. Implementations
  20209. // that detect IPv6 only when the host begins with '[' would parse the
  20210. // host as a hostname and miss the match.
  20211. ProxyAndTargetServers s;
  20212. Client cli("fe80::1", s.target_port());
  20213. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  20214. cli.set_proxy("127.0.0.1", s.proxy_port());
  20215. cli.set_no_proxy({"fe80::/10"});
  20216. auto res = cli.Get("/");
  20217. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20218. EXPECT_EQ(0, s.proxy_hits());
  20219. EXPECT_EQ(1, s.target_hits());
  20220. }
  20221. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  20222. ProxyAndTargetServers s;
  20223. Client cli("::1", s.target_port());
  20224. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  20225. cli.set_proxy("127.0.0.1", s.proxy_port());
  20226. cli.set_no_proxy({"[::1]"});
  20227. auto res = cli.Get("/");
  20228. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20229. EXPECT_EQ(0, s.proxy_hits());
  20230. EXPECT_EQ(1, s.target_hits());
  20231. }
  20232. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  20233. ProxyAndTargetServers s;
  20234. Client cli("fe80::1", s.target_port());
  20235. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  20236. cli.set_proxy("127.0.0.1", s.proxy_port());
  20237. cli.set_no_proxy({"[fe80::]/10"});
  20238. auto res = cli.Get("/");
  20239. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20240. EXPECT_EQ(0, s.proxy_hits());
  20241. EXPECT_EQ(1, s.target_hits());
  20242. }
  20243. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  20244. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  20245. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  20246. // tricks via address-family conversion.
  20247. ProxyAndTargetServers s;
  20248. Client cli("::ffff:127.0.0.1", s.target_port());
  20249. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  20250. cli.set_proxy("127.0.0.1", s.proxy_port());
  20251. cli.set_no_proxy({"127.0.0.1"});
  20252. auto res = cli.Get("/");
  20253. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20254. EXPECT_GE(s.proxy_hits(), 1);
  20255. EXPECT_EQ(0, s.target_hits());
  20256. }
  20257. TEST(NoProxyTest, IPv4CidrMatch) {
  20258. ProxyAndTargetServers s;
  20259. Client cli("127.0.0.1", s.target_port());
  20260. cli.set_proxy("127.0.0.1", s.proxy_port());
  20261. cli.set_no_proxy({"127.0.0.0/8"});
  20262. auto res = cli.Get("/");
  20263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20264. EXPECT_EQ(0, s.proxy_hits());
  20265. EXPECT_EQ(1, s.target_hits());
  20266. }
  20267. TEST(NoProxyTest, IPv4CidrNonMatch) {
  20268. ProxyAndTargetServers s;
  20269. Client cli("127.0.0.1", s.target_port());
  20270. cli.set_proxy("127.0.0.1", s.proxy_port());
  20271. cli.set_no_proxy({"10.0.0.0/8"});
  20272. auto res = cli.Get("/");
  20273. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20274. EXPECT_GE(s.proxy_hits(), 1);
  20275. EXPECT_EQ(0, s.target_hits());
  20276. }
  20277. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  20278. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  20279. // IPv4 target matches.
  20280. ProxyAndTargetServers s;
  20281. Client cli("127.0.0.1", s.target_port());
  20282. cli.set_proxy("127.0.0.1", s.proxy_port());
  20283. cli.set_no_proxy({"0.0.0.0/0"});
  20284. auto res = cli.Get("/");
  20285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20286. EXPECT_EQ(0, s.proxy_hits());
  20287. EXPECT_EQ(1, s.target_hits());
  20288. }
  20289. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  20290. ProxyAndTargetServers s;
  20291. Client cli("127.0.0.1", s.target_port());
  20292. cli.set_proxy("127.0.0.1", s.proxy_port());
  20293. cli.set_no_proxy({"127.0.0.1"});
  20294. auto res = cli.Get("/");
  20295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20296. EXPECT_EQ(0, s.proxy_hits());
  20297. EXPECT_EQ(1, s.target_hits());
  20298. }
  20299. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  20300. ProxyAndTargetServers s;
  20301. Client cli("127.0.0.1", s.target_port());
  20302. cli.set_proxy("127.0.0.1", s.proxy_port());
  20303. cli.set_no_proxy({"127.0.0.0/33"});
  20304. auto res = cli.Get("/");
  20305. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20306. EXPECT_GE(s.proxy_hits(), 1);
  20307. EXPECT_EQ(0, s.target_hits());
  20308. }
  20309. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  20310. // Empty prefix after the slash must be rejected, not silently treated as /32.
  20311. ProxyAndTargetServers s;
  20312. Client cli("127.0.0.1", s.target_port());
  20313. cli.set_proxy("127.0.0.1", s.proxy_port());
  20314. cli.set_no_proxy({"127.0.0.1/"});
  20315. auto res = cli.Get("/");
  20316. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20317. EXPECT_GE(s.proxy_hits(), 1);
  20318. EXPECT_EQ(0, s.target_hits());
  20319. }
  20320. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  20321. ProxyAndTargetServers s;
  20322. auto cli = make_client("internal.corp", s);
  20323. cli->set_proxy_basic_auth("u", "p");
  20324. cli->set_no_proxy({"internal.corp"});
  20325. auto res = cli->Get("/");
  20326. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20327. EXPECT_EQ(1, s.target_hits());
  20328. EXPECT_EQ(0, s.proxy_hits());
  20329. EXPECT_FALSE(s.last_had_proxy_authz())
  20330. << "Proxy-Authorization must not be sent direct to the target";
  20331. }
  20332. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  20333. ProxyAndTargetServers s;
  20334. auto cli = make_client("public.example", s);
  20335. cli->set_proxy_basic_auth("u", "p");
  20336. cli->set_no_proxy({"internal.corp"}); // does not match
  20337. auto res = cli->Get("/");
  20338. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20339. EXPECT_GE(s.proxy_hits(), 1);
  20340. EXPECT_TRUE(s.last_had_proxy_authz());
  20341. }
  20342. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  20343. ProxyAndTargetServers s;
  20344. auto cli = make_client("anything.test", s);
  20345. auto res = cli->Get("/");
  20346. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20347. EXPECT_GE(s.proxy_hits(), 1);
  20348. EXPECT_EQ(0, s.target_hits());
  20349. }
  20350. TEST(NoProxyTest, PortSpecificEntryRejected) {
  20351. ProxyAndTargetServers s;
  20352. auto cli = make_client("example.com", s);
  20353. cli->set_no_proxy({"example.com:8080"});
  20354. auto res = cli->Get("/");
  20355. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20356. EXPECT_GE(s.proxy_hits(), 1);
  20357. EXPECT_EQ(0, s.target_hits());
  20358. }
  20359. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  20360. ProxyAndTargetServers s;
  20361. auto cli = make_client("anything.test", s);
  20362. cli->set_no_proxy({"", " ", "\t"});
  20363. auto res = cli->Get("/");
  20364. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20365. EXPECT_GE(s.proxy_hits(), 1);
  20366. EXPECT_EQ(0, s.target_hits());
  20367. }
  20368. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  20369. // An entry with leading/trailing whitespace must still match — env-style
  20370. // values are commonly pasted with stray spaces and an implementation
  20371. // that feeds the raw token directly to inet_pton would fail to match
  20372. // valid CIDRs because of the spaces.
  20373. ProxyAndTargetServers s;
  20374. Client cli("127.0.0.1", s.target_port());
  20375. cli.set_proxy("127.0.0.1", s.proxy_port());
  20376. cli.set_no_proxy({" 127.0.0.0/8 "});
  20377. auto res = cli.Get("/");
  20378. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20379. EXPECT_EQ(0, s.proxy_hits());
  20380. EXPECT_EQ(1, s.target_hits());
  20381. }
  20382. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  20383. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  20384. // go direct and must NOT carry Proxy-Authorization.
  20385. std::atomic<int> proxy_hits{0};
  20386. std::atomic<int> target_hits{0};
  20387. std::atomic<bool> target_saw_authz{false};
  20388. no_proxy_test::ScopedServer proxy_mock, target;
  20389. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  20390. proxy_hits++;
  20391. res.status = 302;
  20392. res.set_header("Location", "http://127.0.0.1:" +
  20393. std::to_string(target.port()) + "/landed");
  20394. });
  20395. target.svr().Get(".*", [&](const Request &req, Response &res) {
  20396. target_hits++;
  20397. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  20398. res.set_content("direct", "text/plain");
  20399. });
  20400. proxy_mock.listen();
  20401. target.listen();
  20402. Client cli("public.example", target.port());
  20403. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  20404. cli.set_proxy("127.0.0.1", proxy_mock.port());
  20405. cli.set_proxy_basic_auth("u", "p");
  20406. cli.set_no_proxy({"127.0.0.1"});
  20407. cli.set_follow_location(true);
  20408. auto res = cli.Get("/redir");
  20409. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20410. EXPECT_GE(proxy_hits.load(), 1);
  20411. EXPECT_GE(target_hits.load(), 1);
  20412. EXPECT_FALSE(target_saw_authz.load());
  20413. }
  20414. #ifdef CPPHTTPLIB_SSL_ENABLED
  20415. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  20416. // Direct origin replying 407 must not trigger the digest retry; otherwise
  20417. // proxy creds would be sent to the (possibly hostile) origin.
  20418. std::atomic<int> target_hits{0};
  20419. std::atomic<bool> target_saw_proxy_authz{false};
  20420. no_proxy_test::ScopedServer target;
  20421. target.svr().Get(".*", [&](const Request &req, Response &res) {
  20422. target_hits++;
  20423. if (req.has_header("Proxy-Authorization")) {
  20424. target_saw_proxy_authz = true;
  20425. }
  20426. res.status = StatusCode::ProxyAuthenticationRequired_407;
  20427. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  20428. "nonce=\"abc\", algorithm=MD5");
  20429. });
  20430. target.listen();
  20431. // The proxy address is set to the target's port: the bypass MUST kick in;
  20432. // if it doesn't, the test still routes "via proxy" to the same server and
  20433. // the Proxy-Authorization assertion below catches the leak.
  20434. Client cli("evil.example", target.port());
  20435. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  20436. cli.set_proxy("127.0.0.1", target.port());
  20437. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  20438. cli.set_no_proxy({"evil.example"});
  20439. auto res = cli.Get("/x");
  20440. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20441. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  20442. EXPECT_EQ(1, target_hits.load());
  20443. EXPECT_FALSE(target_saw_proxy_authz.load());
  20444. }
  20445. #endif
  20446. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  20447. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  20448. std::atomic<int> proxy_hits{0};
  20449. std::atomic<int> bypass_hits{0};
  20450. std::atomic<bool> proxy_saw_c_url{false};
  20451. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  20452. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  20453. proxy_hits++;
  20454. if (req.path.find("/start") != std::string::npos) {
  20455. res.status = 302;
  20456. res.set_header("Location", "http://127.0.0.1:" +
  20457. std::to_string(bypass_server.port()) +
  20458. "/middle");
  20459. return;
  20460. }
  20461. if (req.path.find("/end") != std::string::npos) {
  20462. proxy_saw_c_url = true;
  20463. res.set_content("c-via-proxy", "text/plain");
  20464. return;
  20465. }
  20466. res.set_content("unexpected", "text/plain");
  20467. });
  20468. // public.example's "advertised" port is arbitrary (the request never lands
  20469. // there — it goes through the proxy), but use a dynamic value to stay
  20470. // friendly with sharded parallel runs.
  20471. int public_port = bypass_server.port();
  20472. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  20473. bypass_hits++;
  20474. res.status = 302;
  20475. res.set_header("Location", "http://public.example:" +
  20476. std::to_string(public_port) + "/end");
  20477. });
  20478. proxy_mock.listen();
  20479. bypass_server.listen();
  20480. Client cli("public.example", public_port);
  20481. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  20482. cli.set_proxy("127.0.0.1", proxy_mock.port());
  20483. cli.set_no_proxy({"127.0.0.1"});
  20484. cli.set_follow_location(true);
  20485. auto res = cli.Get("/start");
  20486. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20487. EXPECT_EQ(StatusCode::OK_200, res->status);
  20488. EXPECT_EQ("c-via-proxy", res->body);
  20489. EXPECT_GE(proxy_hits.load(), 2);
  20490. EXPECT_GE(bypass_hits.load(), 1);
  20491. EXPECT_TRUE(proxy_saw_c_url.load());
  20492. }
  20493. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  20494. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  20495. // request reconnects to the correct endpoint.
  20496. std::atomic<int> proxy_hits{0};
  20497. std::atomic<int> target_hits{0};
  20498. no_proxy_test::ScopedServer proxy_mock, target;
  20499. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  20500. proxy_hits++;
  20501. res.set_content("via-proxy", "text/plain");
  20502. });
  20503. target.svr().Get(".*", [&](const Request &, Response &res) {
  20504. target_hits++;
  20505. res.set_content("direct", "text/plain");
  20506. });
  20507. proxy_mock.listen();
  20508. target.listen();
  20509. Client cli("public.example", target.port());
  20510. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  20511. cli.set_proxy("127.0.0.1", proxy_mock.port());
  20512. cli.set_keep_alive(true);
  20513. auto res1 = cli.Get("/a");
  20514. ASSERT_TRUE(res1);
  20515. EXPECT_EQ("via-proxy", res1->body);
  20516. EXPECT_EQ(1, proxy_hits.load());
  20517. EXPECT_EQ(0, target_hits.load());
  20518. cli.set_no_proxy({"public.example"});
  20519. auto res2 = cli.Get("/b");
  20520. ASSERT_TRUE(res2);
  20521. EXPECT_EQ("direct", res2->body);
  20522. EXPECT_EQ(1, proxy_hits.load());
  20523. EXPECT_EQ(1, target_hits.load());
  20524. }
  20525. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  20526. namespace proxy_tunnel_test {
  20527. // SSLServer counterpart to no_proxy_test::ScopedServer.
  20528. class ScopedSSLServer {
  20529. public:
  20530. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  20531. port_ = svr_.bind_to_any_port("127.0.0.1");
  20532. }
  20533. ~ScopedSSLServer() {
  20534. svr_.stop();
  20535. if (th_.joinable()) { th_.join(); }
  20536. }
  20537. SSLServer &svr() { return svr_; }
  20538. int port() const { return port_; }
  20539. void listen() {
  20540. th_ = std::thread([this] { svr_.listen_after_bind(); });
  20541. svr_.wait_until_ready();
  20542. }
  20543. private:
  20544. SSLServer svr_;
  20545. std::thread th_;
  20546. int port_ = 0;
  20547. };
  20548. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  20549. class ScopedConnectProxy {
  20550. public:
  20551. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  20552. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  20553. if (listen_fd_ < 0) { return; }
  20554. int yes = 1;
  20555. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  20556. sockaddr_in a{};
  20557. a.sin_family = AF_INET;
  20558. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  20559. a.sin_port = 0;
  20560. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  20561. return;
  20562. }
  20563. socklen_t alen = sizeof(a);
  20564. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  20565. 0) {
  20566. return;
  20567. }
  20568. port_ = ntohs(a.sin_port);
  20569. if (::listen(listen_fd_, 1) != 0) { return; }
  20570. th_ = std::thread([this] { run(); });
  20571. }
  20572. ~ScopedConnectProxy() {
  20573. stop_ = true;
  20574. if (listen_fd_ >= 0) {
  20575. ::shutdown(listen_fd_, SHUT_RDWR);
  20576. ::close(listen_fd_);
  20577. }
  20578. if (th_.joinable()) { th_.join(); }
  20579. }
  20580. int port() const { return port_; }
  20581. int connect_hits() const { return connect_hits_.load(); }
  20582. private:
  20583. void run() {
  20584. while (!stop_.load()) {
  20585. fd_set rfds;
  20586. FD_ZERO(&rfds);
  20587. FD_SET(listen_fd_, &rfds);
  20588. timeval tv{0, 100 * 1000};
  20589. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  20590. if (sel <= 0) { continue; }
  20591. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  20592. if (client_fd < 0) { continue; }
  20593. std::string req;
  20594. char buf[2048];
  20595. while (req.find("\r\n\r\n") == std::string::npos) {
  20596. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  20597. if (n <= 0) { break; }
  20598. req.append(buf, static_cast<size_t>(n));
  20599. }
  20600. if (req.compare(0, 7, "CONNECT") != 0) {
  20601. ::close(client_fd);
  20602. continue;
  20603. }
  20604. connect_hits_++;
  20605. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  20606. ::send(client_fd, ok, std::strlen(ok), 0);
  20607. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  20608. sockaddr_in o{};
  20609. o.sin_family = AF_INET;
  20610. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  20611. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  20612. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  20613. 0) {
  20614. ::close(client_fd);
  20615. ::close(origin_fd);
  20616. continue;
  20617. }
  20618. auto forward = [](int from, int to) {
  20619. char b[8192];
  20620. for (;;) {
  20621. ssize_t n = ::recv(from, b, sizeof(b), 0);
  20622. if (n <= 0) { break; }
  20623. ssize_t off = 0;
  20624. while (off < n) {
  20625. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  20626. if (s <= 0) {
  20627. off = n;
  20628. break;
  20629. }
  20630. off += s;
  20631. }
  20632. }
  20633. ::shutdown(to, SHUT_WR);
  20634. };
  20635. std::thread t1([&] { forward(client_fd, origin_fd); });
  20636. std::thread t2([&] { forward(origin_fd, client_fd); });
  20637. t1.join();
  20638. t2.join();
  20639. ::close(client_fd);
  20640. ::close(origin_fd);
  20641. }
  20642. }
  20643. int forward_port_ = -1;
  20644. int listen_fd_ = -1;
  20645. int port_ = 0;
  20646. std::thread th_;
  20647. std::atomic<bool> stop_{false};
  20648. std::atomic<int> connect_hits_{0};
  20649. };
  20650. } // namespace proxy_tunnel_test
  20651. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  20652. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  20653. // retry; otherwise proxy creds would be sent to the origin.
  20654. std::atomic<int> origin_hits{0};
  20655. std::atomic<bool> origin_saw_proxy_authz{false};
  20656. proxy_tunnel_test::ScopedSSLServer origin;
  20657. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  20658. origin_hits++;
  20659. if (req.has_header("Proxy-Authorization")) {
  20660. origin_saw_proxy_authz = true;
  20661. }
  20662. res.status = StatusCode::ProxyAuthenticationRequired_407;
  20663. res.set_header("Proxy-Authenticate",
  20664. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  20665. "algorithm=MD5");
  20666. });
  20667. origin.listen();
  20668. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  20669. ASSERT_NE(0, proxy.port());
  20670. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  20671. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  20672. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  20673. // and answer with its own status, making this test flaky.
  20674. SSLClient cli("127.0.0.1", origin.port());
  20675. cli.enable_server_certificate_verification(false);
  20676. cli.set_proxy("127.0.0.1", proxy.port());
  20677. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  20678. auto res = cli.Get("/x");
  20679. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20680. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  20681. EXPECT_EQ(1, origin_hits.load());
  20682. EXPECT_FALSE(origin_saw_proxy_authz.load());
  20683. EXPECT_EQ(1, proxy.connect_hits());
  20684. }
  20685. #endif